spring boot将null属性从angular2的JSON post请求映射到POJO

时间:2017-03-06 12:11:52

标签: json spring rest angular spring-boot

在对这个话题做了大量研究之后,我决定在这里问一下。我得到POJO / Model的所有null属性,它应该从我从Angular 2 Front端发布的JSON中获取值。这是其余的控制器方法:

@RequestMapping(value = "/employees/update",  method = RequestMethod.POST, consumes = "application/json")
    public String allEmployees( @RequestBody Employee emp){
        return "";
    } 

以下是POJO / Model / Hibernate实体:

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(nullable = false, updatable = false)
private Long id;

private String firstname;
private String lastname;
private String department;

public Employee(){}

public Long getId() {
    return id;
}
public void setId(Long id) {
    this.id = id;
}
public String getFirstname() {
    return firstname;
}
public void setFirstname(String firstname) {
    this.firstname = firstname;
}
public String getLastname() {
    return lastname;
}
public void setLastname(String lastname) {
    this.lastname = lastname;
}
public String getDepartment() {
    return department;
}
public void setDepartment(String department) {
    this.department = department;
}

以下是Angular 2服务方法:

updateEmployee(emp:Employee){
  let url: string = "http://localhost:8080/api/employees/update";
  let headers = new Headers();
  headers.append('Content-Type', 'application/json');
  return  this.http.post(url, {emp}, {headers: headers, withCredentials: true }).map(res => res.json());
}

和Angular 2的Employee接口:

export interface Employee{
  id: number;
  firstname: string;
  lastname: string;
  department: string;
}

我做错了什么?我搜索过类似的问题,但我发现没有一个适用于我的情况。谢谢!

2 个答案:

答案 0 :(得分:0)

尝试使用@ResponseBody

注释该方法

哪个会成为:

@ResponseBody
@RequestMapping(value = "/employees/update",  method = RequestMethod.POST, consumes = "application/json")
    public String allEmployees( @RequestBody Employee emp){
        return "";
    } 

答案 1 :(得分:0)

您需要在发送之前序列化javascript对象。尝试:

this.http.post(url, JSON.stringify(emp), {headers: headers, withCredentials: true }).map(res => res.json());