What is @ModelAttribute in Spring MVC?

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

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

相关标签:
13条回答
  • 2020-11-22 09:21

    The ModelAttribute annotation is used as part of a Spring MVC Web application and can be used in two scenarios.

    First of all, it can be used to inject data into a pre-JSP load model. This is especially useful in ensuring that a JSP is required to display all the data itself. An injection is obtained by connecting one method to the model.

    Second, it can be used to read data from an existing model and assign it to the parameters of the coach's method.

    refrence https://dzone.com/articles/using-spring-mvc%E2%80%99s

    0 讨论(0)
  • 2020-11-22 09:23

    @ModelAttribute simply binds the value from jsp fields to Pojo calss to perform our logic in controller class. If you are familiar with struts, then this is like populating the formbean object upon submission.

    0 讨论(0)
  • 2020-11-22 09:24

    So I will try to explain it in simpler way. Let's have:

    public class Person {
        private String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(final String name) {
            this.name = name;
        }
    }
    

    As described in the Spring MVC documentation - the @ModelAttribute annotation can be used on methods or on method arguments. And of course we can have both use at the same time in one controller.

    1.Method annotation

    @ModelAttribute(“cities”)
     public List<String> checkOptions(){
     return new Arrays.asList(new[]{“Sofia”,”Pleven","Ruse”});//and so on
    }
    

    Purpose of such method is to add attribute in the model. So in our case cities key will have the list new Arras.asList(new[]{“Sofia”,”Pleven","Ruse”}) as value in the Model (you can think of Model as map(key:value)). @ModelAttribute methods in a controller are invoked before @RequestMapping methods, within the same controller.

    Here we want to add to the Model common information which will be used in the form to display to the user. For example it can be used to fill a HTML select:

    2.Method argument

    public String findPerson(@ModelAttriute(value="person") Person person) {
        //..Some logic with person
        return "person.jsp";
    }
    

    An @ModelAttribute on a method argument indicates the argument should be retrieved from the model. So in this case we expect that we have in the Model person object as key and we want to get its value and put it to the method argument Person person. If such does not exists or (sometimes you misspell the (value="persson")) then Spring will not find it in the Model and will create empty Person object using its defaults. Then will take the request parameters and try to data bind them in the Person object using their names.

    name="Dmitrij"&countries=Lesoto&sponsor.organization="SilkRoad"&authorizedFunds=&authorizedHours=&
    

    So we have name and it will be bind to Person.name using setName(String name). So in

    //..Some logic with person
    

    we have access to this filled name with value "Dimitrij".

    Of course Spring can bind more complex objects like Lists, Maps, List of Sets of Maps and so on but behind the scene it makes the data binding magic.

    1. We can have at the same time model annotated method and request method handler with @ModelAttribute in the arguments. Then we have to union the rules.

    2. Of course we have tons of different situations - @ModelAttribute methods can also be defined in an @ControllerAdvice and so on...

    0 讨论(0)
  • 2020-11-22 09:31

    @ModelAttribute can be used as the method arguments / parameter or before the method declaration. The primary objective of this annotation to bind the request parameters or form fields to an model object

    Ref. http://www.javabeat.net/modelattribute-spring-mvc/

    0 讨论(0)
  • 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!

    0 讨论(0)
  • 2020-11-22 09:37

    @ModelAttribute refers to a property of the Model object (the M in MVC ;) so let's say we have a form with a form backing object that is called "Person" Then you can have Spring MVC supply this object to a Controller method by using the @ModelAttribute annotation:

    public String processForm(@ModelAttribute("person") Person person){
        person.getStuff();
    }
    

    On the other hand the annotation is used to define objects which should be part of a Model. So if you want to have a Person object referenced in the Model you can use the following method:

    @ModelAttribute("person")
    public Person getPerson(){
        return new Person();
    }
    

    This annotated method will allow access to the Person object in your View, since it gets automatically added to the Models by Spring.

    See "Using @ModelAttribute".

    0 讨论(0)
提交回复
热议问题