Search code examples
springspring-mvcmodelattribute

Does a variable with @ModelAttribute get populated from request parameters?


I am interested in the specifics of Spring @ModelAttribute's work on method parameters.

As we know, when a requested attribute is absent from the model, then its instance gets created and populated from the view form.

My question concerns the scenario when the form does not have expected properties but when such properties are available in URL template parameters. I would like to know if in this case our variable will be populated with the values of those request parameters?

Like here, for instance, will the variable attributeToPopulate get populated with the parameters 1,2,3 from the URL http://localhost:8080/MyApp/parameter1=whatever?parameter2=whatever?parameter3=whatever?:

RequestMapping(method = RequestMethod.GET)
public  String fooMethod(@ModelAttribute("attributeName") FooClass attributeToPopulate){
// method implementation
return "view";
}

Neither Spring documentation, reference documentation, nor Q&A sites refer to such situations explicitly. However, one post here on Stack Overflow does mention that variables annotated with ModelAtrribute get populated in this way (answer of the user Xelian):

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

Considering a small number of upvotes for that answer, I am bit skeptical but at the same time curious about whether @ModelAttribute indeed functions in such way.

Any informative input will be greatly appreciated.


Solution

  • You can set default values to fields in the FooClass instead of setting them in RequestMapping annotation. In this case you will not have to copypaste RequestMapping with default values in all the methods where you are working with FooClass as a ModelAttribute. @tomatefraiche I have tried to do this by

    <spring:url value="/hello?name=default" var="userActionUrl" />
    <form:form method="get" modelAttribute="user" action="${userActionUrl}">
      <form:input path="name" type="text" disabled="true" />
    </form:form>
    

    and

    @GetMapping("/hello")   
      public String hello(@ModelAttribute("user") User user, Model model) {
      model.addAttribute("name", user.name);
      model.addAttribute("user", user);
      return "hello";
    

    }

    and looks like Spring override values in the url. In the controller there is an empty value. Also URL is hello?name= after form submission. So looks like you can not set default values through url since it will be replaced.