springmvc--Processing a data model

Source: Internet
Author: User

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 entry is Org.springframework.ui.Model, Org.springframework.ui.ModelMap, or JAVA.UTI.MAP, when the processing method returns, The data in the map 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
First, Modelandview

1. Add Model data:

    • Moelandview AddObject (String attributename, Objectattributevalue)
    • Modelandview Addallobject (map<string,?> modelmap)

2. Set the view:

    • void Setview (view view)
    • void Setviewname (String viewName)

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

/*** The return value of the target method can be a modelandview type.      * This can include view and model information * SPRINGMVC will put the data in the Modelandview model into the request domain object. * @return     */@RequestMapping ("/testmodelandview")     PublicModelandview Testmodelandview () {String viewName=SUCCESS; Modelandview Modelandview=NewModelandview (viewName); //add model data to Modelandview.Modelandview.addobject ("Time",NewDate ()); returnModelandview; }
Ii. Map and model

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

2. Concrete 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;    }
Third, @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
    • @SessionAttributes by the object type of the Model property, in addition to specifying the properties that need to be placed in the session through the property name ( 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 In addition to attributes that      need to be placed in the session by the property name (in effect using the Value property values),     * You can also specify which model properties need to be placed in the session by the object type of the Model property ( is actually using the types property value)     *      * Note: This annotation can only be placed above the class. Instead of decorating the method      . */     @RequestMapping ("/testsessionattributes")    public String Testsessionattributes (map<string, object> Map) {        new User ("Tom", "123456", "[email Protected] ", ();        Map.put ("user", user);        Map.put ("School", "Atguigu");         return SUCCESS;    }
Iv. @ModelAtrtribute
/*** 1. There are @ModelAttribute tagged methods that are called!* 2 by Springmvc before each target method executes. @ModelAttribute annotations can also be used to modify the entry parameter of the target method POJO type, whose Value property values are as follows Function: * 1). SPRINGMVC uses the Value property values to find the corresponding object in the Implicitmodel, and if it exists, it is passed directly into the parameter of the target method. * 2). SPRINGMVC will take value as key, and the object of type POJO is value, which is deposited into request.*/@ModelAttribute Public voidGetUser (@RequestParam (value= "id", required=false) Integer ID, Map<string, object>map) {System.out.println ("Modelattribute Method"); if(id! =NULL){            //To simulate getting an object from the databaseUser User =NewUser (1, "Tom", "123456", "[email protected]", 12); System.out.println ("Get an object from the database:" +user); Map.put ("User", user); } }/** * running Flow: * 1. To perform a method of @ModelAttribute annotation decoration: Remove the object from the database and put the object in the Map. The key is: User * 2. Springmvc the user object from the MAP and assigns the request parameter of the form to the corresponding property of the user object. * 3. SPRINGMVC Pass the above object to 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! * * SPRINGMVC determine the target method POJO type into the parameters of the process * *. Determine a key: * *). If the parameter of the POJO type of the target method is used @ModelAttribute as a modifier, the key is the first letter of the POJO class name, lowercase *). If the @ModelAttribute is used to decorate, the key is the value of the @ModelAttribute annotation. * *. Find the corresponding object of key in Implicitmodel, and if present, pass in as input parameter. If you have saved the Map in the method of @ModelAttribute tag, and the key is the same as the key determined by the first step, you will get it. . If no key corresponding object exists in the Implicitmodel, check whether the current Handler uses the @SessionAttributes annotation 
* adornment, if the annotation is used, and the value of the @SessionAttributes annotation A key is included in the value of the attribute, and the value of the value corresponding to the key is obtained from the HttpSession
*, and if present, it is passed directly into the parameter of the target method. If it does not exist, an exception will be thrown. If the Handler is not identified @SessionAttrib Utes the value of the annotation or @SessionAttributes annotation does not contain a key,
* will create a parameter of type POJO by reflection, passing in the parameter of the target method. SPRINGMVC will save the key and POJO type objects to Implicitmodel, which will then be saved to the request. */@RequestMapping ("/testmodelattribute") PublicString Testmodelattribute (@ModelAttribute ("user") user user) {System.out.println ("Modify:" +user); returnSUCCESS;}

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.