Spring REST Hello World XML tutorial with Example

In this tutorial, we will learn to write APIs capable of returning XML representations of resources.

Step 1 :- Open Eclipse and Create Dynamic Web Project named SpringRESTXMLExample

Step 2:- Make sure you use Target Runtime as Apache Tomcat 7.0 and Dynamic web module version as 3.0.

Step 3 :- copy below jars to WEB-INF/lib folder.
  • commons-logging-1.2.jar
  • jackson-annotations-2.6.0.jar
  • jackson-core-2.6.0.jar
  • jackson-databind-2.6.0.jar
  • spring-aop-4.1.4.RELEASE.jar
  • spring-beans-4.1.4.RELEASE.jar
  • spring-context-4.1.4.RELEASE.jar
  • spring-core-4.1.4.RELEASE.jar
  • spring-expression-4.1.4.RELEASE.jar
  • spring-web-4.1.4.RELEASE.jar
  • spring-webmvc-4.1.4.RELEASE.jar
STEP 4:- Create Spring Configuration Bean file. /WebContent/WEB-INF/dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
 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.tutorialsdesk" />
 <mvc:annotation-driven/>
 <bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
 <property name="messageConverters">
 <list>
 <ref bean="xmlMessageConverter"/>
 </list>
 </property>
 </bean>
 
 <bean id="xmlMessageConverter"
class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter"/>
</beans>


Here we are relying on the Spring MVC HttpMessageConverter to convert an object to the xml representation requested by the user. @ResponseBody annotation (included through @RestController) tells Spring MVC that the result of the method should be used as the body of the response. As we want XML this marshaling is done by the Jaxb2RootElementHttpMessageConverter provided by Spring which is automatically registered in spring context if JAXB libraries are found in classpath. As we are using JRE 7 to run this application and it has JAXB inbuilt,

STEP 5:- Map Spring MVC in /WebContent/WEB-INF/web.xml file as below
<?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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
 <display-name>SpringRESTXMLExample</display-name>
 <welcome-file-list>
 <welcome-file>index.html</welcome-file>
 </welcome-file-list>
 <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>
</web-app>


STEP 6:- Create Controller Class
  • package com.tutorialsdesk.controller
  • Filename: EmployeeController.java
package com.tutorialsdesk.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.tutorialsdesk.model.Employee;
import com.tutorialsdesk.model.EmployeeList;

@RestController
public class EmployeeController {

 private static EmployeeList employees = new EmployeeList();
 
 static{
 employees.getEmployees().add(new
Employee(1,"Martin","Gates","martin@tutorialsdesk.com"));
 employees.getEmployees().add(new
Employee(2,"Jhon","Smith","jhon@tutorialsdesk.com"));
 employees.getEmployees().add(new
Employee(3,"Manav","Kushal","manav@tutorialsdesk.com"));
 employees.getEmployees().add(new
Employee(4,"Prince","Sethi","prince@tutorialsdesk.com"));
 }
 
 @RequestMapping(value = "/employees")
 public ResponseEntity<EmployeeList> getAllEmployees()
 {
 if(employees.getEmployees().size() > 0){
 return new ResponseEntity<EmployeeList>(employees, HttpStatus.OK);
 }
 return new ResponseEntity<EmployeeList>(HttpStatus.NOT_FOUND);
 }
 
 @RequestMapping(value = "/employees/create", method = RequestMethod.POST)
 public ResponseEntity<Employee> createEmployee(@RequestBody Employee employee)
 {
 return new ResponseEntity<Employee>(employee,HttpStatus.OK);
 }
 
 @RequestMapping(value = "/employees/{id}")
 public ResponseEntity<Employee> getEmployeeById
(@PathVariable("id") int id)
 {
 for(Employee employee : employees.getEmployees()){
 if(id == employee.getId()){
 return new ResponseEntity<Employee>(employee, HttpStatus.OK);
 }
 }
 
 return new ResponseEntity<Employee>(HttpStatus.NOT_FOUND);
 }
 
 @RequestMapping(value = "/employees/{id}", method = RequestMethod.PUT)
 public ResponseEntity<Employee> updateEmployee(@PathVariable("id")
int id, @RequestBody Employee employee)
 {
 return new ResponseEntity<Employee>(employee, HttpStatus.OK);
 }
 
