在Spring应用程序中的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请求,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;
}
}
有人能帮我解释一下这里出了什么问题吗?
发布于 2021-09-12 11:59:38
尝试删除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>
https://stackoverflow.com/questions/69150919
复制相似问题