Spring中的@ModelAttribute和@SessionAttribute

use*_*456 4 annotations spring-mvc modelattribute

正如Spring规范所说,@ModelAttribute将在映射处理程序之前执行,@SessionAttribute将模型属性保留在会话中。

考虑下面的场景:表单 bean 在控制器被调用后创建,并且也被设置为会话属性。下次调用 MenuController 时,createForm() 将再次执行并创建另一个新的表单 bean。我的问题是:这个最新创建的表单 bean 会被设置为会话属性吗?哪个表单 bean 将绑定到方法 bookList() 中的参数?

希望大家能帮忙。谢谢。

@Controller
@RequestMapping("/store")
@SessionAttribute("form")
public class MenuController {
     @ModelAttribute("form")
     public Form createForm() {
     return new Form();
     }

     @RqeustMapping("/book")
     public String bookList(@ModelAttribute("form") Form form){
     //processing the form
     }
}
Run Code Online (Sandbox Code Playgroud)

Eug*_*yuk 5

当在bookList给定会话中第一次调用该方法时,然后@ModelAttribute('form)调用方法 with,将返回值(Form 对象)存储在中HttpSession,最后bookList使用作为参数传递的相同 Form 对象(从会话获取)来调用该方法。

对于同一个 中的后续请求,Spring 从会话中检索相同的 Form 对象,并且在会话结束之前HttpSession不会再次调用该方法。@ModelAttribute('form')

每次方法调用结束后,bookListSpring 将 Form 对象的更新版本存储在HttpSession.

如果您使用的是 Spring Boot 2.x,您可以调试DefaultSessionAttributeStore#retrieveAttribute方法来了解此行为。