简体   繁体   中英

Some information about annoting a method parameter with @ModelAttribute in Spring MVC

I am studying on the Spring MVC Showcase project, dowlodable from STS dashboard

I have the following situation that is not completly clear for me:

I have the following form:

<form id="readForm"action="<c:url value="/messageconverters/form" />" method="post">
        <input id="readFormSubmit"type="submit"value="Read Form Data"/>             
</form>

Related to the submit action of a form having id="readForm" I have the following Jquery function that simply execute an AJAX call hadding to the body field of the request two valorized textual variables: **foo=bar and fruit=apple

$("#readForm").submit(function() {
    var form = $(this); // Contiene il riferimento all'elemento form submittato 

    // Contiene il riferimento all'emento input all'interno del form (il bottone)
    var button = form.children(":first");

    $.ajax({ 
        type: "POST",               // Tipo di Request: POST 
        // URL specificato dall'attributo "action" del form: "/messageconverters/form" 
        url: form.attr("action"),   
        // Dati che vengono passati all'interno del campo body dell'HTTP Request, 2 variabili
        data: "foo=bar&fruit=apple", 

        // Tipo di media type accettabile dalla response
        contentType: "application/x-www-form-urlencoded", 
        dataType: "text", // Tipo di dati passato dalla HTTP Request 

        success: function(text) {       // Caso di successo: 
            MvcUtil.showSuccessResponse(text, button); 
        }, 

        error: function(xhr) {          // Caso di errore:
            MvcUtil.showErrorResponse(xhr.responseText, button); 
        }
    });
    return false;
});

The method of my controller class that hanldes this request is the following one:

@RequestMapping(value="/form", method=RequestMethod.POST)
public @ResponseBody String readForm(@ModelAttribute JavaBean bean) {
    return "Read x-www-form-urlencoded: " + bean;
}

Ok, the method take as input parameter a JavaBean object that is annoted with @ModelAttribute annotation.

Looking inside the example definied JavaBean class I have:

@XmlRootElement
public class JavaBean {

    @NotNull
    private String foo;
    @NotNull
    private String fruit;

    public JavaBean() {
    }

    public JavaBean(String foo, String fruit) {
        this.foo = foo;
        this.fruit = fruit;
    }

    // GETTER e SETTER METHOD
}

So JavaBeans contain two properties having the same name of the form variables passing in the HTTP Request that is generated when I have submitted my form

Reading the @ModelAttribute annotation documentation ( http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/bind/annotation/ModelAttribute.html ) I find that I can use it both to annotate a method, both to annotate a method parameter .

My case is the second case and for this case I can read: Annotation that binds a method parameter or method return value to a named model attribute, exposed to a web view

So what exactly means?

I think that if I annote a method parameter with this annotation it means that if the variables names passed inside the body of the HTTP Request match with the variables of my annoted object, Spring automatically copy the value of this variable inside the properties having the same name in the annoted object

But I am not sure of this...

Someone can help me to understand well this thing?

Tnx Andrea

I don't think so. @ModelAttribute is not about HTTP request parameter. When you annotated your method parameter like:

public String foo(@ModelAttribute ("petKey") Pet pet){
}

you would have a "pet" object that would come from your controller model object. Spring would search for "petKey" in model map object.

and when you annotated your method like:

@ModelAttribute ("petKey")
public Pet foo(){
   return new Pet;
}

after executing method and returning from method, Spring would put " new Pet " as value and "petKey" as key inside model object(map).

My answer might be late but i was researching the same and found this link which is interesting.

It gives a understanding on using the @ModelAttribute() at method level which goes well in hand with @SessionAttribute annotation. http://www.intertech.com/Blog/understanding-spring-mvc-model-and-session-attributes/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM