[spring-mvc] How to use Session attributes in Spring-mvc

Could you help me write spring mvc style analog of this code?

 session.setAttribute("name","value");

And how to add an element that is annotated by @ModelAttribute annotation to session and then get access to it?

This question is related to spring-mvc session servlets

The answer is


SessionAttribute annotation is the simplest and straight forward instead of getting session from request object and setting attribute. Any object can be added to the model in controller and it will stored in session if its name matches with the argument in @SessionAttributes annotation. In below eg, personObj will be available in session.

@Controller
@SessionAttributes("personObj")
public class PersonController {

    @RequestMapping(value="/person-form")
    public ModelAndView personPage() {
        return new ModelAndView("person-page", "person-entity", new Person());
    }

    @RequestMapping(value="/process-person")
    public ModelAndView processPerson(@ModelAttribute Person person) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("person-result-page");

        modelAndView.addObject("pers", person);
        modelAndView.addObject("personObj", person);

        return modelAndView;
    }

}

Use @SessionAttributes

See the docs: Using @SessionAttributes to store model attributes in the HTTP session between requests

"Understanding Spring MVC Model And Session Attributes" also gives a very good overview of Spring MVC sessions and explains how/when @ModelAttributes are transferred into the session (if the controller is @SessionAttributes annotated).

That article also explains that it is better to use @SessionAttributes on the model instead of setting attributes directly on the HttpSession because that helps Spring MVC to be view-agnostic.


The below annotated code would set "value" to "name"

@RequestMapping("/testing")
@Controller
public class TestController {
@RequestMapping(method = RequestMethod.GET)
public String testMestod(HttpServletRequest request){
    request.getSession().setAttribute("name", "value");
    return "testJsp";
  }
}

To access the same in JSP use ${sessionScope.name}.

For the @ModelAttribute see this link


Try this...

@Controller
@RequestMapping("/owners/{ownerId}/pets/{petId}/edit")
@SessionAttributes("pet")
public class EditPetForm {

    @ModelAttribute("types")

    public Collection<PetType> populatePetTypes() {
        return this.clinic.getPetTypes();
    }

    @RequestMapping(method = RequestMethod.POST)
    public String processSubmit(@ModelAttribute("pet") Pet pet, 
            BindingResult result, SessionStatus status) {
        new PetValidator().validate(pet, result);
        if (result.hasErrors()) {
            return "petForm";
        }else {
            this.clinic.storePet(pet);
            status.setComplete();
            return "redirect:owner.do?ownerId="
                + pet.getOwner().getId();
        }
    }
}

Isn't it easiest and shortest that way? I knew it and just tested it - working perfect here:

@GetMapping
public String hello(HttpSession session) {
    session.setAttribute("name","value");
    return "hello";
}

p.s. I came here searching for an answer of "How to use Session attributes in Spring-mvc", but read so many without seeing the most obvious that I had written in my code. I didn't see it, so I thought its wrong, but no it was not. So lets share that knowledge with the easiest solution for the main question.


When I trying to my login (which is a bootstrap modal), I used the @sessionattributes annotation. But problem was when the view is a redirect ("redirect:/home"), values I entered to session shows in the url. Some Internet sources suggest to follow http://docs.spring.io/spring/docs/4.3.x/spring-framework-reference/htmlsingle/#mvc-redirecting But I used the HttpSession instead. This session will be there until you close the browsers. Here is sample code

        @RequestMapping(value = "/login")
        @ResponseBody
        public BooleanResponse login(HttpSession session,HttpServletRequest request){
            //HttpServletRequest used to take data to the controller
            String username = request.getParameter("username");
            String password = request.getParameter("password");

           //Here you set your values to the session
           session.setAttribute("username", username);
           session.setAttribute("email", email);

          //your code goes here
}

You don't change specific thing on view side.

<c:out value="${username}"></c:out>
<c:out value="${email}"></c:out>

After login add above codes to anyplace in you web site. If session correctly set, you will see the values there. Make sure you correctly added the jstl tags and El- expressions (Here is link to set jstl tags https://menukablog.wordpress.com/2016/05/10/add-jstl-tab-library-to-you-project-correctly/)


In Spring 4 Web MVC. You can use @SessionAttribute in the method with @SessionAttributes in Controller level

@Controller
@SessionAttributes("SessionKey")
public class OrderController extends BaseController {

    GetMapping("/showOrder")
    public String showPage(@SessionAttribute("SessionKey") SearchCriteria searchCriteria) {
     // method body
}

Use This method very simple easy to use

HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getNativeRequest();

                                                            request.getSession().setAttribute("errorMsg", "your massage");

in jsp once use then remove

<c:remove var="errorMsg" scope="session"/>      

Examples related to spring-mvc

Two Page Login with Spring Security 3.2.x ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized The type WebMvcConfigurerAdapter is deprecated RestClientException: Could not extract response. no suitable HttpMessageConverter found Spring boot: Unable to start embedded Tomcat servlet container UnsatisfiedDependencyException: Error creating bean with name 8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

Examples related to session

What is the best way to manage a user's session in React? Spring Boot Java Config Set Session Timeout PHP Unset Session Variable How to kill all active and inactive oracle sessions for user Difference between request.getSession() and request.getSession(true) PHP - Session destroy after closing browser Get Current Session Value in JavaScript? Invalidating JSON Web Tokens How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session How can I get session id in php and show it?

Examples related to servlets

Google Recaptcha v3 example demo Difference between request.getSession() and request.getSession(true) init-param and context-param java.lang.NoClassDefFoundError: org/json/JSONObject how to fix Cannot call sendRedirect() after the response has been committed? getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever? Create a simple Login page using eclipse and mysql Spring get current ApplicationContext insert data into database using servlet and jsp in eclipse What is WEB-INF used for in a Java EE web application?