java 使用 Spring 返回 XML 响应 Rest API

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35536887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 00:14:01  来源:igfitidea点击:

Return XML response Rest API with Spring

javajsonxmlspring

提问by Roberto Fernandez Diaz

I am trying to response with XML to a given call to the API.

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

Right now it works with JSON, I can send JSON or XML and return JSON.

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

But I cannot do the same with XML.

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

From now what I have is this:

从现在开始,我所拥有的是:

RestVoterController class:

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 class:

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

}

回答by Mike Shauneu

I tested your code and it works for me. Please look:

我测试了你的代码,它对我有用。敬请期待:

First I create mock for voterService.

首先,我为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;
    }
}

Then I have to slightly modify your controller (remove Transactionannotation because I have no data source in my service mock).

然后我必须稍微修改您的控制器(删除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());
    }
}

Also I have to create mock for Voterbecause you don't share it.

此外,我必须创建模拟,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 + "]";
    }
}

And finally integration test.

最后是集成测试。

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

The result could be find in a output of the test and should contain two lines.

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

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

回答by Mhmoud Sabry

produces = { MediaType.APPLICATION_JSON_VALUE} is the solution to me

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