 @RequestMapping(value = "/employees/{id}", method = RequestMethod.DELETE)
 public ResponseEntity<String> deleteEmployee(@PathVariable("id")
int id)
 {
 return new ResponseEntity<String>(HttpStatus.OK);
 }
}

Instead of returning the java objects directly, you can wrap them inside ResponseEntity. The ResponseEntity is a class in Spring MVC that acts as a wrapper for an object to be used as the body of the result together with a HTTP status code. This provides greater control over what you are returning to client in various use cases. e.g. returning a 404 error if no employee is found for given employee id.

STEP 7:- Create Model Class
  • package com.tutorialsdesk.model
  • Filename: Employee.java
You will need to annotate your model objects with jaxb annotations so that JAXB can marshal the java object into XML representation to be sent to client for that API.
package com.tutorialsdesk.model;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlAccessType;

@XmlRootElement (name = "employee")
@XmlAccessorType(XmlAccessType.NONE)
public class Employee implements Serializable{

 private static final long serialVersionUID = 5088863992478607917L;

 @XmlAttribute
 private Integer id;
 
 @XmlElement
 private String firstName;
 
 @XmlElement
 private String lastName;
 
 @XmlElement
 private String email;

 public Employee(Integer id, String firstName, String lastName, String email) {
 super();
 this.id = id;
 this.firstName = firstName;
 this.lastName = lastName;
 this.email = email;
 }

 public Employee() {
 super();
 }

 public Integer getId() {
 return id;
 }

 public void setId(Integer id) {
 this.id = id;
 }

 public String getFirstName() {
 return firstName;
 }

 public void setFirstName(String firstName) {
 this.firstName = firstName;
 }

 public String getLastName() {
 return lastName;
 }

 public void setLastName(String lastName) {
 this.lastName = lastName;
 }

 public String getEmail() {
 return email;
 }

 public void setEmail(String email) {
 this.email = email;
 }

 public static long getSerialversionuid() {
 return serialVersionUID;
 }

 @Override
 public String toString() {
 return "Employee [id=" + id + ", firstName=" + firstName
 + ", lastName=" + lastName + ", email=" + email + "]";
 }
 
}

STEP 8:- Create Model Class
  • package com.tutorialsdesk.model
  • Filename: EmployeeList.java
package com.tutorialsdesk.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement (name="employees")
public class EmployeeList implements Serializable{

 private static final long serialVersionUID = -7565600226888520442L;
 private List<Employee> employees = new ArrayList<Employee>();
 public List<Employee> getEmployees() {
 return employees;
 }
 
 public void setEmployees(List<Employee> employees) {
 this.employees = employees;
 }
}


STEP 9 :- Run your project enter below URL in your browser

Now when you hit the URL : http://localhost:8080/SpringRESTXMLExample/employees you will get this result.
<?xml version="1.0" encoding="UTF-8"
standalone="yes" ?> 
- <employees>
- <employees id="1">
 <firstName>Martin</firstName> 
 <lastName>Gates</lastName> 
 <email>martin@tutorialsdesk.com</email> 
 </employees>
- <employees id="2">
 <firstName>Jhon</firstName> 
 <lastName>Smith</lastName> 
 <email>jhon@tutorialsdesk.com</email> 
 </employees>
- <employees id="3">
 <firstName>Manav</firstName> 
 <lastName>Kushal</lastName> 
 <email>manav@tutorialsdesk.com</email> 
 </employees>
- <employees id="4">
 <firstName>Prince</firstName> 
 <lastName>Sethi</lastName> 
 <email>prince@tutorialsdesk.com</email> 
 </employees>
 </employees>


If you hit the URL : http://localhost:8080/SpringRESTXMLExample/employees/4 you will get this result.
<employee id="4">
<firstName>Prince</firstName>
<lastName>Sethi</lastName>
<email>prince@tutorialsdesk.com</email>
</employee>


Keep visiting TutorialsDesk for more tutorials and practical programming examples on Spring MVC. Hope we are able to explain you Spring REST Hello World XML Example, if you have any questions or suggestions please write to us using contact us form.

Please share us on social media if you like the tutorial.
SHARE
    Blogger Comment
    Facebook Comment