Correct usage of session in Spring MVC < goto >

Source: Internet
Author: User
Tags goto

Spring MVC is a very good framework, and its excellence is inherited from the strong modularity and Dependency of Spring's own Dependency injection (injection), which is designed to reveal ease of use, reusability and ease of integration. The excellent design patterns spread throughout, making the framework even though the learning curve is steep, but once mastered it is addictive. Beginners do not need to know too much about the implementation of the framework, a random search on how to use the "note-based controller" can be used quickly, and some books such as "Spring in Action" also provides a very good choice to get started.

There are a plethora of online posts, Chinese quick start, easy to learn in English. In this way, spring learning is an easy and enjoyable process.

But!!

Most of the information on the use of the session in spring is very secretive. Perhaps the problem is too easy to infer? Most of the information does not include what I will be stating below. For the correct use of the session in spring, it is even recommended to use HttpSession directly. But this approach clearly violates spring's "technology agnostic" (the term I understand means that no matter what specific application you use, a servlet, a local JVM program, or something else, Your controller can be reused).

So I began to search the vast network of resources and books on the correct use of the session and Spring MVC processing session mechanism, which is the most in-depth and clearly considered this article. From the above, and the information I have looked at such as official documents, I can infer a few points:

1. The Spring framework checks the model information after the controller is called, and before rendering the view, and adds the attributes indicated by the @sessionattributes () annotation to the session

2. @ModelAttribute when declaring the parameters of a controller, it can be used to indicate that this parameter refers to an object that exists in the model. If the object already exists in model, the model can have data saved before calling the controller, which should not only be because The Handlerinterceptor or @modelattribute tag method has explicitly added some objects to the model object, and It is important that spring will add some objects to the model by default.

3. If an object already exists in the session, you can directly use Modelattribute to declare the controller's parameters, which can be used directly in the controller.

1 of them are clear, and the article I mentioned is mainly about this. and from 2 and 3 we may be able to boldly launch a conclusion:

Spring will populate the model with the objects in the session before invoking the controller

Because I want to get 3 from 2, this conclusion is more natural. So is that actually the case? Can do a little experiment. Emulating the article I quoted, I wrote the following code:

@Controller @requestmapping ("/user") @SessionAttributes ("UserId")PublicClassUsercontroller {@RequestMapping (value= "/login", method=GET)PublicString Login (IntID, model model, HttpServletRequest request, HttpSession session) {Model.addattribute ("userId"), id); System.out.println (""); System.out.println (""); SYSTEM.OUT.PRINTLN ("Inside Login"); System.out.println (""); SYSTEM.OUT.PRINTLN ("---Model data---"); Map Modelmap =Model.asmap ();For(Object ModelKey:modelMap.keySet ()) {Object Modelvalue =Modelmap.get (Modelkey); System.out.println (Modelkey + "--" +Modelvalue); } System.out.println (""); SYSTEM.OUT.PRINTLN ("* * * Session Data * * * *"); Enumeration<string> e =Session.getattributenames ();While(E.hasmoreelements ()) {String s =E.nextelement (); SYSTEM.OUT.PRINTLN (s + "= =" +Session.getattribute (s)); }Return "/test"; } @RequestMapping (value= "/check", method=GET)PublicString Check (model, HttpServletRequest request, HttpSession session) {System.out.println (""); System.out.println (""); System.out.println ("Inside Check"); System.out.println (""); SYSTEM.OUT.PRINTLN ("---Model data---"); Map modelmap = Model.asmap (); for Modelmap.get (Modelkey); System.out.println (Modelkey + "--" + Modelvalue);} System.out.println (""); System.out.println ("Session Data * * * *"  Session.getattributenames (); while (E.hasmoreelements ()) {String s = E.nextelement (); SYSTEM.OUT.PRINTLN (s + "= =" + Session.getattribute (s));} return "/test" ;}}       

The role of test.jsp is to print out the objects in the session.

The order of the calls is to first ensure that the session is empty, successively enter the following link:

Http://localhost:8080/XX/user/check

Http://localhost:8080/XX/user/login?id=1

Http://localhost:8080/XX/user/check

The results of the page display are:

1

2

3

The results of Tomcat output are:

Inside check

---Model data---

Session Data * * *


Inside login

---Model data---
UserId--1

Session Data * * *


Inside check

---Model data---
UserId--1

Session Data * * *
UserId = = 1

The results are as I expected. First, there is no UserID attribute in the session, and after a controller joins it, the model in the controller is automatically added to the object that already exists in the session. While it is true that many of the posts mention that @sessionattributes is not the correct way to use the session, the result is that it allows the final attribute to be added to the HttpSession object. (There may be more discussion here, and I'd like to have something more convincing that I can use it back to httpsession). So, a relatively comparative "technology agnostic" approach to using the session in spring is:

1 use @sessionattributes hint framework which attributes need to exist in session

2 Add these attributes to the model in some controllers

3 Use these attributes directly in some other controler

4 in other controllers, determine if there is a corresponding attribute in the model to see if this attribute has been registered in the session

Correct usage of session in Spring MVC < goto >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.