【发布时间】:2021-05-17 10:20:31
【问题描述】:
我在使用 Spring Data JPA 时遇到了这个奇怪的错误。这是我的实体类...
// imports
@Entity
public class Activity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String activity;
public Activity() {}
public Activity(String activity) {
this.activity = activity;
}
// getters and setters
}
而Controller类是……
// imports
@Controller
@RequestMapping("/students/activity")
public class ActivityController {
@Autowired
private ActivityService activityService;
@GetMapping("/new-activity")
public String displayForm(Model model) {
model.addAttribute("newActivity", new Activity());
return "students/activity-form";
}
@PostMapping("/save-activity")
public String saveActivity(Activity activity){
activityService.save(activity);
return "redirect:/students/activity/new-activity";
}
}
我正在使用 thymeleaf 引擎进行查看。这是我的activity-form.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>Activity Form</title></head>
<body>
<form action="/students/activity/save-activity" th:object="${newActivity}" method="POST" >
<label>Activity:</label>
<input type="text" th:field="*{activity}">
<button type="submit">Add activity</button>
</form>
</body>
</html>
对我来说一切似乎都很好,但是当我提交活动时,它在浏览器和控制台中显示 Bad Request , 400 Error 并显示此错误
Resolved [org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'info.javacafe.studentforumapp.entities.Activity'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Integer] for value 'activity 1'; nested exception is java.lang.NumberFormatException: For input string: "activity1"]
我认为 spring 试图将我的活动从 String 转换为 Integer,但我不知道为什么会这样。谁能帮我解释一下为什么会这样?
【问题讨论】:
-
控制器期待您的 Activity 类的 json 表示形式。您正在向它传递纯文本字符串
-
是的@blurfus 你是对的,但是在我的实体类中,该字段仅用字符串声明,我不知道为什么它试图将其转换为整数。
-
分享你正在尝试的请求并抛出异常
-
我正在从我的浏览器请求...
-
你用的是什么版本?
标签: java spring spring-boot spring-mvc thymeleaf