"command" modelName magic value in spring MVC 3

How to remove some impression of the "magic value" of the "command" parameter modelName 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 following 3 source classes spring -webmvc-3.0.5:

 $ 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 this:

  • BaseCommandController deprecated
  • We do not use MultiActionController and FormTag
+4
source share
2 answers

When you use 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 should write:

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

Because the spring framework expects an object named "command". The default command name used to bind command objects is "command". This name is used when binding the created 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 the 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> 
+10
source

I would not use the default name. If the object is User call User , if it Item calls its Item . If you need a default (e.g. for a generic structure), define your own constant.

0
source

All Articles