Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"command" modelName magic value in spring MVC 3

How to remove some of the "magic value" impression of "command" modelName parameter to create a ModelAndView ?

Example:

@RequestMapping(value = "/page", method = GET)
public ModelAndView render() {
    return new ModelAndView("page", "command", new MyObject());
}

One hope was to use a spring constant such as

new ModelAndView("page", DEFAULT_COMMAND_NAME, new MyObject());

I found "command" in the 3 following classes of the spring-webmvc-3.0.5 sources jar:

$ ack-grep 'public.*"command"'
org/springframework/web/servlet/mvc/BaseCommandController.java
140:    public static final String DEFAULT_COMMAND_NAME = "command";

org/springframework/web/servlet/mvc/multiaction/MultiActionController.java
137:    public static final String DEFAULT_COMMAND_NAME = "command";

org/springframework/web/servlet/tags/form/FormTag.java
56: public static final String DEFAULT_COMMAND_NAME = "command";

The problem is :

  • BaseCommandController is deprecated
  • We don't use MultiActionController and FormTag
like image 666
Philippe Blayo Avatar asked Jul 22 '11 13:07

Philippe Blayo


1 Answers

When you use on your jsp spring tag <form:form>

<form:form method="POST" action="../App/addCar">
<table>
<tr>
    <td><form:label path="brand">Name</form:label></td>
    <td><form:input path="brand" /></td>        
</tr>
<tr>
    <td><form:label path="year">Age</form:label></td>
    <td><form:input path="year" /></td>
</tr>    
<tr>
    <td colspan="2">
        <input type="submit" value="Submit" />            
    </td>
</tr>
</table>  
</form:form>

you must write:

@RequestMapping(value = "/car", method = RequestMethod.GET)
public ModelAndView car() {
return new ModelAndView("car", "command", new Car());
}

Because the spring framework expects an object with name "command". Default command name used for binding command objects: "command". This name to use when binding the instantiated command class to the request.

http://static.springsource.org/spring/docs/1.2.9/api/org/springframework/web/servlet/mvc/BaseCommandController.html

But when you use html form <form> you can write:

@RequestMapping(value = "/car", method = RequestMethod.GET)
public ModelAndView car() {
return new ModelAndView("car", "YOUR_MODEL_NAME", new Car());
}

But on your page

<form method="POST" action="../App/addCar">
<table>
<tr>
    <td><form:label path="YOUR_MODEL_NAME.brand">Name</form:label></td>
    <td><form:input path="YOUR_MODEL_NAME.brand" /></td>        
</tr>
<tr>
    <td><form:label path="YOUR_MODEL_NAME.year">Age</form:label></td>
    <td><form:input path="YOUR_MODEL_NAME.year" /></td>
</tr>    
<tr>
    <td colspan="2">
        <input type="submit" value="Submit" />            
    </td>
</tr>
</table>  
</form>
like image 65
Dimus Avatar answered Nov 02 '22 23:11

Dimus