Forms 为什么不使用@RequestParam而不是@ModelAttribute

Forms 为什么不使用@RequestParam而不是@ModelAttribute,forms,spring-mvc,servlets,Forms,Spring Mvc,Servlets,在Spring MVC控制器的POST请求处理方法(用@RequestMapping注释)中,您可以通过两种方式访问从表单发布的表单值(正确吗?) 使用@modeldattribute 您可以使用将所有表单值捆绑在一起的模型对象(命令)类,并使用带注释的参数@Valid@modeldattribute传递表单值。这似乎是处理表单的常见方式 @RequestMapping(value = { "thing/{thing}/part/" }, method = RequestMethod.POST

在Spring MVC控制器的POST请求处理方法(用
@RequestMapping
注释)中,您可以通过两种方式访问从表单发布的表单值(正确吗?)

使用
@modeldattribute
您可以使用将所有表单值捆绑在一起的模型对象(命令)类,并使用带注释的参数
@Valid
@modeldattribute
传递表单值。这似乎是处理表单的常见方式

 @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;
 }
为什么要使用
@modeldattribute
既然必须创建一个辅助命令类,那么为什么还要麻烦使用
@modeldattribute
?使用
@RequestParam

有什么限制实际上,至少有四种方法(@RequestParam、@modeldattribute、未注释的Pojo参数和直接从请求对象开始)

 @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;
 }
使用单个结构化参数的主要原因是,如果您有包含多个字段的结构化数据。它比使用几个@RequestParam参数更方便,并且可以同时验证所有参数。使用@modeldattributes,您可以轻松地从会话、数据库或flashAttributes检索单个对象

您可以将现有实体或POJO与@ModelAttribute一起使用,不必创建自定义表单支持对象


但是,如果你只有一两个参数,那么@RequestParam就可以了

@modeldattribute
注释参数与获取表单值无关。@zeroflagL Errr?除此之外,它没有任何用处。如果它与参数一起使用,则该对象将添加到模型中,并可选地从模型中获取,因此名为
模型属性
。对象将填充有或没有
@modeldattribute
的表单值。实际上,处理传入数据的方法是无限的。例如,您没有提到
@RequestBody
,您可以编写自己的参数解析器
@modeldattribute
不用于读取表单值。