Spring 4 REST XML Response Example with Jackson 2
June 29, 2016
On this page we will provide spring 4 REST web service XML response example with Jackson 2. We need to configure message converter to read and write XML. Spring provides MappingJackson2XmlHttpMessageConverter
to achieve this purpose when using Jackson and is instantiated using custom ObjectMapper
which is customized to indent the XML code, configure date format etc. The bean will be created using @JacksonXmlRootElement
and @JacksonXmlProperty
. The controller will expose REST web service method that will produce media type as application/xml. In our demo we will use java configuration as well as XML configuration to configure message converter. Now find the complete example.
Contents
- Software Used
- Project Structure in Eclipse for Java Configuration
- Gradle File to Resolve Spring and Jackson 2 JAR Dependencies
- Java Configuration for MappingJackson2XmlHttpMessageConverter
- Create Bean with @JacksonXmlRootElement and @JacksonXmlProperty
- Create Controller using @RestController
- Create Web Application Initializer
- Project Structure in Eclipse for XML Configuration
- XML Configuration for MappingJackson2XmlHttpMessageConverter
- web.xml
- Run Application
- Download Complete Source Code
Software Used
Find the software used in our example.1. Java 8
2. Spring 4.2.6.RELEASE
3. Jackson 2.7.5
4. Tomcat 8
5. Eclipse
6. Gradle
Project Structure in Eclipse for Java Configuration
Find the project structure in eclipse for java configuration.Gradle File to Resolve Spring and Jackson 2 JAR Dependencies
Find gradle file to resolve spring and Jackson 2 JAR dependencies and build the project.build.gradle
apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'war' archivesBaseName = 'spring-rest' version = '1' repositories { mavenCentral() } dependencies { compile 'org.springframework.boot:spring-boot-starter-web:1.3.5.RELEASE' compile 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.7.5' compile 'org.codehaus.woodstox:woodstox-core-asl:4.4.1' }
Java Configuration for MappingJackson2XmlHttpMessageConverter
To get XML response we need to use message converter. Jackson 2 providesMappingJackson2XmlHttpMessageConverter
that is being configured using Jackson2ObjectMapperBuilder
.
AppConfig.java
package com.concretepage.config; import java.util.List; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration @ComponentScan("com.concretepage") @EnableWebMvc public class AppConfig extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.xml(); builder.indentOutput(true); converters.add(new MappingJackson2XmlHttpMessageConverter(builder.build())); } }
HttpMessageConverters
that reads and writes request and response body.
Jackson2ObjectMapperBuilder : This is a builder to create
ObjectMapper
instance.
MappingJackson2XmlHttpMessageConverter: It is used to read and write XML.
Create Bean with @JacksonXmlRootElement and @JacksonXmlProperty
Find the bean whose instance will be converted in XML data.Company.java
package com.concretepage; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; @JacksonXmlRootElement(localName="company-info", namespace="com.concretepage") public class Company { @JacksonXmlProperty(localName="id", isAttribute=true) private Integer id; @JacksonXmlProperty(localName="company-name") private String companyName; @JacksonXmlProperty(localName="ceo-name") private String ceoName; @JacksonXmlProperty(localName="no-emp") private Integer noEmp; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public String getCeoName() { return ceoName; } public void setCeoName(String ceoName) { this.ceoName = ceoName; } public Integer getNoEmp() { return noEmp; } public void setNoEmp(Integer noEmp) { this.noEmp = noEmp; } }
XmlRootElement
that defines the name of the root element.
@JacksonXmlProperty : It defines XML specific properties. It has a boolean attribute
isAttribute
. If it is true, the class filed will be converted to an attribute of root tag, otherwise it will be a property of XML response.
Create Controller using @RestController
Now create the controller class using spring 4@RestController
. This class will expose REST web service methods. The method should produce media type as application/xml.
CompanyController.java
package com.concretepage; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/app") public class CompanyController { @RequestMapping(value= "/fetch/{id}", produces = MediaType.APPLICATION_XML_VALUE) public Company getForObjectXMLDemo(@PathVariable(value = "id") Integer id) { Company comp = new Company(); comp.setId(id); comp.setCompanyName("XYZ"); comp.setCeoName("ABCD"); comp.setNoEmp(100); return comp; } }
Create Web Application Initializer
Now we create web application initializer.WebAppInitializer.java
package com.concretepage.config; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[] { AppConfig.class }; } @Override protected Class<?>[] getServletConfigClasses() { return null; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } }
Project Structure in Eclipse for XML Configuration
We will also discuss how to configure message converter in XML configuration. Find the project structure in eclipse.XML Configuration for MappingJackson2XmlHttpMessageConverter
Here we will configureMappingJackson2XmlHttpMessageConverter
using XML configuration.
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.concretepage"/> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter"> <property name="objectMapper" ref="xmlMapper"/> </bean> </mvc:message-converters> </mvc:annotation-driven> <bean id="xmlMapper" parent="objectMapper"> <property name="createXmlMapper" value="true"/> </bean> <bean id="objectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"> <property name="indentOutput" value="true"/> </bean> </beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Spring 4 REST XML Example</display-name> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/dispatcher-servlet.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
Run Application
Find the steps to run the example.1. Download source code and navigate to the root directory of the project using command prompt.
2. Run the gradle command gradle clean build to create WAR file.
3. Deploy WAR in tomcat and access the URL
http://localhost:8080/spring-rest-1/app/fetch/15
4. View the source code. The output will be as follows.
<company-info xmlns="com.concretepage" id="15"> <company-name xmlns="">XYZ</company-name> <ceo-name xmlns="">ABCD</ceo-name> <no-emp xmlns="">100</no-emp> </company-info>