@SessionAttributes 只能作用在类上,作用是将指定的Model中的键值对添加至session中,方便在下一次请求中使用。

简单示例

  • 目标是通过 @SessionAttributes 注解将Model中attrName为 "user","age","name" 的值添加至 session 中
 @Controller
@RequestMapping("/testSessionAttribute")
@SessionAttributes(value = {"user","age","name"})
public class TestSessionAttributeController { @ModelAttribute("user")
public User addUser(){
User user = new User();
user.setName("James");
user.setAge(29);
return user;
} @RequestMapping("/testHandler")
public String testHandler(Model model, String age, String name){
16 model.addAttribute("age",age);
17 model.addAttribute("name",name);
System.out.println(age);
System.out.println(name);
return "result";
}
}

对应的jsp代码如下:

 <body>
${sessionScope.user.age}
${sessionScope.user.name}
<br/>
${sessionScope.age}
${sessionScope.name}
</body>

通过实例可以得出一下结论:

  1. 不论是利用@ModelAttribute添加至model的数据,还是手动添加至model的数据,均遵循 @SessionAttributes 的规则

清除@SessionAttributes向session中添加的值

如果需要清除通过@SessionAttribute添加至 session 中的数据,则需要在controller 的 handler method中添加 SessionStatus参数,在方法体中调用SessionStatus#setComplete。

需要注意的是,此时清除的只是该Controller通过@SessionAttribute添加至session的数据(当然,如果不同controller的@SessionAttribute拥有相同的值,则也会清除)

@Controller
@RequestMapping("/testSessionAttribute")
@SessionAttributes(value = {"user","age","name"})
public class TestSessionAttributeController { .......................... @RequestMapping("/removeSessionAttributes")
public String removeSessionAttributes(SessionStatus sessionStatus){
sessionStatus.setComplete();
return "result";
}
}

通过@ModelAttributes和@SessionAttributes共同添加至session中的数据,只会添加一次

在没用使用SessionStatus清除过之前,通过@ModelAttributes和@SessionAttributes共同添加至session中的数据并不会更新,如下例:

 @Controller
@RequestMapping("/testSessionAttribute")
@SessionAttributes(value = {"user","age","name"})
public class TestSessionAttributeController { public static int age = 29;
@ModelAttribute("user")
public User addUser(){
User user = new User();
user.setName("James");
user.setAge(age++);
return user;
} @RequestMapping("/testHandler")
public String testHandler(Model model, String age, String name){
model.addAttribute("age",age);
model.addAttribute("name",name);
System.out.println(age);
System.out.println(name);
return "result";
} }
 <body>
${sessionScope.user.age}
${sessionScope.user.name}
<br/>
${sessionScope.age}
${sessionScope.name}
</body>

第一次请求:http://localhost:8080/testSessionAttribute/testHandler.action?name=James&age=29

结果:

29 James 
29 James

第二次请求:http://localhost:8080/testSessionAttribute/testHandler.action?name=James&age=30

29 James 
30 James

原因是,在org.springframework.web.bind.annotation.support.HandlerMethodInvoker#invokeHandlerMethod中进行了如下操作:

 public final Object invokeHandlerMethod(Method handlerMethod, Object handler,
NativeWebRequest webRequest, ExtendedModelMap implicitModel) throws Exception { Method handlerMethodToInvoke = BridgeMethodResolver.findBridgedMethod(handlerMethod);
try {
boolean debug = logger.isDebugEnabled();
for (String attrName : this.methodResolver.getActualSessionAttributeNames()) {
8 Object attrValue = this.sessionAttributeStore.retrieveAttribute(webRequest, attrName);
9 if (attrValue != null) {
10 implicitModel.addAttribute(attrName, attrValue);
11 }
}
for (Method attributeMethod : this.methodResolver.getModelAttributeMethods()) {
Method attributeMethodToInvoke = BridgeMethodResolver.findBridgedMethod(attributeMethod);
Object[] args = resolveHandlerArguments(attributeMethodToInvoke, handler, webRequest, implicitModel);
if (debug) {
logger.debug("Invoking model attribute method: " + attributeMethodToInvoke);
}
String attrName = AnnotationUtils.findAnnotation(attributeMethod, ModelAttribute.class).value();
20 if (!"".equals(attrName) && implicitModel.containsAttribute(attrName)) {
21 continue;
22 }
ReflectionUtils.makeAccessible(attributeMethodToInvoke);
Object attrValue = attributeMethodToInvoke.invoke(handler, args);
if ("".equals(attrName)) {
Class<?> resolvedType = GenericTypeResolver.resolveReturnType(attributeMethodToInvoke, handler.getClass());
attrName = Conventions.getVariableNameForReturnType(attributeMethodToInvoke, resolvedType, attrValue);
}
if (!implicitModel.containsAttribute(attrName)) {
implicitModel.addAttribute(attrName, attrValue);
}
}
Object[] args = resolveHandlerArguments(handlerMethodToInvoke, handler, webRequest, implicitModel);
if (debug) {
logger.debug("Invoking request handler method: " + handlerMethodToInvoke);
}
ReflectionUtils.makeAccessible(handlerMethodToInvoke);
return handlerMethodToInvoke.invoke(handler, args);
}
catch (IllegalStateException ex) {
// Internal assertion failed (e.g. invalid signature):
// throw exception with full handler method context...
throw new HandlerMethodInvocationException(handlerMethodToInvoke, ex);
}
catch (InvocationTargetException ex) {
// User-defined @ModelAttribute/@InitBinder/@RequestMapping method threw an exception...
ReflectionUtils.rethrowException(ex.getTargetException());
return null;
}
}

