Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set session variable spring mvc 3

How can I set a session object which I can use then in any of my views by using ${variable} or ${requestScope.variable}

To be able to use sessions do I need to set <%@ page session="true" %> ?

like image 722
Gandalf StormCrow Avatar asked May 09 '11 15:05

Gandalf StormCrow


1 Answers

If you want to access a session variable in your view the easiest way to do it is :

${sessionScope.yourVariable} 

See the Using Scope Objects for more info.

If you set <%@ page session="true"> then the JSP will merge the session scope and at the page scope into a single namespace. Then you can do:

${yourVariable}

You can put something into the session in a mvc controller like this:

@RequestMapping("/test")
@Controller
public class TestController {
    @RequestMapping(method = RequestMethod.GET)
    public String testMestod(HttpServletRequest request)
    {
        request.getSession().setAttribute("testVariable", "Test Values!!");
        return "testJsp";
    }
}

Finally, the @SessionAttribute is meant for a specifc use case, and doesn't put variables into the session so that anyone can access them:

Here is how the spring folks describe the functionality of @SessionAttribute:

The @SessionAttributes works in the same way as the sessionForm of the SimpleFormController. It puts the command (or for the @SessionAttributes any object) in the session for the duration between the first and the last request (most of the time the initial GET and the final POST). After that the stuff is removed.

Each Controller has it's own ModelMap so something put as a @SessionAttributes in controller1 isn't available in controller2 and vice versa. For that to work you will have to put stuff on the session manually yourself.

like image 199
Karthik Ramachandran Avatar answered Oct 30 '22 01:10

Karthik Ramachandran