我正在学习Spring Boot,这是我的新手,并试图创建一个接收发布请求的控制器,但是在我的整个测试过程中,该控制器始终接收空请求主体对象。请指导我我在做什么错。
{
"user":{
"name":"teste",
"lastName":"teste"
} "contact":{
"email":"teste@teste.com",
"phone":"0123456789"
} "isMarried":true
}
Java类:
@RequestMapping(method=RequestMethod.POST,value= "/user", consumes= MediaType.ALL_VALUE )
public ResponseEntity<Void> login(@RequestBody User user,
@RequestBody contact,
boolean isMarried){
System.out.println(user.getUsername());
return new ResponseEntity<Void>(HttpStatus.CREATED);
}
sysout为null,但isMarried可以工作:(
Java实体:
@Entity
public class User{
@Id @GeneratedValue @Column(name= "id")
private Integer id;
@Column(name="name")
private String name;
@Column(name= "last_name")
private String lastName;
Getters and setters....
}
@Entity
public contact {
@Id @GeneratedValue @Column(name= "id")
private Integer id;
@Column(name="email")
private String email;
@Column(name= "phone")
private String phone;
Getters and setters....
}
答案 0 :(得分:1)
@RequestBody
批注应代表请求的整个主体,并且仅绑定到请求中的一个对象。因此,您必须更改输入的json格式,post方法的签名,并创建一个封装类以将User,Contact和IsMarried数据保存在一起。
{
"user": {
"name": "teste",
"lastName": "teste"
},
"contact": {
"email": "teste@teste.com",
"phone": "0123456789"
},
"isMarried": true
}
@RequestMapping(method=RequestMethod.POST,value= "/user", consumes= MediaType.ALL_VALUE )
public ResponseEntity<Void> login(@RequestBody UserDetail userDetail){
System.out.println(userDetail.getUser.getUsername());
return new ResponseEntity<Void>(HttpStatus.CREATED);
}
class UserDetail{
User user;
Contact contact;
boolean married;
}
答案 1 :(得分:0)
您只能发送这样的用户详细信息。
{ “ name”:“ teste”, “ lastName”:“ teste” }
您的请求方法应如下所示。
@RequestMapping(method=RequestMethod.POST,value= "/user", consumes= MediaType.ALL_VALUE )
public ResponseEntity<Void> login(@RequestBody User user){
System.out.println(user.getName());
System.out.println(user.getLastName());
return new ResponseEntity<Void>(HttpStatus.CREATED);
}
希望这会有所帮助。