相关注解
@SessionAttribute:标注在方法的参数上,读取session中的数据
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SessionAttribute {
@AliasFor("name")
String value() default "";
@AliasFor("value")
String name() default "";
boolean required() default true;
}
@SessionAttributes:标注在类上,向session中添加数据
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface SessionAttributes {
@AliasFor("names")
String[] value() default {};
@AliasFor("value")
String[] names() default {}; //将数据模型中指定名称的数据存储在session中
Class<?>[] types() default {}; //将数据模型中指定类型的数据存储在session中
}
示例
***************
controller 层
HelloController
@RestController
@SessionAttributes(names = {"name2"},types = {Person.class})
public class HelloController {
@RequestMapping("/hello4")
public String hello4(HttpSession session){
session.setAttribute("name","瓜田李下");
return "success 4";
}
@RequestMapping("/hello5")
public ModelAndView hello5(){
ModelAndView mv=new ModelAndView();
mv.setView(new MappingJackson2JsonView());
mv.addObject("name2","海贼王");
Person person=new Person();
person.setName("瓜田李下");
person.setAge(20);
mv.addObject("person",person);
return mv;
}
@RequestMapping("/hello6")
public String hello6(@SessionAttribute("name") String name,@SessionAttribute("name2") String name2,@SessionAttribute("person") Person person){
System.out.println(name);
System.out.println(name2);
System.out.println(person);
return "success 6";
}
}
使用测试
依次调用/hello4、/hello5、/hello6
瓜田李下
海贼王
Person(name=瓜田李下, age=20)