【发布时间】:2014-11-19 16:16:45
【问题描述】:
在 Spring MVC 控制器的 POST 请求处理方法(使用 @RequestMapping 注释)中,您可以通过两种方式从表单访问表单值 POST(正确吗?)。
使用@ModelAttribute
您可以使用将所有表单值捆绑在一起的模型对象(命令)类,并使用注释为@Valid@ModelAttribute的参数传入表单值。这似乎是处理表单的常用方式。
@RequestMapping(value = { "thing/{thing}/part/" }, method = RequestMethod.POST)
public String processForm(
@PathVariable("thing") final String thing,
@ModelAttribute(value = "command") @Valid final Command command,
final BindingResult bindingResult) {
if (!bindingResult.hasErrors()) {
final String name = command.getName();
final long time = command.getTime().getTime();
// Process the form
return "redirect:" + location;
} else {
return "form";
}
}
使用@RequestParam。
您可以使用@RequestParam 注释单个方法参数。
@RequestMapping(value = { "thing/{thing}/part/" }, method = RequestMethod.POST)
public String processForm(
@PathVariable("thing") final String thing,
@RequestParam(value = "name", required=true) final String name,
@RequestParam(value = "time", required=true) final Date time,
final HttpServletResponse response) {
// Process the form
return "redirect:" + location;
}
为什么使用@ModelAttribute
那么为什么还要使用@ModelAttribute,因为它必须创建一个辅助命令类带来不便?使用@RequestParam 有什么限制。
【问题讨论】:
-
用
@ModelAttribute注释参数与获取表单值无关。 -
@zeroflagL 错误?它没有别的用处。
-
如果它与参数一起使用,则该对象被添加到模型中,并且可以选择从模型中获取,因此名称为
Model Attribute。该对象将使用带有或不带有@ModelAttribute的表单值填充。
标签: forms spring-mvc servlets