Spring 4 RestController没有正确映射xml请求

时间:2017-05-08 10:17:12

标签: xml spring-mvc spring-restcontroller

enter image description here我正在尝试创建一个支持XML请求并生成xml响应的RESTful Web服务,我正在使用spring 4.3.5 ...

问题在于,当我使用邮递员发布帖子请求并在我的服务方法中添加调试时,我发现xml请求属性没有使用播放器POJO进行映射/反序列化。

任何帮助都将不胜感激。谢谢

@RestController
public class SyncRestfulService {

LoggerManager loggerManager = new LoggerManager();

@RequestMapping(value = RestURIConstants.SAMPLE_POST_PLAYER, method = RequestMethod.POST, headers = {
        "Content-type=application/xml" })
public Player getPlayer(Player requestEntity) {

    loggerManager.info(LoggerConstantEnum.SyncRestfulService ,
            "| <AbilitySyncRestfulService> Method: getPlayer " + requestEntity);

    loggerManager.info(LoggerConstantEnum.SyncRestfulService , "Id : ", requestEntity.getId());

    return requestEntity;
}

}

请求xml数据

//Request 
<player>
    <id>1</id>
    <matches>251</matches>
    <name>Anand</name>
</player>

//response xml data
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <player>
    <id>0</id>
 </player>

// jaxb pojo

@XmlRootElement(name = "player")
@XmlAccessorType(XmlAccessType.NONE)
public class Player {

    private int id;

    private String name;

    private String matches;

    public int getId() {
        return id;
    }
    @XmlElement(name = "id")
    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }
    @XmlElement(name = "name")
    public void setName(String name) {
        this.name = name;
    }

    public String getMatches() {
        return matches;
    }
    @XmlElement(name = "matches")
    public void setMatches(String matches) {
        this.matches = matches;
    }
}

1 个答案:

答案 0 :(得分:2)

public Player getPlayer(Player requestEntity) { ... }

这是您的请求处理方法(省略@RequestMapping注释)。使用此方法,您可以对对象执行参数绑定。因此,如果您要传递网址/player/?id=2&name=foo,则id字段将获得值2name字段值foo

但是,您不想进行绑定,而是希望进行消息转换。要启用此功能,必须使用@RequestBody注释方法参数,这将告诉Spring MVC不是use参数绑定,但尝试检测合适的HttpMessageConverter以将HTTP消息体转换为Player实例。

public Player getPlayer(@RequestBody Player requestEntity) { ... }

上面的签名可以解决您的问题。另请参阅reference guide,它很好地解释了这一点。

注意: @RestController@Controller@ResponseBody的组合,它不会推断@RequestBody。请参阅reference guide