【发布时间】:2022-01-19 19:19:09
【问题描述】:
我正在尝试创建一个简单的 Spring Web 应用程序。我在执行 POST 方法时遇到了错误。当我转到我的 post 方法映射到的 url 时,我收到以下错误:
Whitelabel 错误页面 此应用程序没有明确的映射 /error,因此您将其视为后备。
EET 2022 年 1 月 19 日星期三 20:57:38 出现意外错误(类型=错误 请求,状态=400)。
我有一个 html 表单,用户可以在其中输入数据,从中创建一个对象并将其添加到数据库(对于 ui 模板,我使用 Mustache)
另外,控制台中的错误如下:
.w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: "charity"]
这是我的控制器:
@RequestMapping("/share")
@Controller
public class CharityController {
@Autowired
private CharityServiceImpl charityService;
@PostMapping("charities/charity")
public String addCharity(@RequestBody Charity charity){
charityService.save(charity);
return "addForm";
}
html表单:
<!DOCTYPE HTML>
<html>
<head>
<title>Add New Charity</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<div>
<form method="post" action="charities/charity">
<input type="number" name="id" placeholder="Id"/>
<input type="text" name="name" placeholder="Charity name"/>
<input type="text" name="description" placeholder="Description"/>
<button type="submit">Add</button>
</form>
</div>
</body>
</html>
实体类:
@Entity
public class Charity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@NotBlank
private String name;
@NotBlank
private String description;
public Charity(Integer id, String name, String description) {
this.id = id;
this.name = name;
this.description = description;
}
public Charity() {
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
DAO 方法:
public void save(Charity charity) {
Session session = sessionFactory.openSession();
session.beginTransaction();
session.saveOrUpdate(charity);
session.getTransaction().commit();
session.close();
}
服务实现:
public void save(Charity charity){
charityDao.save(charity);
}
【问题讨论】:
-
看起来您在 id 输入中输入了“charity”
-
我什至无法用我的表单打开 url,所以我想这不太可能:( 但我怀疑它试图从 "localhost:8080/share/charities/charity" 的 url 获取参数,而不是从 ui形式。
-
@PostMapping("charities/charity") 应该是 @PostMapping("/charities/charity")
-
谢谢,我试过了,但还是一样的错误:(
标签: java spring spring-boot spring-mvc mustache