SPRINGMVC Processing a data model

Source: Internet
Author: User
Tags class definition

Working with model data

Spring MVC provides several ways to output the model data:

  Modelandview: The method body can add model data through the object when the processing method returns a value of type Modelandview
  map and Model: When the processing method returns, when the entry is Org.springframework.ui.Model, Org.springframework.ui.ModelMap, or JAVA.UTI.MAP, the map Data is automatically added to the model.
  @SessionAttributes: A property in the model is staged in HttpSession so that the property can be shared between multiple requests
  @ModelAttribute: When the annotation is annotated with a method in the parameter, the object of the entry is placed in the data model

Modelandview

The return value of the controller processing method, if Modelandview, contains both the view information and the model data information.

SPRINGMVC will put the data in the Modelandview model into the request domain object.

To add model data:
Moelandview AddObject (String attributename, Object AttributeValue)
Modelandview Addallobject (map<string,?> modelmap)

To set the view:
void Setview (view view)
void Setviewname (String viewName)

1@RequestMapping ("/testmodelandview")2      PublicModelandview Testmodelandview () {3String ViewName =SUCCESS;4Modelandview Modelandview =NewModelandview (viewName);5         6         //add model data to Modelandview.7Modelandview.addobject ("Time",NewDate ());8         9         returnModelandview;Ten}
ModelandviewMap and Model

Spring MVC internally uses a Org.springframework.ui.Model interface to store model data

Specific steps
Spring MVC creates an implied model object as a storage container for model data before invoking the method.
if the method's incoming parameter is a MAP or model type , Spring MVC passes a reference to the implied model to those arguments. In the body of the method, the developer can access all the data in the model through this entry object, or you can add new attribute data to the model

    /**      * The target method can add parameters to the Map type (which can actually be either the Model type or      the Modelmap type). @param Map      @return     */     @RequestMapping ("/testmap")    public String testmap (map<string, Object> map) {        System.out.println (Map.getclass (). GetName ());         Map.put ("names", Arrays.aslist ("Tom", "Jerry", "Mike"));         return SUCCESS;    }
View Code@SessionAttributes

If you want to share a model property data across multiple requests, you can label a @SessionAttributes on the controller class, and Spring MVC will temporarily save the corresponding properties in the model to HttpSession.

@SessionAttributes you can specify which model properties need to be placed in the session by the object type of the model property, except that you can specify the properties that need to be placed in the session through the property name
@SessionAttributes (types=user.class) adds all attributes of type User.class in the implied model to the session.
@SessionAttributes (value={"user1", "User2"})
@SessionAttributes (Types={user.class, Dept.class})
@SessionAttributes (value={"user1", "User2"}, Types={dept.class})

 /**   * @SessionAttributes except that you can specify the required place by property name The attributes in the conversation (which are actually using the Value property values), * You can also specify which model properties need to be placed into the session by the object type of the model property (actually using the types property value) * Note: The annotation can only be placed above the class.      And can not be modified to put the method.  */  @RequestMapping ( "/ Testsessionattributes ")  public  String Testsessionattributes (map<string, Object> Map) {User user  = new  User ("Tom", "123456", "[email protected]", 15 "user" , user);        Map.put ( "School", "Atguigu" );     return   SUCCESS; }
View Code@ModelAttribute

Use @ModelAttribute annotations on method definitions: Spring MVC calls the method labeled @modelattribute on the method level one by one before invoking the target processing method.
Use @modelattribute annotations before the method's entry:

You can get the object from the suppressed model data in the hidden object, bind the request parameter to the object, and then pass in the
Adding a method-in Parameter object to the model

@ModelAttributepublic void GetUser (@RequestParam (value= "id", required=false) Integer ID, map<string, object> Map {System.out.println ("Modelattribute method"), if (id! = NULL) {//Simulates fetching objects from the database user user = new User (1, "Tom", "123456", "[ Email protected] ", 12); System.out.println ("Get an object from the database:" + user); Map.put ("User", user);}}
@RequestMapping ("/testmodelattribute") public String Testmodelattribute (@ModelAttribute ("user") user user) { System.out.println ("Modified:" + user); return SUCCESS;}

Run the process:

1. Perform @ModelAttribute annotation retouching method: Remove the object from the database and put the object in the Map. Key: User
2. SPRINGMVC removes the user object from the MAP and assigns the request parameter of the form to the corresponding property of the user object.
3. Springmvc the above objects into the parameters of the target method.
Note: In @ModelAttribute decorated method, the key that is placed in the MAP needs to be the same as the first letter lowercase string of the target method into the parameter type!

1         /*process of source code analysis2 * 1. Call the method that @ModelAttribute the annotation adornment. In fact, the data in the Map in @ModelAttribute method is placed in the Implicitmodel.3 * 2. Resolve the target parameter of the request processor, in fact the target parameter is derived from the target property of the Webdatabinder object4 * 1). To create a Webdatabinder object:5 *①. Determine the ObjectName property: If the Attrname property value passed in is "", the ObjectName is the first letter of the class name lowercase.6 * * Note: attrname. If the POJO attribute of the target method is decorated with @ModelAttribute, the Attrname value is @ModelAttribute7 * The Value property values8      * 9 *②. Determine the target property:Ten * > Find attrname corresponding property values in Implicitmodel. If present, OK One * > * If not present: Verify that the current Handler is using @SessionAttributes for decoration, if used, try to A * Gets the property value corresponding to the attrname. If there is no corresponding attribute value in the session, an exception is thrown. - * > If the Handler is not decorated with @SessionAttributes, or if the key specified by value is not used in the @SessionAttributes - * Matches Attrname, the POJO object is created by reflection the      *  - * 2). SPRINGMVC assigns the request parameters of the form to the properties of the Webdatabinder target.  - * 3). *SPRINGMVC will give Webdatabinder's attrname and target to Implicitmodel.  - * Near to the request domain object. + * 4). Pass the target of the webdatabinder as an argument to the parameter of the destination method.  -      */        
source code Analysis processSPRINGMVC the process of determining the target method POJO type entry

1. Identify a key:

1). If the parameter of the POJO type of the target method is used @ModelAttribute as a modifier, the key is the lowercase of the first letter of the POJO class name
2). If the @ModelAttribute is used to decorate, the key is the value of the @ModelAttribute annotation.
2. Find the corresponding object of key in Implicitmodel, if present, pass in as input
1). If you have saved the Map in the method of @ModelAttribute tag, and key and 1 determine the same key, you will get it.
3. If no key corresponding object exists in Implicitmodel, check whether the current Handler uses @SessionAttributes annotation decoration, if the annotation is used, and @SessionAttributes the Value property of the annotation The value contains the key, and the value of the key is obtained from the HttpSession, and if it exists, it is passed directly into the parameter of the target method. An exception will be thrown if it does not exist.
4. If Handler does not have an identifier @SessionAttributes annotation or @SessionAttributes Note that does not contain a key, the parameter of the POJO type is created by reflection and passed in as the parameter of the target method
5. SPRINGMVC will save the key and POJO type objects to the Implicitmodel, which will then be saved to the request.

Exceptions thrown by the @sessionattributes

If @sessionattributes ("xxx") is marked at the processing class definition, an attempt is made to get the property from the session and assign it to the parameter, and then populate the Parameter object with the request message. Throws a Httpsessionrequiredexception exception if the corresponding attribute is not found in the session

SPRINGMVC Processing a data model

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.