"Translating" Understanding Spring MVC Model Attribute and Session Attribute

Source: Internet
Author: User

As a Java Web application developer, you have quickly learned the request (HttpServletRequest) and session (HttpSession) scopes. When designing and building Java WEB applications, it is important to understand these scopes and how to interact with objects and those scopes. "There is an article on StackOverflow that will help you quickly understand the request and session scope"

SPRING MVC Scope

When I started writing Web apps with spring MVC, I found that spring model and session attribute were a bit cryptic, especially when they interacted with the HTTP request and session scopes I knew. Can a Spring model element be found in my session or request? If that's the case, how do I control it? In this article, I want to explain how Spring MVC's model and session work.

SPRING's @MODELATTRIBUTE

There are several ways to add data or objects to Spring's model. In general, data or objects are added to the Spring model by a note from the controller layer. In the following example, use the @ModelAttribute to add an instance named Mycommandbean to the model with the key value "Myrequestobject".

1  Public classMycontroller {2  3@ModelAttribute ("Myrequestobject")4      PublicMycommandbean Addstufftorequestscope () {5System.out.println ("Inside of Addstufftorequestscope");6Mycommandbean Bean =NewMycommandbean ("Hello World", 42);7         returnBean;8     }9  Ten@RequestMapping ("/dosomething") One      PublicString Requesthandlingmethod (model model, HttpServletRequest request) { ASystem.out.println ("Inside of DoSomething handler method"); -   -SYSTEM.OUT.PRINTLN ("---Model data---"); theMap Modelmap =Model.asmap (); -          for(Object modelKey:modelMap.keySet ()) { -Object Modelvalue =Modelmap.get (modelkey); -System.out.println (Modelkey + "--" +modelvalue); +         } -   +System.out.println ("= = = Request Data = = ="); AJava.util.Enumeration Reqenum =request.getattributenames (); at          while(Reqenum.hasmoreelements ()) { -String s =reqenum.nextelement (); - System.out.println (s); -System.out.println ("= =" +Request.getattribute (s)); -         } -   in         return"NextPage"; -     } to   +          //... the rest of the controller -}

In a request that arrives, any method that is @ModelAttribute annotated will be called before the Controller handler method (as in the example above Requesthandlingmethod). These methods will be used to add data to a JAVA.UTIL.MAP before handler method executes and then join the Spring model. It can be shown with a sample operation. I created two JSP pages: index.jsp and nextpage.jsp. A link on index.jsp is used to send a request to the Requesthandlingmethod () application trigger in Mycontroller. In the above code, Requesthandlingmethod () returns "NextPage" as the logical name of the next view, which in this case is handled as nextpage.jsp.

When this small URL is modified to this form, the controller's SYSTEM.OUT.PRINTLN shows how the @ModelAttribute method was executed before handler. It also shows the process that Mycommandbean creates and joins the Spring model and is available in handler method.

1 Inside of Addstufftorequestscope2 Inside of DoSomething handler method3---Model data---4Myrequestobject-Mycommandbean [Somestring=hello World, somenumber=42]5= = = Request Data = =6 Org.springframework.web.servlet.DispatcherServlet.THEME_SOURCE7==webapplicationcontext forNamespace ' Dispatcher-servlet ': startup date [Sun Oct 21:40:56 CDT 2013]; Root of context Hierarchy8 Org.springframework.web.servlet.DispatcherServlet.THEME_RESOLVER9==[Email protected]cTen Org.springframework.web.servlet.DispatcherServlet.CONTEXT One==webapplicationcontext forNamespace ' Dispatcher-servlet ': startup date [Sun Oct 21:40:56 CDT 2013]; Root of context Hierarchy A org.springframework.web.servlet.HandlerMapping.pathWithinHandlerMapping -==dosomething.request - Org.springframework.web.servlet.HandlerMapping.bestMatchingPattern the==/dosomething.* - Org.springframework.web.servlet.DispatcherServlet.LOCALE_RESOLVER -==[email protected]18fd23e4

Now the question becomes, "Where is the Spring model's data stored?" "Is it stored in a standard Java request scope?" The answer is--yes ... In the end, then. As you can read from the above output, Mycommandbean is in the model, but when handler method executes it is not in the Request object. Indeed, Spring did not add the model data as attribute to the request after handler method was executed and the next view (in this case, nextpage.jsp) was displayed.

It can also be shown by the attribute of the output stored in the index.jsp and nextpage.jsp HttpServletRequest. I've placed a JSP code block on all two pages (as shown below) to show HttpServletRequest's attribute.

123<%4Java. UTIL. Enumeration<string> Reqenum =REQUEST. Getattributenames ();5 While (Reqenum. hasMoreElements ()) {6STRING S =Reqenum. Nextelement ();7 Out . PRINT (S);8Out. PRINTLN ("= =" +REQUEST. GetAttribute (S));9%><br/>Ten<% One     } A%>

When the app starts, index.jsp loads and you can see there is no attribute in the request scope.

In this example, when "do something" is clicked, the Mycontroller handler method is executed, and then the nextpage.jsp is redirected and displayed. The same JSP code block has been written in nextpage.jsp, which also provides the attribute in the request scope. Look, when nextpage.jsp renders, it shows that the Mycommandbean model created in the controller is added to the httpservletrequest scope! The key value "Myrequestobject" of the Spring model attribute is copied and used as the key value of the request attribute.

So before the next view is rendered, the Spring model data has been copied to HttpServletRequest before the handler method executes (or between).

Reasons for using SPRING MODEL and REQUEST

You may wonder why Spring uses model attribute. Why not just add the data to the request object? I found the answer in the book "Professional Java Development with the Spring Framework" from Rod Johnson and others. This book is a bit outdated about the spring API (based on Spring 2.0), but I found that the book provides some extended explanations for the operation of the spring engine. Here is a reference to the model element part of the book:

Adding elements directly to the HttpServletRequest (like request attributes) looks like it is serving the same goal. The reason for this is to be more explicit when you see the requirements that we set for the MVC framework. It should be as relevant as possible to the view, which means that we can merge the view technology and not be bound by HttpServletRequest.

SPRING's @SESSIONATTRIBUTES

So now you know how Spring manages model data, and how to connect standard Http request attribute data. So what about Spring's session data?

The Spring @SessionAttribute is used in the controller to specify which model attributes needs to be stored in the session. In fact, the Spring document declares @SessionAttributes annotations "listing the model attributes names that need to be explicitly stored in the session or in some of the interactive storage spaces. "In other words," Some of the interactive storage space "indicates that Spring MVC is trying to maintain a design concept that is not associated with technology.

In fact, what @SessionAttributes allows you to do is tell Spring which model attributes will be copied to HttpSession before the view is displayed. This can also be demonstrated with a short code.

In index.jsp and nextpage.jsp, I added additional JSP code blocks to display the HttpSession attributes.

12<%3Java. UTIL. Enumeration<string> Sessenum =REQUEST. GetSession ()4     . Getattributenames ();5 While (Sessenum. hasMoreElements ()) {6STRING S =Sessenum. Nextelement ();7 Out . PRINT (S);8Out. PRINTLN ("= =" +REQUEST. GetSession (). GetAttribute (S));9%><br/>Ten<% One   } A%>

I use the @SessionAttributes annotation mycontroller to put the same model attributes (Myrequestobject) into the Spring session.

1 @CONTROLLER 2 @SESSIONATTRIBUTES ("Myrequestobject")3publicCLASS mycontroller {4   ... 5 }

In addition, add code in the controller's handler method to display the attributes in the HttpSession (as shown in HttpServletRequest attributes).

1@SUPPRESSWARNINGS ("Rawtypes")2@REQUESTMAPPING ("/dosomething")3 Public STRING Requesthandlingmethod (model model, HttpServletRequest REQUEST, HTTPSESSION SESSION) {4SYSTEM. Out. PRINTLN ("INSIDE of dosomething HANDLER METHOD");5 6SYSTEM. Out. PRINTLN ("---MODEL DATA---");7MAP Modelmap =MODEL. Asmap ();8 For (OBJECT Modelkey:modelmap. KEYSET ()) {9OBJECT Modelvalue =Modelmap. GET (Modelkey);TenSYSTEM. Out. PRINTLN (Modelkey + "--" +modelvalue); One   } A  -SYSTEM. Out. PRINTLN ("= = = REQUEST DATA = = ="); -Java. UTIL. Enumeration<string> Reqenum =REQUEST. Getattributenames (); the While (Reqenum. hasMoreElements ()) { -STRING S =Reqenum. Nextelement (); - SYSTEM. Out. PRINTLN (S); -SYSTEM. Out. PRINTLN ("= =" +REQUEST. GetAttribute (S)); +   } -  +SYSTEM. Out. PRINTLN ("* * * SESSION DATA * * * *"); AEnumeration<string> E =SESSION. Getattributenames (); at While (E.hasmoreelements ()) { -STRING S =e.nextelement (); - SYSTEM. Out. PRINTLN (S); -SYSTEM. Out. PRINTLN ("* *" +SESSION. GetAttribute (S)); -   } -  inRETURN "NEXTPAGE"; -}

Now that we can see the addition of @SessionAttributes annotations, Spring MVC processes the session object before, during, and after an HTTP request. The results are shown below. First, when index.jsp is displayed (before the request is sent and processed by Spring MVC), we can see that both HttpServletRequest and HttpSession have no attribute data.

Handler method executes (Requesthandlingmethod), you can see that Mycommandbean is added to the Spring model attributes, but has not yet joined HttpServletRequest or HttpSession scope.

But when handler method executes and nextpage.jsp is displayed, you can see that the Model attribute data (Mycommandbean) has been copied as a attribute to HttpServletRequest and HttpSession (with the same attribute key).

Control SESSION ATTRIBUTES

Now you understand how the Spring model and session attribute data are added into HttpServletRequest and HttpSession. Maybe you're starting to care about managing the data in the Spring session. Spring provides a way to remove the Spring session attributes and also remove it from the HttpSession (no need to delete the entire HttpSession). Simply add a Spring Sessionstatus object as a parameter to a controller handler method. In this method, use the Sessionstatus object to end the Spring session.

1 @REQUESTMAPPING ("/endsession") 2 public STRING NEXTHANDLINGMETHOD2 (sessionstatus status) {3   status. SetComplete (); 4   RETURN "LastPage"; 5}
Summarize

Hopefully this article will help you understand Spring model and session attributes. This is not magical, just a question of understanding how HttpSession and HttpServletRequest store the Spring model and session attributes. I have put the displayed code on the Intertech Web site. If you are interested in continuing to explore and understand Spring model and session, download it here.

If you are interested in learning more about Spring (or any kind of Java technology), consider registering now and becoming a member of Intertech. Learn more here and register here.

Original link: Intertech
Starting at Importnew, Link: http://www.importnew.com/16782.html

"Translating" Understanding Spring MVC Model Attribute and Session Attribute

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.