I made a simple REST webservice with Spring Boot 1.2.5 and it works fine for JSON but I can't make this work to return XML.
This is my controller:
@RestController
..
@RequestMapping(method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
@ResponseStatus(HttpStatus.OK)
public List<Activity> getAllActivities() {
return activityRepository.findAllActivities();
}
When I call it with Accept: application/json
everything works, but when I try with application/xml
I get some HTML with 406 Error and message:
The resource identified by this request is only capable of generating responses
with characteristics not acceptable according to the request "accept" headers.
My model objects:
@XmlRootElement
public class Activity {
private Long id;
private String description;
private int duration;
private User user;
//getters & setters...
}
@XmlRootElement
public class User {
private String name;
private String id;
//getters&setters...
}
My pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.5.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
Do I need some additional jars in my pom.xml to make this work? I tried adding jaxb-api or jax-impl but it didn't help.
To make this work in Spring Boot without using Jersey we need to add this dependency:
The output will be a bit ugly but it works:
Here is nice tutorial: http://www.javacodegeeks.com/2015/04/jax-rs-2-x-vs-spring-mvc-returning-an-xml-representation-of-a-list-of-objects.html
We can achieve this as below :
Code