【发布时间】: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