forms - 为什么不使用@RequestParam 而不是@ModelAttribute

标签 forms spring-mvc servlets

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

使用@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 有什么限制。

最佳答案

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

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

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

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

关于forms - 为什么不使用@RequestParam 而不是@ModelAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27021679/

相关文章:

java - 在方法级别过滤 servlet

spring - 扩展 SpringBootServletInitializer 时如何注册 DispatcherServlets 并重写 onStartup

javascript - React 中输入小数的数字?

iphone - 获取iPhone GO按钮以提交表单

uri 参数中带斜杠的 Rest 模板

java - Spring Security 不允许加载 CSS 或 JS 资源

css - 复选框控制 servlet 中所有相同的 css 类 ID 颜色

database - 如何在Access中完成一个数字?

javascript - JQuery 提交 - 无限循环

apache - Spring Security ajax 登录使用 http 重定向而不是 https