2

I am new to Spring so please forgive me if my question seems dumb.

I am unable to get @SessionAttributes (along with @ModelAttribute) to work in my Spring controller. What am I doing wrong? Here is the code ...

@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;
}
}

and here is the output...

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

I expected ...

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

Note that I tried retrieving the attribute from the request, the session, and the seesion from the request (which is probably redundant)

Thanks

martind
  • 21
  • 2

1 Answers1

0

It won't put the value into session until the end of the request.

If you want to use the value of myAttribute in your doSomething method, do this:

/* 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
   ...
}

See @ModelAttribute annotation, when to use it?

Community
  • 1
  • 1
Neil McGuigan
  • 46,580
  • 12
  • 123
  • 152