Content Negotiation in Spring Framework

1. Introduction

With what we had done with BeanNameViewResolver, is that we just had created multiple bean views in Spring context to generate the expected output. Spring soon introduced the Content Negotiation strategy, where we can use the traditional RESTful @ResponseBody approach and HTTP message converters, to return desired outputs in JSON or XML, along with some flexibility and dynamicity it provides with the configuration.

Often we need to provide multiple representations (or views) of the same data returned by the controller. This is very elegantly achieved with Content negotiation in Spring.

2. Implementation

To quickly start with the implementation, lets first create a new maven project. Click here to get help on creating your new maven project in Eclipse

Let’s now add the needed dependencies to the pom.xml file.


pom.xml

Open web.xml and make sure you have the proper configuration done.

web.xml

Create a new context file as <servlet name>-servlet.xml, which has to be mvc-dispatcher-servlet.xml with the following content.

mvc-dispatcher-servlet.xml

Note that the component-scanning is applied only to com.jcombat.controller package, so Spring can auto-detect the application controller.

When making an HTTP request, we can specify what type of response we would like to have by setting the Accept header property. But due to improper working of the browsers with Accept headers, we mostly prefer ignoring the Accept headers in a Spring based web applications, which returns output in formats other than the HTML.

With Java Activation Framework (JAF), we don’t need to explicitly specify the media type mappings, instead it gets implicitly done by JAF. To use JAF, we might need to add an extra dependency of activation.jar. Probably we just want to support two output formats i.e. JSON and XML, therefore we are opting out of it and rather specifying the media type mappings explicitly.

It’s now time to write the controller, which should be like specified below.

EmployeeController.java

3. Useful Links

4. Running the application

When we run the application, below is what we see.

JSON Output

Content Negotiation - JSON output

XML Output

Content negotiation - xml output

5. Download the source code

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.