如8-11行所示,在执行被@ModelAttributes注解的方法前,会将上一次通过@SessionAttributes添加至session中的数据添加添加至model中;

第20-22行,在执行被@ModelAttributes注解的方法前,springMVC会判断model中是否已经包含了@ModelAttributes给出的attrName,如果包含,则被@ModelAttributes注解的方法则不再执行

SpringMVC @SessionAttributes 使用的更多相关文章

  1. SpringMVC @SessionAttributes注解

    @SessionAttributes 注解只能作用到类上 @SessionAttributes(value={"user"},types={String.class}) @Sess ...

  2. SpringMVC SessionAttributes 简述

    使用SpringMVC时,我们会发现网络上有关SessionAttributes注解的内容非常少,更多的人甚至推荐你继续用HttpServletRequest中的session管理方法来控制Sessi ...

  3. SpringMVC @SessionAttributes 使用详解以及源码分析

    @sessionattributes @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Inherited @Docum ...

  4. SpringMVC中的常用注解

    RequestParam 作用: 用于  将请求参数区数据  映射到  功能处理方法的参数上. 属性: value  请求参数中的名称 required   请求参数中是否必须提供此参数. 默认值: ...

  5. SpringMVC实例及注解(二)

    @RequestMapping()除了修饰方法,还可以修饰类1.类定义处:提供初步的请求映射信息.相对于WEB应用的根目录2.方法处:提供进一步的细分映射信息.相对于类定义处的URL.若类定义处未标注 ...

  6. Spring MVC 学习笔记(二)

    6. 视图和视图解析器  ❤  Spring MVC如何解析视图                                  • 请求处理方法执行完成后,最终返回一个ModelAndView对象 ...

  7. Spring MVC 学习笔记(一)

    • 1.SpringMVC概述 • 2.SpringMVC的HelloWorld • 3.使用@RequestMapping映射请求 • 4.映射请求参数&请求头 • 5.处理模型数据 • 6 ...

  8. 在SpringMVC中使用@SessionAttributes和@ModelAttribute将数据存储在session域中

    今天在我的springMVC项目--图书管理系统中,希望在登录时将登录的Users存在session中,开始是准备在controller中使用Servlet API中的对象,可是一直无法引用,不知道为 ...

  9. SpringMVC(十六) 处理模型数据之SessionAttributes

    @SessionAttributes原理 默认情况下Spring MVC将模型中的数据存储到request域中.当一个请求结束后,数据就失效了.如果要跨页面使用.那么需要使用到session.而@Se ...

随机推荐

  1. strlen的容易tle情况

    for(int i=1;i<=strlen(**);i++ 这很容易tle 因为 strlen很大 int m=strlen(**)

  2. 如何在Qt Creator中添加库文件和头文件目录

    在使用QtCreator开发图像处理程序的时候想加入Opencv库来处理图形,添加头文件,需要编辑工程文件夹下的.pro文件在文件中添加以下内容,即可包含头文件的文件夹: INCLUDEPATH += ...

  3. mysql导出CSV格式的文件

    select  *  from  Account  into outfile "/tmp/haha.csv" fields terminated by ',' lines term ...

  4. 授人以鱼不如授人以渔——和女儿学一起学成语

    女儿二年级了,前段时间背了<小学生必背古诗词75首>,采用几天一篇,然后滚动复习这种方式.磕磕绊绊也把一本古诗背了一遍,效果吗?是有的,但是不怎么明显,前面背,后面忘.当然这是规律,难免的 ...

  5. SkylineGlobe MFC C++ 开发示例代码

    SkylineGlobe的SDK底层是跨平台的C++内核,面向不同平台封装原生的API,具有很高的执行效率, 下面是C++二次开发时的示例代码: #import "D:\Program Fi ...

  6. 分析网络流量Capsa笔记

    Capsa是一款网络分析仪,允许您监控网络流量,解决网络问题并分析数据包.通过提供生动的图表,通过设计良好的GUI提供丰富的统计信息和实时警报,Capsa可让IT管理员实时识别,诊断和解决有线和无线网 ...

  7. 【持续更新中···】Linux下的小技巧

    1.Linux回到上级文件的命令: cd ..回到上一级目录(注意:cd 和..中间有空格) cd ~回到home目录 cd -回到某一目录

  8. 重磅|0元学 Python运维开发,别再错过了

    51reboot 运维开发又双叒叕的搞活动了,鉴于之前 51reboot 的活动反馈,每次活动结束后(或者已经结束了很长时间)还有人在问活动的事情.这一次小编先声明一下真的不想在此次活动结束后再听到类 ...

  9. 五年.net程序员Java学习之路

    大学毕业后笔者进入一家外企,做企业CRM系统开发,那时候开发效率最高的高级程序语言,毫无疑问是C#.恰逢公司也在扩张,招聘了不少.net程序员,笔者作为应届生,也乐呵呵的加入到.net程序员行列中. ...

  10. Gitlab备份和恢复操作记录

    前面已经介绍了Gitlab环境部署记录,这里简单说下Gitlab的备份和恢复操作记录: 1)Gitlab的备份目录路径设置 [root@code-server ~]# vim /etc/gitlab/ ...