问题描述
在Spring MVC控制器的POST请求处理方法(用 @RequestMapping
注释)中,您可以通过两种方式(正确吗?)从表单中访问POST-ed的表单值.
In a a POST request handling method (annotated with @RequestMapping
) of a Spring MVC controller, you can access the form values POST-ed from the form in two ways (correct?).
您可以使用将所有表单值捆绑在一起的模型对象(命令)类,并使用带注释的参数 @Valid
@ModelAttribute
传递表单值.这似乎是处理表格的常用方法.
You can use a model object (command) class that bundles all the form values together and use an argument annotated @Valid
@ModelAttribute
to pass in the form values. This seems to be the common way of processing forms.
@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
的局限性是什么.
Why Use @ModelAttribute
So why bother using @ModelAttribute
, given that it has the inconvenience of having to create an auxiliary command class? What are the limitations of using a @RequestParam
.
推荐答案
实际上,至少有四种方式(@ RequestParam,@ ModelAttribute,未注释的Pojo参数和直接来自请求对象)
Actually, there are at least four ways (@RequestParam, @ModelAttribute, an un-annotated Pojo parameter, and straight from the Request object)
使用单个结构化参数的主要原因是,如果结构化数据具有多个字段.比使用多个@RequestParam参数更方便,并且您可以同时验证所有参数.使用@ModelAttributes,您可以轻松地从会话,数据库或flashAttributes中检索单个对象.
The main reason to use a single structured parameter is if you have structured data with several fields. It's more convenient than using several @RequestParam params, and you can validate all at the same time. With @ModelAttributes you can retrieve a single object from session, database, or flashAttributes easily.
您可以将现有实体或Pojo与@ModelAttribute一起使用,而不必创建自定义的表单支持对象.
You can use existing Entities or Pojos with @ModelAttribute, you don't need to create a custom Form Backing Object necessarily.
但是,如果您只有一个或两个参数,则@RequestParam可以.
But ya, if you just have one or two params, then @RequestParam is fine.
这篇关于为什么不使用@RequestParam而不是@ModelAttribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!