Spring MVC Pass model data to view method summary __spring

Source: Internet
Author: User
Summary of methods in Spring MVC passing model data to view

In general, there are 4 ways to pass model data to a view

1, Modelandview

Requirement: Processing method return value type is Modelandview. In the method body we add the model data through the Modelandview object.

2, Model/map/modelmap

Requirements: When the processing method returns using Org.springframework.ui.Model, Org.springframework.ui.ModelMap, or JAVA.UTI.MAP as the entry for the processing method, The data in the map is automatically added to the model, which is described later.

3, @SessionAttributes

Use this annotation to annotate a class so that a property in the model is staged to httpsession so that the property can be shared among multiple requests.

4, @ModelAttribute

The annotation can be annotated on a method with a return value, a method with no return value, and an annotation on the method entry, and when the annotation is entered, the object of the argument is placed in the data model, which is described later.

The following will be described in the form of an example. Modelandview

1, create Modelandview, and pass in model data

    @Controller public
    class Hellocontroller {

        @RequestMapping (value =/testmodelandview.do), method = requestmethod.get) Public
        Modelandview Testmodelandview () {
            String viewName = "Hello";//view name
            Modelandview Modelandview = new Modelandview (viewName);

            Modelandview.addobject ("Time", New Date ());
            Modelandview.addobject ("name", "Modelandview");
            Return Modelandview
        }
    }

The processing method returns a Modelandview object and adds data with "time" and "name" as key in the method body.

2, write JSP

Write the name: "Hello.jsp", which reads as follows:

    

In this way, in the browser input: localhost:8080/testmodelandview.do, you can see the following output results:

Attention:
Requestscope.time, {requestscope.time}, {requestscope.get ("Time")},${time} These three kinds of writing effects are the same, in different books/blogs see is one of them. 2, Model/map/modelmap

Spring MVC creates an implied model object as a storage container for model data before invoking the method.

If the method's entry parameter is a MAP or model type, Spring MVC passes a reference to the implied model to those parameters. In the method body, we can access all the data in the model through this parameter object, or we can add new attribute data to the model.

Model and map Use the same basic, specific implementation code as shown in the following figure.

    @RequestMapping (value = "/testmodel.do", method = requestmethod.get) public
    String Testmodel (model model) {
        Model.addattribute ("Time", New Date ());
        Model.addattribute ("name", "Model");
        return "Hello";
    }

    @RequestMapping (value = "/testmap.do", method = requestmethod.get) public
    String TestMap (map<string,object> Map) {
        map.put ("Time", New Date ());
        Map.put ("name", "Map");
        return "Hello";
    }

The code above corresponds to the same hello.jsp as the hello.jsp above Modelandview.

The test is validated to work correctly. 3, @SessionAttributes

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

Note: @SessionAttributes This annotation can only be placed above the class

The following code is: first use map to save the model data to the model object, and then use @sessionattributes at the class definition to copy to the session

    @SessionAttributes ({"Name", "Time"})
    @Controller the public
    class Hellocontroller {

        @RequestMapping (value = "/testsessionattribute.do", method = requestmethod.get) public
        String Testsessionattribute (map<string,object > map) {
            map.put ("Time", New Date ());
            Map.put ("name", "Sessionattribute");
            return "Sessionattribute";
        }

    

The contents of sessionattribute.jsp are as follows:

    

In this way, in the browser input: localhost:8080/testsessionattribute.do, you can see the following output results:

4, @ modelattribute

As mentioned earlier, SPRINGMVC creates an implied instance object of model type each time the request processing method is invoked. If you are ready to use this instance, you can add a model type input parameter to the method. In fact, you can also use the Add @modelattribute annotation type in the method to access the model instance.

You can annotate method parameters with @modelattribute: Methods with @modelattribute annotations add the parameter objects that they enter or create to the model object (if not explicitly added in the method).

You can annotate a @modelattribute processing method (with return value, no return value): The method that is @modelattribute annotated is executed before each method executes controller. 4.1 @ modelattribute Annotation on a method that has a return value

@ Modelattribute Note The return value is added to the model object on a method that has a return value.

    @ModelAttribute Public
    user addUser (user user) {//
        user.setname (' Model Attribute in Mehtod ', this method has return value ");
        return user;

    }
    @RequestMapping (value = "/testmodelattributeinreturnvaluemethod.do", method = requestmethod.get) public
    String Testmodelattributeinreturnvaluemethod () {return
        "Modelattributeinrvmethod";
    }

Even if the method body of the AddUser method does not show the model data in the modeling, it will help us complete the addition because of the use of the @modelattribute annotation.

The contents of modelattributeinrvmethod.jsp are as follows:

    

The test results are as follows:

There is also a point to note: Return the user object, the name of the model property is not specified, it is implicitly represented by the return type, such as this method returns the user type, then the Model property name is user, so, in the JSP file as above, you can use the User.Name to access, if you specify the name of the property, such as: @ModelAttribute (value= "MyUser"), you will need to use {User.Name} in the JSP to access, if you specify the name of the property, For example: @ModelAttribute (value= "MyUser"), you need to use {Myuser.name} in the JSP to access

Look at an example of specifying a property name:

     /**
     * Object Merge Specify Object name
     *
    /@RequestMapping (value = "/testmodelattribute4.do", method = Requestmethod.get)
    Public String testModelAttribute4 (@ModelAttribute ("myuser") User user {
    //Change the object User in the Model object
        User.setage (20 );
        return "ModelAttribute4";

    }
    @ModelAttribute (value = "myuser")//Specifies the name of the object and adds it to the Model object public
    user MyUser () {
        User user = new user ();
        User.setname ("Wojiushimogui");
        return user;
    }

The corresponding JSP file contents are as follows:

    

The test results are as follows:

4.2 @ModelAttribute annotation on the method of void return value

@ModelAttribute annotation on the method of void return value, the added model data to be displayed to the model object when the annotation is different from the method with the return value.

    /**
     * @ModelAttribute Note void return value method
     *
    /@ModelAttribute public
    void AddUser (User User,model Model) {
        user.setname ("Model Attribute in Mehtod, this method is not return  value");
        Model.addattribute ("user", user);

    }
    @RequestMapping (value = "/testmodelattributeinnonreturnvaluemethod.do", method = requestmethod.get) public
    String Testmodelattributeinnonreturnvaluemethod () {return
        "Modelattributeinnonrvmethod";
    }

The content of modelattributeinnonrvmethod.jsp is exactly the same as the content of modelattributeinrvmethod.jsp, which is no longer posted here.

The results of the operation are as follows:

Interestingly, if you are in a controller Hellocontroller.java file (see below), there is a @modelattribute annotation on a method that has a return, a note on the Void return value method, and the model data name that is included in the models is consistent. What will happen? Look at the following program code

    @Controller public
    class Hellocontroller {
        /**
         * @modelattribute annotation on a method that has a return value,
         * * 
         * *
        Modelattribute public
        User addUser (user user) {
            user.setname ("Model Attribute in Mehtod", this method has return VA Lue ");
            return user;

        }
        /**
         * @ModelAttribute annotation void return value method
         *
        /@ModelAttribute public
        void AddUser (User user,model Model {
            user.setname ("Model Attribute in Mehtod, this method is not return  value");
            Model.addattribute ("user", user);
        }
        @RequestMapping (value = "/testmodelattributeinreturnvaluemethod.do", method = requestmethod.get) public
        String Testmodelattributeinreturnvaluemethod () {return
            "Modelattributeinrvmethod";
        }

    }

The results of the operation are:

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.