【问题标题】:Return XML response Rest API with Spring使用 Spring 返回 XML 响应 Rest API
【发布时间】:2016-02-21 13:43:48
【问题描述】:

我正在尝试使用 XML 响应对 API 的给定调用。

现在它适用于 JSON,我可以发送 JSON 或 XML 并返回 JSON。

但我不能对 XML 做同样的事情。

从现在开始我拥有的是这样的:

RestVoterController 类:

@RequestMapping("/rest")
@RestController
public class RESTVoterController {

@Autowired
private VoterService voterService;

@RequestMapping(value = {"/user.json","/user"},
        method = RequestMethod.POST,
        consumes = {"application/json","application/xml"},
        produces = {"application/json"})
@Transactional(readOnly = true)
public Voter getVoterInfoJSON(@RequestBody VoterRequestGet voterRequestGet) {
    return this.voterService.findByEmailAndPassword(voterRequestGet.getLogin(), voterRequestGet.getPassword());
}

@RequestMapping(value = "/user.xml",
        method = RequestMethod.POST,
        consumes = {"application/xml","application/json"},
        produces = "application/xml")
@Transactional(readOnly = true)
public Voter getVoterInfoXML(@RequestBody VoterRequestGet voterRequestGet) {
    return this.voterService.findByEmailAndPassword(voterRequestGet.getLogin(), voterRequestGet.getPassword());
}

@RequestMapping(value = "/changepassword",
        method = RequestMethod.POST,
        headers = "Accept=application/json",
        produces = "application/json")
@Transactional(readOnly = true)
public void changePassword(@RequestBody VoterRequestChangePassword voterRequestChangePassword) {
    this.voterService.changePassword(voterRequestChangePassword.getLogin(), voterRequestChangePassword.getOldPassword(), voterRequestChangePassword.getNewPassword());
}
}

VoterRequestGet 类:

@XmlRootElement(name = "user")
@XmlAccessorType(XmlAccessType.FIELD)
public class VoterRequestGet {

@XmlElement
private String login;
@XmlElement
private String password;

public VoterRequestGet()
{
}

public String getLogin() {
    return login;
}

public void setLogin(String login) {
    this.login = login;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

}

【问题讨论】:

    标签: java json xml spring


    【解决方案1】:

    我测试了您的代码,它适用于我。请看:

    首先我为voterService 创建模拟。

    package com.example;
    
    import org.springframework.stereotype.Service;
    
    @Service
    public class VoterService {
        public Voter findByEmailAndPassword(String login, String password) {
            Voter voter = new Voter();
            voter.setLogin(login);
            voter.setPassword(password);
            return voter;
        }
    }
    

    然后我必须稍微修改您的控制器(删除Transaction 注释,因为我的服务模拟中没有数据源)。

    package com.example;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    
    @RequestMapping("/rest")
    @RestController
    public class RESTVoterController {
    
        @Autowired
        private VoterService voterService;
    
        @RequestMapping(value = {"/user.json","/user"},
                method = RequestMethod.POST,
                consumes = {"application/json","application/xml"},
                produces = {"application/json"})
        public Voter getVoterInfoJSON(@RequestBody VoterRequestGet voterRequestGet) {
            return this.voterService.findByEmailAndPassword(voterRequestGet.getLogin(), voterRequestGet.getPassword());
        }
    
        @RequestMapping(value = "/user.xml",
                method = RequestMethod.POST,
                consumes = {"application/xml","application/json"},
                produces = "application/xml")
        public Voter getVoterInfoXML(@RequestBody VoterRequestGet voterRequestGet) {
            return this.voterService.findByEmailAndPassword(voterRequestGet.getLogin(), voterRequestGet.getPassword());
        }
    }
    

    我还必须为Voter 创建模拟,因为你不分享它。

    package com.example;
    
    import javax.xml.bind.annotation.XmlAccessType;
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlRootElement;
    
    @XmlRootElement(name = "voter")
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Voter {
    
        @XmlElement
        private String login;
        @XmlElement
        private String password;
    
        public Voter() {
        }
    
        public String getLogin() {
            return login;
        }
    
        public void setLogin(String login) {
            this.login = login;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        @Override
        public String toString() {
            return "Voter [login=" + login + ", password=" + password + "]";
        }
    }
    

    最后是集成测试。

    package com.example;
    
    import javax.annotation.Resource;
    
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.autoconfigure.web.ServerProperties;
    import org.springframework.boot.test.SpringApplicationConfiguration;
    import org.springframework.boot.test.WebIntegrationTest;
    import org.springframework.http.HttpEntity;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.MediaType;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    import org.springframework.web.client.RestTemplate;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringApplicationConfiguration(classes = TestApplication.class)
    @WebIntegrationTest("server.port:0")
    public class RESTVoterControllerTest {
    
        private ServerProperties serverProperties;
    
        private RestTemplate restTemplate = new RestTemplate();
    
        @Resource
        public void setServerProperties(ServerProperties serverProperties) {
            this.serverProperties = serverProperties;
        }
    
        @Value("${local.server.port}")
        private int serverPort;
    
        private String serverUri;
    
    
        @Before
        public void setUp() throws Exception {
            String contextPath = serverProperties.getContextPath();
            serverUri = "http://localhost:" + serverPort + (contextPath == null ? "/" : contextPath);
        }
    
        @After
        public void tearDown() throws Exception {
        }
    
    
        @Test
        public void testCreate() throws Exception {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_XML);
            VoterRequestGet voterRequest = new VoterRequestGet();
            voterRequest.setLogin("email");
            voterRequest.setPassword("secret");
    
            HttpEntity<VoterRequestGet> request = new HttpEntity<>(voterRequest, headers);
    
            System.out.println(restTemplate.postForEntity(
                    serverUri + "/rest/user.json", request, String.class).getBody());
    
            System.out.println(restTemplate.postForEntity(
                    serverUri + "/rest/user.xml", request, String.class).getBody());
        }
    }
    

    结果可以在测试的输出中找到,并且应该包含两行。

    {"login":"email","password":"secret"}
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?><voter><login>email</login><password>secret</password></voter>
    

    【讨论】:

      【解决方案2】:

      您需要像 jackson 这样的 XML 映射库,因此将其添加到您的 pom.xml 将解决您的问题:

      <dependency>
          <groupId>com.fasterxml.jackson.dataformat</groupId>
          <artifactId>jackson-dataformat-xml</artifactId>
      </dependency>
      

      【讨论】:

        【解决方案3】:

        产生 = { MediaType.APPLICATION_JSON_VALUE} 是我的解决方案

        【讨论】:

          猜你喜欢
          • 2022-01-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多