【问题标题】:Why not use @RequestParam instead of @ModelAttribute为什么不使用 @RequestParam 而不是 @ModelAttribute
【发布时间】: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


【解决方案1】:

实际上,更像至少有四种方式(@RequestParam、@ModelAttribute、未注释的 Pojo 参数,以及直接来自 Request 对象)

使用单个结构化参数的主要原因是您的结构化数据包含多个字段。它比使用多个 @RequestParam 参数更方便,并且您可以同时验证所有参数。使用@ModelAttributes,您可以轻松地从会话、数据库或 flashAttributes 中检索单个对象。

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

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

【讨论】:

  • 其实处理传入数据的方法是无限的。您没有提到 @RequestBody 例如,您可以编写自己的参数解析器。 @ModelAttribute 不用于读取表单值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-07
  • 2013-09-09
  • 2013-10-28
  • 2012-05-28
  • 2021-10-12
相关资源
最近更新 更多