【问题标题】:Required request parameter for method POST is not present方法 POST 所需的请求参数不存在
【发布时间】:2021-11-08 01:14:55
【问题描述】:

我正在努力解决 Spring Boot 应用程序中 POST 方法中 @RequestParam 的问题。 我在页面上有一个简单的表单,只有一个参数:

@GetMapping("/")
public String mainPage(Model model){
     return "HelloPage";
}

还有HelloPage

<div class="form-group col-sm-6">
  <form method="post" enctype="text/plain">
      <div class="form-group">
          <label>
              <input type="text" class="form-control"
                     name="authorname" placeholder="Employee name"
              />
          </label>
      </div>
      <div class="form-group">
          <button type="submit" class="btn btn-primary ml-2">Next</button>
      </div>
  </form>
</div>

我创建了一个 POST 方法来创建一个新作者并重定向到另一个我想显示这个作者姓名的页面:

@PostMapping("/")
public String postAuthor(@RequestParam("authorname") String authorname){
  Author author = authorService.saveAuthor(authorname);
  return "redirect:/surveys/" + author.getId();
}

当我在 HelloPage 上填写表单后单击按钮时,出现以下错误:

出现意外错误(类型=错误请求,状态=400)。必需的 方法参数类型字符串的请求参数“作者名”不是 展示 org.springframework.web.bind.MissingServletRequestParameterException: 方法参数类型的必需请求参数“作者名” 字符串不存在

我不明白为什么会这样,因为 POST 方法应该能够从表单中获取请求参数!

Author 只是一个简单的实体模型:

@Entity
@Table(name = "authors")
public class Author {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String authorname;

    public Author() {}

    public Author(String authorname) {
        this.authorname = authorname;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getAuthorname() {
        return authorname;
    }

    public void setAuthorname(String authorname) {
        this.authorname = authorname==null || authorname.isEmpty()? "default user" : authorname;
    }
}

谁能解释一下这里出了什么问题?

【问题讨论】:

    标签: spring-boot


    【解决方案1】:

    尝试删除enctype="text/plain"。根据https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plain-text-form-data

    使用 text/plain 格式的有效负载旨在为人类提供 可读。它们不能被计算机可靠地解释,因为 格式不明确(例如,无法区分 值末尾的换行符中的文字换行符)。

    话虽如此,请尝试以下操作:

    <div class="form-group col-sm-6">
      <form method="post">
          <div class="form-group">
              <label>
                  <input type="text" class="form-control"
                         name="authorname" placeholder="Employee name"
                  />
              </label>
          </div>
          <div class="form-group">
              <button type="submit" class="btn btn-primary ml-2">Next</button>
          </div>
      </form>
    </div>
    

    【讨论】:

      猜你喜欢
      • 2023-01-07
      • 2023-01-07
      • 2017-10-23
      • 2021-09-21
      • 1970-01-01
      • 2023-02-15
      • 2019-03-29
      • 2021-01-12
      • 2020-01-06
      相关资源
      最近更新 更多