Spring注释@SessionAttributes如何工作

时间:2015-07-10 20:23:42

标签: java spring spring-mvc

我是Spring的新手,所以如果我的问题显得愚蠢,请原谅我。

我无法让@SessionAttributes(以及@ModelAttribute)在我的Spring控制器中工作。我究竟做错了什么?这是代码......

@Controller
@SessionAttributes("myAttribute")
public class MyController {

@ModelAttribute("myAttribute")
public String createMySessionAttribute() {
    System.out.println("Inside of createMySessionAttribute");
    return new String("mySessionAttribute");
}

//......

@RequestMapping("/doSomething.do")
public ModelAndView doSomething(HttpSession session, HttpServletRequest request) {

    String sessionAttribute = (String)session.getAttribute("myAttribute");
    String requestAttribute = (String)request.getAttribute("myAttribute");
    String requestSessionAttribute = (String)request.getSession().getAttribute("myAttribute");

    System.out.println(" sessionAttribute = " + sessionAttribute
            + "; requestAttribute = " + requestAttribute
            + "; requestSessionAttribute = " + requestSessionAttribute 
            );


    ModelAndView modelAndView = new ModelAndView("nextPage");

    return modelAndView;
}
}

这是输出......

Inside of createMySessionAttribute
sessionAttribute = null; requestAttribute = null; requestSessionAttribute = null 

我期待......

Inside of createMySessionAttribute
sessionAttribute = mySessionAttribute; requestAttribute = mySessionAttribute; requestSessionAttribute = mySessionAttribute

请注意,我尝试从请求中检索属性,会话和请求中的seeion(这可能是多余的)

由于

1 个答案:

答案 0 :(得分:0)

在请求结束之前,它不会将值放入会话中。

如果您想在myAttribute方法中使用doSomething的值,请执行以下操作:

/* It should have been called @WriteModelAttribute when used like this */
@ModelAttribute("myAttribute")
String writeModelAttribute() {
    return "myAttribute value";
}

/* It should have been called @ReadModelAttribute when used like this */
ModelAndView doSomething(@ModelAttribute("myAttribute") String myAttribute) {
   System.out.println(myAttribute);  //=myAttribute value
   ...
}

请参阅@ModelAttribute annotation, when to use it?