Spring 如何在一个端点中使用不同的请求主体?
我需要构建一个需要在一个端点的请求体中使用不同xmlTypes的服务 为此,我实施了以下措施:Spring 如何在一个端点中使用不同的请求主体?,spring,spring-boot,spring-mvc,Spring,Spring Boot,Spring Mvc,我需要构建一个需要在一个端点的请求体中使用不同xmlTypes的服务 为此,我实施了以下措施: @PostMapping(value="/one") public ResponseEntity<?> result( String xmlType, @RequestBody Object body ) { Employe employee = null; // employee
@PostMapping(value="/one")
public ResponseEntity<?> result(
String xmlType,
@RequestBody Object body
) {
Employe employee = null; // employee object that is generated by xsd file.
Profile profile = null; // profile object that is generated by xsd file.
if (body instanceof Employe) {
employee = (Employe) body;
} else if (body instanceof Profile) {
profile = (Profile) body;
}
// business logic
return ResponseEntity.accepted().build();
}
@PostMapping(value=“/one”)
公众反应结果(
字符串xmlType,
@请求体对象体
) {
Employe employee=null;//由xsd文件生成的employee对象。
Profile Profile=null;//由xsd文件生成的Profile对象。
if(员工的正文实例){
雇员=(雇员)团体;
}else if(配置文件的主体实例){
轮廓=(轮廓)主体;
}
//业务逻辑
返回ResponseEntity.accepted().build();
}
但是通过这个实现,我得到了不受支持的媒体类型错误
服务的使用示例强>
- url:“/domain/one?xmlType=Profile”,正文(requestBody):
- url:“/domain/one?xmlType=Employee”,正文(requestBody):
当我使用特定对象时,它可以工作,但我无法实现通用版本。那么,如何实现这一功能呢?这实际上是一个好问题
使用
@JsonIgnoreProperties(ignoreUnknown=true)
注释创建一个空的DTO类怎么样?由于以下原因,我将使用两种方法缩小请求映射:
@PostMapping(value=“/one”,params=“xmlType=Profile”)
公共响应后配置文件(@RequestBody Profile body){
...
}
@PostMapping(value=“/one”,params=“xmlType=Employee”)
公共响应postEmployee(@RequestBody-Employee-body){
...
}
使用请求方法,如get put post delete patch或传递标志
@PostMapping(value = "/one", params = "xmlType=Profile")
public ResponseEntity<?> postProfile(@RequestBody Profile body) {
...
}
@PostMapping(value = "/one", params = "xmlType=Employee")
public ResponseEntity<?> postEmployee(@RequestBody Employee body) {
...
}