What is @ModelAttribute in Spring MVC?

后端 未结 13 1017
一个人的身影
一个人的身影 2020-11-22 08:43

What is the purpose and usage of @ModelAttribute in Spring MVC?

13条回答
  •  独厮守ぢ
    2020-11-22 09:36

    Take any web application whether it is Gmail or Facebook or Instagram or any other web application, it's all about exchanging data or information between the end user and the application or the UI and the back end application. Even in Spring MVC world there are two ways to exchange data:

    1. from the Controller to the UI, and
    2. from the UI to the Controller.

    What we are interested here is how the data is communicated from the UI to Controller. This can also be done in 2 ways:

    1. Using an HTML Form
    2. Using Query Parameters.

    Using an HTML Form: Consider the below scenario,

    When we submit the form data from the web browser, we can access that data in our Controller class as an object. When we submit an HTML form, the Spring Container does four things. It will,

    1. first read all the data that is submitted that comes in the request using the request.getParameter method.
    2. once it reads them, it will convert them into the appropriate Java type using integer.parseInt, double.parseDouble and all the other parse methods that are available based on the data type of the data.
    3. once parsed, it will create a object of the model class that we created. For example, in this scenario, it is the user information that is being submitted and we create a class called User, which the Container will create an object of and it will set all the values that come in automatically into that object.
    4. it will then handover that object by setting the values to the Controller.

    To get this whole thing to work, we'll have to follow certain steps.

    We first need to define a model class, like User, in which the number of fields should exactly match the number of fields in the HTML form. Also, the names that we use in the HTML form should match the names that we have in the Java class. These two are very important. Names should match, the number of fields in the form should match the number of fields in the class that we create. Once we do that, the Container will automatically read the data that comes in, creates an object of this model, sets the values and it hands it over to the Controller. To read those values inside the Controller, we use the @ModelAttribute annotation on the method parameters. When we create methods in the Controller, we are going to use the @ModelAttribute and add a parameter to it which will automatically have this object given by the Container.

    Here is an example code for registering an user:

    @RequestMapping(value = "registerUser", method = RequestMethod.POST)
    public String registerUser(@ModelAttribute("user") User user, ModelMap model) {
        model.addAttribute("user", user);
        return "regResult";
    }
    

    Hope this diagrammatic explanation helped!

提交回复
热议问题