POST方法所需的请求参数不存在



我正在努力解决在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上填写表单后点击按钮时,它给了我这个错误:

出现意外错误(type=Bad Request, status=400)。要求请求参数'authorname'的方法参数类型字符串不是现在org.springframework.web.bind.MissingServletRequestParameterException:为方法参数类型要求请求参数"authorname"字符串不存在

我不明白为什么会发生这种情况,因为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;
}
}
谁能解释和帮助我这里有什么问题吗?

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

使用文本/纯格式的有效负载旨在人性化可读。它们不能被计算机可靠地解释,因为格式是不明确的(例如,没有办法区分

从值末尾的换行符开始,在值中插入文字换行符。

话虽如此,不妨试试下面这句话:

<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>

最新更新