POST请求正文json值:
{
"id" : 452312313231,
"name" : "b2",
"floor": 5
}
建筑类代码:
@Entity
@Table(name = "building")
public class Building implements Serializable{
private static final long serialVersionUID = -3009157732242241606L;
@Id
@Column(name = "building_ID")
@NotNull
@Digits(fraction = 0, integer = 15)
private long id;
@Column(name = "NAME")
@NotNull
private String name;
@Column(name = "floor")
@NotNull
@Digits(fraction = 0, integer = 2)
private int floor;
public Building() {}
public Building(long id, String name, int floor) {
this.id = id;
this.name = name;
this.floor = floor;
}
控制器代码:
@RequestMapping(value = "/building", method = RequestMethod.POST, headers = "Accept=application/json")
@ResponseBody
String post(Model model, @Valid @ModelAttribute("Building") Building building, BindingResult result) {
if (result.hasErrors()) {
System.out.println("Wrong data");
return "Null values or worng data please check properly Number = " + result.getErrorCount() + " \n Error : "
+ result.getAllErrors();
} else {
buildingRep.save(building);
return "Succesfull";
}
}
使用jpa保存数据。我通过@RequestBody选择@ModelAttribute以便于验证。问题是构建对象总是空的。 我在用json对象做任何事情吗?
答案 0 :(得分:0)
@ModelAttribute 是一个注释,它将方法参数或方法返回值绑定到命名的模型属性,然后将其公开给Web视图。对于 @RequestBody ,绑定到Web请求标头并包含DTO。
因此,您可以使用 @RequestHeade 来代替 @Valid @ModelAttribute(" Building" ),它应该有效。