[Translation] Understand Spring MVC Model Attribute, Session Attribute, and mvcattribute

Source: Internet
Author: User

[Translation] Understand Spring MVC Model Attribute, Session Attribute, and mvcattribute

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 very important to understand these scopes and how to interact data with objects with these scopes. [There is an article on StackOverflow that helps you quickly understand request and session scopes]

Spring mvc Scope

When I started to write Web applications using Spring MVC, I found Spring model and session attribute a little mysterious, especially when they interact with the well-known HTTP request and session scope. Can a Spring model element be found in my session or request? If so, how can I control it? In this article, I want to explain how Spring MVC model and session work.

@ MODELATTRIBUTE of SPRING

There are several ways to add data or objects to the Spring model. Generally, data or objects are added to the Spring model through an annotation at the controller layer. In the following example, use @ ModelAttribute to add an instance named MyCommandBean to a model with the key value "myRequestObject.

 1 public class MyController { 2   3     @ModelAttribute("myRequestObject") 4     public MyCommandBean addStuffToRequestScope() { 5         System.out.println("Inside of addStuffToRequestScope"); 6         MyCommandBean bean = new MyCommandBean("Hello World",42); 7         return bean; 8     } 9  10     @RequestMapping("/dosomething")11     public String requestHandlingMethod(Model model, HttpServletRequest request) {12         System.out.println("Inside of dosomething handler method");13  14         System.out.println("--- Model data ---");15         Map modelMap = model.asMap();16         for (Object modelKey : modelMap.keySet()) {17             Object modelValue = modelMap.get(modelKey);18             System.out.println(modelKey + " -- " + modelValue);19         }20  21         System.out.println("=== Request data ===");22         java.util.Enumeration reqEnum = request.getAttributeNames();23         while (reqEnum.hasMoreElements()) {24             String s = reqEnum.nextElement();25             System.out.println(s);26             System.out.println("==" + request.getAttribute(s));27         }28  29         return "nextpage";30     }31  32          //  ... the rest of the controller33 }

In a received request, any method annotated by @ ModelAttribute will be called before the controller handler method (just like requestHandlingMethod in the preceding example ). These methods add the data to a java. util. Map before the handler method is executed, and then add the data to the Spring model. You can use an example. 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 logic name of the next view. In this example, it is processed as nextpage. jsp.

When this small URL is modified to this form, the controller's System. out. println shows how the @ ModelAttribute method is executed before the handler method. It also shows how MyCommandBean creates and adds Spring model and is available in handler method.

 1 Inside of addStuffToRequestScope 2 Inside of dosomething handler method 3 --- Model data --- 4 myRequestObject -- MyCommandBean [someString=Hello World, someNumber=42] 5 === Request data === 6 org.springframework.web.servlet.DispatcherServlet.THEME_SOURCE 7 ==WebApplicationContext for namespace 'dispatcher-servlet': startup date [Sun Oct 13 21:40:56 CDT 2013]; root of context hierarchy 8 org.springframework.web.servlet.DispatcherServlet.THEME_RESOLVER 9 ==org.springframework.web.servlet.theme.FixedThemeResolver@204af48c10 org.springframework.web.servlet.DispatcherServlet.CONTEXT11 ==WebApplicationContext for namespace 'dispatcher-servlet': startup date [Sun Oct 13 21:40:56 CDT 2013]; root of context hierarchy12 org.springframework.web.servlet.HandlerMapping.pathWithinHandlerMapping13 ==dosomething.request14 org.springframework.web.servlet.HandlerMapping.bestMatchingPattern15 ==/dosomething.*16 org.springframework.web.servlet.DispatcherServlet.LOCALE_RESOLVER17 ==org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver@18fd23e4

 

Now the question is changed to "where is the Spring model data stored ?』 Is it stored in the standard Java request scope? The answer is -- right... In the end. As you read from the above output, MyCommandBean is in the model, but it is not in the request object when handler method is executed. Indeed, after the handler method is executed, no model data is added to the request as the attribute until the next view (nextpage. jsp in this example) is displayed.

You can also display the attribute stored in HttpServletRequest of index. jsp and nextpage. jsp. I have deployed a JSP code block on both pages (as shown below) to display the attribute of HttpServletRequest.

 1 

 

When the application is started and index. jsp is loaded, you can see that there is no attribute in the request scope.

In this example, when "do something" is clicked, execute the handler method of MyController, and then jump to and display nextpage. jsp. The same jsp code block has been written in nextpage. JSP, and the attribute in the request scope is also provided. When nextpage. jsp is rendered, the MyCommandBean model created in the controller is added to the HttpServletRequest scope! The key value "myRequestObject" of Spring model attribute is copied and used as the key value of request attribute.

Therefore, before the next view is rendered, the Spring model data has been copied to HttpServletRequest before the handler method is executed (or.

Reasons for using spring model and REQUEST

You may want to know why Spring uses model attribute. Why not add data directly to the request object? I found the answer in the Professional Java Development with the Spring Framework book by Rod Johnson and others. The Spring API part of this book is somewhat outdated (written based on Spring 2.0), but I found it provides some extensions for Spring engine running. The reference of the model element in the book is as follows:

Adding an element directly to HttpServletRequest (like request attributes) Looks like a target in the service. The reason for doing so is to be clearer when we see the requirements we set for the MVC framework. It should be unrelated to the view as much as possible, which means that we can combine the view technology without being bound by HttpServletRequest.

@ SESSIONATTRIBUTES of SPRING

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

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 the @ SessionAttributes annotation "lists the names of model attributes in a session or interactive bucket that need to be explicitly stored .』 In addition, "some interactive buckets" indicate that Spring MVC tries to maintain a design idea unrelated to the technology.

In fact, what @ SessionAttributes allows you to do is to tell Spring which model attributes will be copied to HttpSession together before the view is displayed. You can also use a short code to demonstrate this.

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

 1 

 

I used @ SessionAttributes to annotate MyController and put the same model attributes (myRequestObject) into Spring session.

1 @Controller2 @SessionAttributes("myRequestObject")3 public class MyController {4   ...5 }

 

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

 1 @SuppressWarnings("rawtypes") 2 @RequestMapping("/dosomething") 3 public String requestHandlingMethod(Model model, HttpServletRequest request, HttpSession session) { 4   System.out.println("Inside of dosomething handler method"); 5   6   System.out.println("--- Model data ---"); 7   Map modelMap = model.asMap(); 8   for (Object modelKey : modelMap.keySet()) { 9     Object modelValue = modelMap.get(modelKey);10     System.out.println(modelKey + " -- " + modelValue);11   }12  13   System.out.println("=== Request data ===");14   java.util.Enumeration<String> reqEnum =         request.getAttributeNames();15   while (reqEnum.hasMoreElements()) {16     String s = reqEnum.nextElement();17     System.out.println(s);18     System.out.println("==" + request.getAttribute(s));19   }20  21   System.out.println("*** Session data ***");22   Enumeration<String> e = session.getAttributeNames();23   while (e.hasMoreElements()){24     String s = e.nextElement();25     System.out.println(s);26     System.out.println("**" + session.getAttribute(s));27   }28  29   return "nextpage";30 }

Now, we can see that after @ SessionAttributes annotation is added, Spring MVC processes session objects before, between, and after an HTTP request. The result is 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.

When handler method is executed (requestHandlingMethod), you can see that MyCommandBean is added to Spring model attributes, but it has not been added to the HttpServletRequest or HttpSession scope.

However, when handler method is executed and nextpage. jsp is displayed, you can see that model attribute data (MyCommandBean) has been copied to HttpServletRequest and HttpSession (with the same attribute key) as an attribute ).

Control SESSION ATTRIBUTES

Now you have understood how to add Spring model and session attribute data to HttpServletRequest and HttpSession. You may be concerned about how to manage data in Spring sessions. Spring provides a method to remove Spring session attributes and also remove it from HttpSession (you do not need to delete the entire HttpSession ). Add a Spring SessionStatus object as a parameter to a controller handler method. In this method, use the SessionStatus object to end this Spring session.

1 @RequestMapping("/endsession")2 public String nextHandlingMethod2(SessionStatus status){3   status.setComplete();4   return "lastpage";5 }

 

Summary

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

If you are interested in studying Spring (or any Java Technology) in depth, you can register immediately to become a member of Intertech. Learn more and register here.

Original article: Intertech
Starting at importnew

Related Article

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.