如何使用Spring Boot Rest Data返回xml

时间:2014-11-19 06:23:06

标签: xml json rest spring-boot spring-data-rest

我需要Spring引导休息数据的输出为xml而不是json。我已经放入了我的Repository对象:

@RequestMapping(value="/findByID", method=RequestMethod.GET, headers = { "Accept=application/xml" }, produces="application/xml")
MyXmlAnnotatedObject findById(@Param("id") BigInteger id);

我还将以下内容添加到我的pom dependancies

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

    <dependency>
        <groupId>org.codehaus.woodstox</groupId>
        <artifactId>woodstox-core-asl</artifactId>
        <version>4.4.1</version>
    </dependency>

但是当我尝试

http://localhost:9000/factset/search/findByID?id=18451

我仍然得到JSON。我真的需要为我的用户使用XML 任何想法?

3 个答案:

答案 0 :(得分:4)

RequestMapping注释不适用于存储库。存储库方法不允许您更改结果格式(默认为JSON)。如果您希望您的服务以XML格式返回数据,那么您需要创建简单的@Controller。

@Controller
public class RestEndpoint {

    @Autowired
    private SomeRepository someRepository;

    @RequestMapping(value="/findByID", method=RequestMethod.GET, produces=MediaType.APPLICATION_XML_VALUE)
    public @ResponseBody MyXmlAnnotatedObject findById(@Param("id") BigInteger id) {

        return someRepository.findById(id);
    }

}

UPD:以下是官方Spring文档的链接:http://docs.spring.io/spring-data/rest/docs/2.1.4.RELEASE/reference/html/repository-resources.html

**3.6 The query method resource**
The query method resource executes the query exposed through an individual query method on the repository interface.

**3.6.1 Supported HTTP methods**

As the search resource is a read-only resource it supports GET only.

**GET**

Returns the result of the query execution.

**Parameters**

If the query method has pagination capabilities (indicated in the URI template pointing to the resource) the resource takes the following parameters:

page - the page number to access (0 indexed, defaults to 0).
size - the page size requested (defaults to 20).
sort - a collection of sort directives in the format ($propertyname,)+[asc|desc]?.
**Supported media types**

application/hal+json
application/json

答案 1 :(得分:2)

请不要因为恋尸癖而责怪我,但我已经创建了一个能够满足您需求的例子:https://github.com/sergpank/spring-boot-xml

简而言之,您应该告诉平台您在POST请求的标题中需要XML(如果您使用像Postman这样的工具进行测试):

Accept : application/xml
Content-Type : application/xml

如果您要将XML消息转换器设置为RestTemplate:

,它将自动完成
public class RestfulClient {

    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate(Arrays.asList(new Jaxb2RootElementHttpMessageConverter()));

        Contact random = restTemplate.getForObject("http://localhost:8080/contact/random", Contact.class);
        System.out.println("Received: " + random);

        Contact edited = restTemplate.postForObject("http://localhost:8080/contact/edit", random, Contact.class);
        System.out.println("Edited: " + edited);
    }
}

不要忘记使用 @XmlRootElement @XmlElement 注释(如果您更喜欢JAXB)注释您的课程:

@AllArgsConstructor
@NoArgsConstructor
@ToString
@Setter
@XmlRootElement
public class Contact implements Serializable {
    @XmlElement
    private Long id;

    @XmlElement
    private int version;

    @Getter private String firstName;

    @XmlElement
    private String lastName;

    @XmlElement
    private Date birthDate;

    public static Contact randomContact() {
        Random random = new Random();
        return new Contact(random.nextLong(), random.nextInt(), "name-" + random.nextLong(), "surname-" + random.nextLong(), new Date());
    }
}

您的控制器中的方法还应该有 @RequestBody 注释来解组XML和 @ResponseBody 注释来编组回复XML。

@Controller
@RequestMapping(value="/contact")
public class ContactController {
    final Logger logger = LoggerFactory.getLogger(ContactController.class);

    @RequestMapping("/random")
    @ResponseBody
    public Contact randomContact() {
        return Contact.randomContact();
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    public Contact editContact(@RequestBody Contact contact) {
        logger.info("Received contact: {}", contact);
        contact.setFirstName(contact.getFirstName() + "-EDITED");
        return contact;
    }
}

答案 2 :(得分:-1)

以下代码在我的Application for return XML content

中工作正常

XML RESPONSE FORMAT

代码:

            @SpringBootApplication
            @Configuration
            @ComponentScan
            @EnableAutoConfiguration
            @EnableScheduling
            public class Application extends SpringBootServletInitializer{



               public static void main(String[] args) {
                  SpringApplication.run(Application.class, args);
               }

