This tutorial introduces Spring MVC Content Negotiation Viewresolver XML JSON Example. Spring MVC Content Negotiation features help you response different types of a document at the same URI. The best appropriate response will be served to fit your request. In this tutorial, we will create the example that negotiate between XML and JSON using HTTP Accept header or file extension.
Table of contents:
1. Maven Dependency
2. Project structure
3. Spring MVC Content Negotiation XML JSON Configuration
4. Controller Endpoint
5. Spring MVC Content Negotiation Viewresolver XML JSON Example
Other interesting posts you may like
Maven Dependency
We need to use the following dependencies that supports to create excel document and pdf document.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
<?xml version="1.0" encoding="UTF-8"?> <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.javabycode.spring.mvc</groupId> <artifactId>Xml-Json-Viewresovler-Example</artifactId> <version>1.0.0-SNAPSHOT</version> <name>SPRING-MVC - ${project.artifactId}</name> <url>http://javabycode.com</url> <packaging>war</packaging> <properties> <encoding>UTF-8</encoding> <spring.version>4.3.0.RELEASE</spring.version> </properties> <dependencies> <!-- spring libraries --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- xml --> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> <version>2.7.4</version> </dependency> <!-- servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <finalName>xml-json-viewresolver</finalName> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project> |
Project structure
Spring MVC Content Negotiation XML JSON Configuration
Here, we need to create the content negotiation manager by extending the WebMvcConfigurerAdapter and override two methods configureContentNegotiation and configureViewResolvers.
The configureContentNegotiation(ContentNegotiationConfigurer configurer) method is used to register a default content type.
The configureViewResolvers(ViewResolverRegistry registry) method is used to register different view resolvers that the application can serve. In this code snippet we register both the MappingJackson2XmlView for serving XML and the MappingJackson2JsonView for serving JSON.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
package com.javabycode.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.web.servlet.config.annotation.*; import org.springframework.web.servlet.view.json.MappingJackson2JsonView; import org.springframework.web.servlet.view.xml.MappingJackson2XmlView; @EnableWebMvc @Configuration @ComponentScan("com.javabycode") public class MyWebConfig extends WebMvcConfigurerAdapter { @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer .defaultContentType(MediaType.APPLICATION_JSON_UTF8) .parameterName("type") .favorParameter(true) .ignoreUnknownPathExtensions(false) .ignoreAcceptHeader(false) .useJaf(true); } @Override public void configureViewResolvers(ViewResolverRegistry registry) { registry.enableContentNegotiation( new MappingJackson2XmlView(), new MappingJackson2JsonView()); } } |
This is the same Spring XML configuration as above.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<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"> <mvc:annotation-driven/> <context:component-scan base-package="com.javabycode" /> <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean"> <property name="defaultContentType" value="APPLICATION_JSON_UTF8"/> <property name="parameterName" value="type"/> <property name="favorParameter" value="true"/> <property name="ignoreUnknownPathExtensions" value="false"/> <property name="ignoreAcceptHeader" value="false"/> <property name="useJaf" value="true"/> </bean> <mvc:view-resolvers> <mvc:content-negotiation> <mvc:default-views> <bean class="org.springframework.web.servlet.view.xml.MappingJackson2XmlView"/> <bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/> </mvc:default-views> </mvc:content-negotiation> </mvc:view-resolvers> </beans> |
Notices: we need to use the DispatcherServlet to mapping the request to the correct controller methods. It is the same DispatcherServlet of the previous Spring MVC so it is not mentioned here or you can see it in the source code attachment.
Controller Endpoint
This Fruit POJO is used to add content to the XML and JSON response.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
package com.javabycode.model; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Fruit { private Integer id; private String name; private String produceBy; public Fruit() { } public Fruit(Integer id, String name, String produceBy){ this.id = id; this.name = name; this.produceBy = produceBy; } public Integer getId() { return id; } public String getName() { return name; } public String getProduceBy() { return produceBy; } } |
The FruitsController is responsible to create and return an instance of the Fruit class for Model which be used to display in XML or JSON format.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.javabycode.controller; import com.javabycode.model.Fruit; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/viewfruit") public class FruitsController { @RequestMapping(value="/{id}", method = RequestMethod.GET) public Fruit getCourse(@PathVariable Integer id, ModelMap model) { return new Fruit(id, "Orange", "Indonesia"); } } |
Deploy Spring MVC Content Negotiation Viewresolver XML JSON Example
Building project with maven then deploy file war on application server or servlet container (Tomcat 8 for example).
We access the address with a file extension URL http://localhost:8080/xml-json-viewresolver/viewfruit/1.xml or the address with special request parameter of type xml URL http://localhost:8080/xml-json-viewresolver/viewfruit/1?type=xml, the screen will display the xml response such as the picture
To view JSON response we need to pass a HTTP “Accept: application/json” header with request. Here we put the URL http://localhost:8080/xml-json-viewresolver/viewfruit/1 in the form DHC plugin on Chrome to pass HTTP “Accept: application/json” header via request. The json content should be such as the below screen shot.
That’s it on the tutorial Spring MVC Content Negotiation Viewresolver XML JSON Example. You can also refer to other view resolver example such as Spring MVC Excel Pdf ViewResolver Example
Download complete source code of example, please click link below
spring-mvc-xml-json-viewresovler-example.zip (310 downloads)