Saturday, 14 January 2017

Sending xml(JAXB) and json(Jackson) response with Spring MVC @ResponseBody annotation


In some of our earlier posts we saw examples of how Spring controllers work. 

In those examples we returned a view name from controller method and subsequently corresponding JSP was returned and rendered. In this post we will see how we can send a xml or a json response instead of a JSP.

 Sending xml(JAXB) and json(Jackson) response with Spring MVC @ResponseBody annoatation

Your controller would look like below -

package com.osfg.controllers;

import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.osfg.model.Employee;

 * @author athakur
 * Controller to handle employee information
public class EmployeeController {

    Logger logger = LoggerFactory.getLogger(EmployeeController.class);

    @RequestMapping(value = "/getEmployeeInfoData", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
    public Employee getEmployeeInfo(HttpServletRequest request) {
        logger.debug("Receive GET request for employee data information");
        Employee empForm = new Employee();
        empForm.setName("Aniket Thakur");
        return empForm;

 Most of annotations and code you would already know from previous examples. New thing here is the produces field which is set to 
which mean your controller method can give response in json or xml. 
NOTE : Spring framework matches this produces field with  accepts header of incoming request.

and your Employee model object would look like -

package com.osfg.model;


import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

 * @author athakur
 * Model class for Employee
@XmlRootElement(name = "employee")
public class Employee implements Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private int age;
    public String getName() {
        return name;
    public void setName(String name) { = name;
    public int getAge() {
        return age;
    public void setAge(int age) {
        this.age = age;

Notice the annotations used. Those are required for XML transformation by JAXB library.

NOTE : Don't forget to add <mvc:annotation-driven/>  tag in your spring configuration file.

Once above code and configurations are in place all you have to do is put JAXB and jackson jars on classpath. I am using ivy so add following dependency on youe ivy xml -

<dependency org="com.fasterxml.jackson.core" name="jackson-databind" rev="2.8.5"/>

NOTE : I am using Java 8. JAXB is inbuilt in java since java 7. So no need to explicitly add it.

You can find the working snippet of above code in my github repo -
file of

 Related Links

What's the difference between <mvc:annotation-driven /> and <context:annotation-config /> in servlet?


With Spring 3.0 came mvc name space and along with it came a lot of simplifications in Spring framework. The one that we are going to discuss today is - <mvc:annotation-driven />

This is the simplest tag you can add in your spring configuration file to enable many new features.

This is obvious you spring configuration xml tag. For java equivalent you can add the annotation @EnableWebMvc to one of your @Configuration classes.

public class WebConfig {

The above registers a 
  • RequestMappingHandlerMapping, 
  • a RequestMappingHandlerAdapter, and 
  • an ExceptionHandlerExceptionResolver 
(among others) in support of processing requests with annotated controller methods using annotations such as @RequestMapping, @ExceptionHandler, and others.

What's the difference between <mvc:annotation-driven /> and <context:annotation-config /> in servlet?

With <mvc:annotation-driven /> following features get enabled -

  1. Configures the Spring 3 Type ConversionService (alternative to PropertyEditors)
  2. Adds support for formatting Number fields with @NumberFormat
  3. Adds support for formatting Date, Calendar, and Joda Time fields with @DateTimeFormat, if Joda Time is on the classpath
  4. Adds support for validating @Controller inputs with @Valid, if a JSR-303 Provider is on the classpath
  5. Adds support for support for reading and writing XML, if JAXB is on the classpath (HTTP message conversion with @RequestBody/@ResponseBody)
  6. Adds support for reading and writing JSON, if Jackson is on the classpath (along the same lines as #5)
This is the complete list of HttpMessageConverters set up by mvc:annotation-driven:

  1.  ByteArrayHttpMessageConverter converts byte arrays.  
  2.  StringHttpMessageConverter converts strings. 
  3.  ResourceHttpMessageConverter converts to/from for all media types. 
  4.  SourceHttpMessageConverter converts to/from a javax.xml.transform.Source. 
  5.  FormHttpMessageConverter converts form data to/from a MultiValueMap<String, String>. 
  6.  Jaxb2RootElementHttpMessageConverter converts Java objects to/from XML — added if JAXB2 is present and Jackson 2 XML extension is not present on the classpath. 
  7.  MappingJackson2HttpMessageConverter converts to/from JSON — added if Jackson 2 is present on the classpath. 
  8.  MappingJackson2XmlHttpMessageConverter converts to/from XML — added if Jackson 2 XML extension is present on the classpath. 
  9.  AtomFeedHttpMessageConverter converts Atom feeds — added if Rome is present on the classpath. 
  10.  RssChannelHttpMessageConverter converts RSS feeds — added if Rome is present on the classpath.

context:annotation-config on the other hand looks for annotations on beans in the same application context it is defined and declares support for all the general annotations like @Autowired, @Resource, @Required, @PostConstruct etc etc.

Related Links

t> UA-39527780-1 back to top