               @Override
               protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
                   return application.sources(Application.class);
               }

               private static Class<Application> applicationClass = Application.class;

            }

=============================================== ==========================

        @RestController
        public class PersonController {

            @Autowired
            private PersonRepository personRepository;

            @RequestMapping(value = "/persons/{id}", method = RequestMethod.GET,produces={MediaType.APPLICATION_XML_VALUE},headers = "Accept=application/xml")
            public ResponseEntity<?> getPersonDetails(@PathVariable Long id, final HttpServletRequest request)throws Exception {
                Person personResponse=personRepository.findPersonById(id);
                return ResponseEntity.ok(personResponse);
            }

        }

=============================================== =======================

POM.xml
--------


                <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
                <modelVersion>4.0.0</modelVersion>
                <groupId>com.subu</groupId>
                <artifactId>SpringBootExamples</artifactId>
                <version>0.0.1-SNAPSHOT</version>
                <packaging>war</packaging>
                <parent>
                    <groupId>io.spring.platform</groupId>
                    <artifactId>platform-bom</artifactId>
                    <version>2.0.1.RELEASE</version>
                </parent>
                <properties>
                    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
                    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
                    <java.version>1.7</java.version>
                </properties>
                 <repositories>
                    <repository>
                        <id>vaadin-addons</id>
                        <url>http://maven.vaadin.com/vaadin-addons</url>
                        <snapshots>
                            <enabled>true</enabled>
                        </snapshots>
                    </repository>
                </repositories>
                <dependencies>
                    <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter</artifactId>
                    </dependency>
                    <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-devtools</artifactId>
                    </dependency>
                    <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-data-jpa</artifactId>
                    </dependency>
                    <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-jdbc</artifactId>
                    </dependency>
                    <dependency>
                        <groupId>com.vaadin</groupId>
                        <artifactId>vaadin-spring-boot-starter</artifactId>
                        <version>1.0.1</version>
                    </dependency>
                    <dependency>
                        <groupId>org.postgresql</groupId>
                        <artifactId>postgresql</artifactId>
                        <scope>runtime</scope>
                    </dependency>
                    <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-tomcat</artifactId>
                        <scope>provided</scope>
                    </dependency>
                    <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-test</artifactId>
                        <scope>test</scope>
                    </dependency>
                    <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-web</artifactId>
                        <exclusions>
                            <exclusion>
                                <groupId>org.springframework.boot</groupId>
                                <artifactId>spring-boot-starter-tomcat</artifactId>
                            </exclusion>
                        </exclusions>
                    </dependency>
                    <dependency>
                        <groupId>com.google.guava</groupId>
                        <artifactId>guava</artifactId>
                    </dependency>
                    <dependency>
                        <groupId>com.vaadin.tapio</groupId>
                        <artifactId>googlemaps</artifactId>
                        <version>1.3.4</version>
                    </dependency>
                    <dependency>
                        <groupId>commons-beanutils</groupId>
                        <artifactId>commons-beanutils</artifactId>
                    </dependency>
                    <dependency>
                        <groupId>commons-collections</groupId>
                        <artifactId>commons-collections</artifactId>
                    </dependency>
                    <dependency>
                        <groupId>org.freemarker</groupId>
                        <artifactId>freemarker</artifactId>
                    </dependency>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.1.38</version>
                    </dependency>
                    <dependency>
                        <groupId>com.zaxxer</groupId>
                        <artifactId>HikariCP</artifactId>
                        <version>2.4.5</version>
                    </dependency>
                    <dependency>
                        <groupId>com.fasterxml.jackson.dataformat</groupId>
                        <artifactId>jackson-dataformat-xml</artifactId>
                    </dependency>
                       <dependency>
                    <groupId>org.codehaus.woodstox</groupId>
                    <artifactId>woodstox-core-asl</artifactId>
                    <version>4.4.1</version>
                </dependency>
                    <dependency>
                        <groupId>org.eclipse.persistence</groupId>
                        <artifactId>eclipselink</artifactId>
                        <version>2.6.2</version>
                    </dependency>
                    <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-security</artifactId>
                    </dependency>
                </dependencies>
                <dependencyManagement>
                    <dependencies>
                        <dependency>
                            <groupId>com.vaadin</groupId>
                            <artifactId>vaadin-bom</artifactId>
                            <version>7.7.3</version>
                            <type>pom</type>
                            <scope>import</scope>
                        </dependency>
                    </dependencies>
                </dependencyManagement>

                <build>
                    <plugins>
                        <plugin>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-maven-plugin</artifactId>
                        </plugin>
                    </plugins>
                </build>
            </project>