Spring MVC @SessionAttribute 使用

来源:互联网 发布:linux中etc是什么意思 编辑:程序博客网 时间:2024/05/21 14:29

默认情况下SpringMVC将模型中的数据存储到request域中。当一个请求结束后,数据就失效了。如果要跨页面使用。那么需要使用到session。而@SessionAttributes注解就可以使得模型中的数据存储一份到session域中。

@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Inherited@Documentedpublic @interface SessionAttributes {   @AliasFor("names")   String[] value() default {};   @AliasFor("value")   String[] names() default {};   Class<?>[] types() default {};}

1、names:这是一个字符串数组。里面应写需要存储到session中数据的名称。
2、types:根据指定参数的类型,将模型中对应类型的参数存储到session中。
3、value:其实和names是一样的。

若希望在多个请求之间共用某个模型属性数据,则可以在控制器类上(只能是)标注一个@SessionAttributes,SpringMVC

将在模型中对应的属性暂存到HttpSession中。

@Controller@SessionAttributes(value = {"person"})public class Test {    @RequestMapping(value = "/test")    public String test(Model model)  {        Person person = new Person("lgh", 24);        model.addAttribute("person", person);        System.out.println("test");        return "success";    }}
<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head>    <title>success</title></head><body>    <h1>requestScope.person:${requestScope.person}</h1>    <h1>sessionScope.person:${sessionScope.person}</h1></body></html>
当我们没有标注@SessionAttributes注解的时候,只会输出:
requestScope.person:Person{name='lgh', age=24}
sessionScope.person:

标注@SessionAttributes才会显示:

requestScope.person:Person{name='lgh', age=24}
sessionScope.person:Person{name='lgh', age=24}

@SessionAttributes(value = {"person"})
model.addAttribute("person", person);

的类型值必须匹配,才可以放在session中。


@SessionAttributes除了可以通过属性名指定需要放到会话中的属性外(value={"", ""}),还可以通过模型属性的对象类型指定哪些模型属性需要

放到会话中(type={String.class, int.class})。

@Controller@SessionAttributes(types = {Person.class})public class Test {    @RequestMapping(value = "/test")    public String test(Model model)  {        Person person = new Person("lgh", 24);        model.addAttribute("person", person);        System.out.println("test");        return "success";    }}

value匹配键,type对应值的类型。


可以将ModelMap中的属性绑定到请求处理方法的入参中。

@Controller@SessionAttributes(value = {"person"}, types = {Person.class})public class Test {    @RequestMapping(value = "/test")    public String test(ModelMap model)  {        Person person = new Person("lgh", 24);        model.addAttribute("person", person);        System.out.println("test");        return "success";    }    @RequestMapping("/test2")    public void test2(Writer out, @ModelAttribute("person") Person person) throws IOException {        if (person != null) {            out.write(person.toString());        } else {            out.write("person is null");        }        out.close();    }}

0 0
原创粉丝点击