Spring MVC - XML response with @ResponseBody annotation (Spring + XML)

Updated for Spring 5+

In today's discussion we will see how to return a XML response from a Spring MVC Controller. @ResponseBody annotation does this job done for us, all we need to do is adding @ResponseBody annotation in front of controller and annotate the object we want to return in xml form. Let's see the functioning of @ResponseBody annotation and how it helps in returning an java object in XML form.


Expected Output

Our objective for today's discussion is clear, we will try to return a Java Object and a list of java objects as xml response to the browser. See screen shots below how this will look like:

Single Java object as xml response(Student.java)



List of Java objects as xml response(List )



Return a Java object as xml response from Spring MVC controller

To return an java object in xml form from an spring objects requires two simple configurations:
1) Annotate Object Class
2) Add @ResponseBody annotation to the controller's method


1) Annotate Object Class

\src\main\java\com\beingjavaguys\domain\Student.java
This is a simple Java class (Student) whose object will be returned in xml form, from the controller. @XmlRootElement defines the root element of xml structure, by default it takes class name as root element. Optionally we can give it s "name" parameter if we want some other name as xm root element. @XmlElement defines internal xml nodes, 'name' attribute applies here as well, as same as with @XmlRootElement.
package com.beingjavaguys.domain;  
  
import javax.xml.bind.annotation.XmlRootElement;  
import javax.xml.bind.annotation.XmlElement;  
  
@XmlRootElement(name = "student")  
public class Student {  
 private int id;  
 private String firstName;  
 private String lastName;  
 private String email;  
 private String phone;  
  
 protected Student() {  
 }  
  
 public Student(int id, String firstName, String lastName, String email,  
   String phone) {  
  this.id = id;  
  this.firstName = firstName;  
  this.lastName = lastName;  
  this.email = email;  
  this.phone = phone;  
 }  
  
 public int getId() {  
  return id;  
 }  
  
 @XmlElement  
 public void setId(int id) {  
  this.id = id;  
 }  
  
 public String getFirstName() {  
  return firstName;  
 }  
  
 @XmlElement  
 public void setFirstName(String firstName) {  
  this.firstName = firstName;  
 }  
  
 public String getLastName() {  
  return lastName;  
 }  
  
 @XmlElement  
 public void setLastName(String lastName) {  
  this.lastName = lastName;  
 }  
  
 public String getEmail() {  
  return email;  
 }  
  
 @XmlElement  
 public void setEmail(String email) {  
  this.email = email;  
 }  
  
 public String getPhone() {  
  return phone;  
 }  
  
 @XmlElement  
 public void setPhone(String phone) {  
  this.phone = phone;  
 }  
}  

2) Add @ResponseBody annotation to the controller's method

\src\main\java\com\beingjavaguys\controller\DataController.java
Second thing we need to do is to use '@ResponseBody' annotation against the controller's method. This will make spring understand that method return value should be bound to the web response body.
package com.beingjavaguys.controller;  
  
import java.util.ArrayList;  
import java.util.List;  
  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.ResponseBody;  
  
import com.beingjavaguys.domain.Student;  
import com.beingjavaguys.domain.StudentList;  
  
@Controller  
public class DataController {  
  
 @RequestMapping("student")  
 public @ResponseBody  
 Student getStudent() {  
  return new Student(23, "Meghna", "Naidu", "meghna@gmail.com",  
    "8978767878");  
 }  
  
 @RequestMapping("studentlist")  
 public @ResponseBody  
 StudentList getStudentList() {  
  List<student> studentList = new ArrayList<student>();  
  studentList.add(new Student(3, "Robert", "Parera", "robert@gmail.com",  
    "8978767878"));  
  studentList.add(new Student(93, "Andrew", "Strauss",  
    "andrew@gmail.com", "8978767878"));  
  studentList.add(new Student(239, "Eddy", "Knight", "knight@gmail.com",  
    "7978767878"));  
  
  return new StudentList(studentList);  
 }  
  
}  


Return a List of Java object as xml response from Spring MVC controller

We just saw how to return an java object in xml form, that was quit simple because we have full control to 'Student' class and hence we could annotate the class easily. In case we want to return a list of objects say 'ArrayList', but we dont have ArrayList class's code to annotate it. So its a bit tricky; we have to make an other class having a list of objects and the object of that annotated class will represent the whole list and will be returned as a list of xml nodes.

\src\main\java\com\beingjavaguys\domain\StudentList.java
package com.beingjavaguys.domain;  
  
import java.util.List;  
  
import javax.xml.bind.annotation.XmlRootElement;  
  
@XmlRootElement(name = "student-list")  
public class StudentList {  
  
 private List<student> studentList;  
  
 protected StudentList() {  
 }  
  
 public StudentList(List<student> studentList) {  
  this.studentList = studentList;  
 }  
  
 @javax.xml.bind.annotation.XmlElement(name = "student")  
 public List<student> getStudentList() {  
  return studentList;  
 }  
}  


That's all we need to know about @ResponseBody annotation and how to return xml response from Spring Controller. Lets now add all other useful files to our project to make it working.

Dependencies required to return xml response from Spring Controller.

pom.xml
<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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.beingjavaguys.sample</groupId>
	<artifactId>SampleSpringMaven</artifactId>
	<packaging>war</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>SampleSpringMaven Maven Webapp</name>
	<url>http://maven.apache.org</url>

	<properties>
		<spring.version>5.1.5.RELEASE</spring.version>
		<jdk.version>1.8</jdk.version>
	</properties>

	<dependencies>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<finalName>SampleSpringMaven</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.0</version>
				<configuration>
					<source>${jdk.version}</source>
					<target>${jdk.version}</target>
				</configuration>
			</plugin>
		</plugins>
	</build>

</project>


Spring configuration file

src\main\webapp\WEB-INF\spring-servlet.xml
This is simple spring configuration file, we have added an entry for our controller's location. Dont forget to add '<mvc:annotation-driven />' this is very important for @ResponseBody annotation to work.
<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
 xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"  
 xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd  
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
  http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd  
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">  
  
 <context:component-scan base-package="com.beingjavaguys.controller" />  
 <mvc:annotation-driven />  
  
</beans>  


src\main\webapp\WEB-INF\web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
       http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
 version="2.5">  
  
 <display-name>Sample Spring Maven Project</display-name>  
  
 <servlet>  
  <servlet-name>spring</servlet-name>  
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  <load-on-startup>1</load-on-startup>  
 </servlet>  
  
 <servlet-mapping>  
  <servlet-name>spring</servlet-name>  
  <url-pattern>*.xml</url-pattern>  
 </servlet-mapping>  
  
</web-app>  

This is all we have added all required files to the project, lets see the overall project structure at once now. Project Structure

If everything goes right and you have configured everything well, run the projct on server and hit following two URL's in the browser.

1)Java Object as xml response : http://localhost:8080/SampleSpringMaven/student.xml
2)Java object's list as xml response: http://localhost:8080/SampleSpringMaven/studentlist.xml

In upcoming blogs we will see more about Spring, Hibernate, Java and Other opensource technologies.


Download source code from: GitHub