springboot中不需要的转换

n6lpvg4x  于 2021-07-23  发布在  Java
关注(0)|答案(1)|浏览(310)

我在使用spring数据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
}

控制器类是。。。

// 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";
    }

}

我用的是自动对焦引擎。这是我的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>

对我来说一切似乎都很好,但是当我提交活动时,它会在浏览器和控制台中显示错误请求和400错误

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试图将我的活动从字符串转换为整数,但我不知道为什么会发生这种情况。有人能帮我解释一下为什么会这样吗?

de90aj5v

de90aj5v1#

将控制器方法更新为

@PostMapping("/save-activity")
public String saveActivity(@ModelAttribute("newActivity") Activity activity){
    activityService.save(activity);
    return "redirect:/students/activity/new-activity";
}

我认为缺少的model属性将正确Map表单值。

相关问题