简体   繁体   English

spring boot从angular2的JSON发布请求中将空属性映射到POJO

[英]spring boot maps null properties to POJO from JSON post request from angular2

After doing a big deal of research on the topic I decided to ask in here. 在对该主题进行了大量研究之后,我决定在这里询问。 I am getting all null properties to the POJO/Model which is supposed to get values from the JSON I am posting from the Angular 2 Front end. 我正在获取POJO / Model的所有空属性,该属性应该从我从Angular 2前端发布的JSON获取值。 Here is the rest controller method: 这是其余的控制器方法:

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

The following is the POJO/Model/Hibernate Entity: 以下是POJO /模型/休眠实体:

@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;
}

The following is the Angular 2 Service method: 以下是Angular 2 Service方法:

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());
}

and the Employee interface of Angular 2: 以及Angular 2的Employee接口:

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

What am I doing wrong? 我究竟做错了什么? I have searched for similar issues but none I found applies to my case. 我已经搜索了类似的问题,但没有发现适用于我的情况。 Thank you! 谢谢!

Try annotating the method with @ResponseBody 尝试使用@ResponseBody注释方法

Which would become: 变成:

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

You need to serialize the javascript object before sending it. 您需要先序列化javascript对象,然后再发送它。 Try: 尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM