Understanding Spring MVC Model Attribute and Session Attribute

Source: Internet
Author: User
Tags java web

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.
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".

  @Controllerpublic class Mycontroller {@ModelAttribute ("myrequestobject") public Mycommandbean Addstufftorequestscope () {System.out.println ("Inside of Addstufftorequestscope"); Mycommandbean bean = new Mycommandbean ("Hello World"); return bean;} @RequestMapping ("/dosomething") public String Requesthandlingmethod (model model, HttpServletRequest request) { System.out.println ("Inside of DoSomething handler method"); 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 ("= = = Request Data = = ="); java.util.Enumeration reqenum = Request.getattributenames (); while ( Reqenum.hasmoreelements ()) {String s = reqenum.nextelement (); System.out.println (s); System.out.println ("= =" + Request.getattribute (s));} return "NextPage";} ... 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.

  Inside of Addstufftorequestscopeinside of DoSomething handler method---Model data---myrequestobject--mycom Mandbean [Somestring=hello World, somenumber=42]=== Request data = = = Org.springframework.web.servlet.dispatcherservlet.theme_source==webapplicationcontext for namespace ' Dispatcher-servlet ': startup date [Sun Oct 21:40:56 CDT 2013]; Root of context hierarchyorg.springframework.web.servlet.dispatcherservlet.theme_resolver[email protected] 48corg.springframework.web.servlet.dispatcherservlet.context==webapplicationcontext for namespace ' Dispatcher-servlet ': startup date [Sun Oct 21:40:56 CDT 2013]; Root of context hierarchyorg.springframework.web.servlet.handlermapping.pathwithinhandlermapping== dosomething.requestorg.springframework.web.servlet.handlermapping.bestmatchingpattern==/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.

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).

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.

在 index.jsp 和 nextpage.jsp 中,我添加了额外的 JSP 代码块,使其显示 HttpSession attributes。

I use the @SessionAttributes annotation mycontroller so that it will be the same model

attributes(myRequestObject)放入 Spring session 中。@Controller@SessionAttributes("myRequestObject")public class MyController { ...}

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

  @SuppressWarnings ("Rawtypes") @RequestMapping ("/dosomething") public String Requesthandlingmethod (Model Model, HttpServletRequest request, HttpSession session) {System.out.println ("Inside of DoSomething handler method"); 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 ("= = = Request Data = = ="); java.util.enumeration<string> reqenum = Request.getattributenames (); while (Reqenum.hasmoreelements ()) {String s = reqenum.nextelement (); System.out.println (s); System.out.println ("= =" + Request.getattribute (s)); } System.out.println ("Session Data * * *"); Enumeration<string> e = Session.getattributenames (); while (E.hasmoreelements ()) {String s = e.nextelement (); System.out.println (s); SYSTEM.OUT.PRINTLN ("* *" + session.getattribute (s)); } return "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.

@RequestMapping("/endsession")public String nextHandlingMethod2(SessionStatus status){ status.setComplete(); return "lastpage";}

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.
Thank you for reading, like small articles can be concerned about the article, the small series will not be updated regularly oh

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.