我从Angular应用程序和Chrome海报发送了相同的Post请求。
从海报我指定以下内容: 网址:http://localhost:8080/rentapp/policy
部首: content-type application / json
内容:身体 { “title”:“NoSmoking”, “说明”: “NoSmoking” }
在Spring Controller中我有以下代码:
@PostMapping
// @Secured("ROLE_ADMIN")
public ResponseEntity<?> create(@Valid AttributeDTO policy, BindingResult bindingResult) {
logger.debug("CreatePolicy=" + policy);
AttributeDTO定义为:
@Data
public class AttributeDTO {
private String title;
private String description;
}
我看到海报请求后填充了AttributeDTO。 在Angular中我有以下方法
public addPolicyWithObservable(policy: Policy): Observable<Policy> {
const headers = new Headers({'Content-Type': 'application/json'});
const options = new RequestOptions({headers: headers});
console.log("addPolicyWithObservable policy=" + policy + " url=" + this.url + " http=" + this.http);
const ret: Observable<Policy> = this.http.post(this.url, policy, options)
.map(this.extractData)
.catch(this.handleErrorObservable);
console.log ("addPolicyWithObservable ret=" + ret);
return ret;
}
private extractData(res: Response) {
const body = res.json();
return body.data || {};
}
private handleErrorObservable(error: Response | any) {
console.error(error.message || error);
return Observable.throw(error.message || error);
}
在政策模型中:
export class Policy {
public id: number;
public title: string;
public description: string;
toString(): string {
return this.title + ': ' + this.description;
}
}
我看到在此请求之后,AttributeDTO(标题和描述)的属性在Java端为空。尽管事实上请求来到Java端并且在Angular端,发送前的日志记录是正确的,即标题和描述已正确填充:
addPolicyWithObservable policy = NoSmoking:NoSmoking url = / api / policy http = [object Object]
createpolicy.service.ts:20 addPolicyWithObservable ret = [object Object]
答案 0 :(得分:0)
这可能是因为您没有将传入的JSON转换为实际对象的功能,或者您没有告诉Spring您希望它使用JSON。
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
// @Secured("ROLE_ADMIN")
public ResponseEntity<?> create(@Valid AttributeDTO policy, BindingResult bindingResult) {
logger.debug("CreatePolicy=" + policy);
&#13;
我不太确定你是否需要这个dependancy
,但为了以防万一。
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.8</version>
</dependency>
&#13;
public addPolicyWithObservable(policy: Policy): Observable<Policy> {
const headers = new Headers({'Content-Type': 'application/json'});
const options = new RequestOptions({headers: headers});
console.log("addPolicyWithObservable policy=" + policy + " url=" + this.url + " http=" + this.http);
return this.http.post(this.url, policy, options)
.map((res) => res.json() as Policy)
.catch((err) => Observable.throw(console.error(err)));
}
&#13;
答案 1 :(得分:0)
尝试使用@RequestBody
的{{1}}注释。
AttributeDTO