AJAX POST请求Spring Boot时实体字段为NULL的原因与解决
问题原因及解决方法
问题现象
前端通过AJAX发送POST请求,携带name和description字段的JSON数据,但后端Spring Boot接口接收Genres实体类时,所有字段值为null,控制台输出Genre = null,数据库新增记录字段也为NULL。
前端AJAX代码
$("#add_button").click(function() { console.log("The button has been pressed"); var genre = { name: $("#genre_name").val(), description: $("#genre_desc").val() }; $.ajax({ type: "POST", url: "/save_genre", data: JSON.stringify(genre), contentType: "application/json", success: function(response) { console.log("Genre successfully created:", response); }, error: function(error) { console.error("An error occurred while creating the genre:", error); } });
后端接口代码
@RestController public class AddGenreRestController { @Autowired private GenreRepository GenreRepository; @PostMapping("/save_genre") public Genres addGenre(@RequestBody Genres genre) { System.out.println("Genre = " + genre.GetName()); return GenreRepository.save(genre); } }
Genres实体类代码
@Entity @Table(name="Genres") public class Genres { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long ID; private String name; @Lob @Column(columnDefinition = "text") private String description; public Genres() { } public Long GetID() { return ID; } public void SetID(Long ID) { this.ID = ID; } public String GetName() { return name; } public void SetName(String name) { this.name = name; } public String GetDescription () { return description; } public void SetDescription(String description) { this.description = description; } }
问题原因
Spring Boot默认使用Jackson处理JSON序列化/反序列化,而Jackson严格遵循JavaBean规范:
- getter方法必须以小写
get开头,setter方法必须以小写set开头;你的实体类中方法是GetName()、SetName()(首字母大写),Jackson无法识别这些方法,无法完成JSON字段到实体类属性的映射。 - 实体类中
ID字段命名不符合Java变量小驼峰规范,虽然不是直接导致空值的原因,但会和不规范的getter/setter一起加剧映射失败的问题。
解决方法
修改Genres实体类的getter/setter方法及字段命名,完全符合JavaBean规范:
@Entity @Table(name="Genres") public class Genres { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; @Lob @Column(columnDefinition = "text") private String description; public Genres() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription () { return description; } public void setDescription(String description) { this.description = description; } }
修改后Jackson就能正常识别属性的getter/setter方法,将前端发送的JSON字段值正确注入到实体类中,后端控制台和数据库也能得到正确的字段值。
内容的提问来源于stack exchange,提问作者dddryinside
相关产品推荐
相关产品推荐

