Spring RESTful Web Services Hello World XML Example

In this Spring RESTful Web Services example, we will learn how to create a RESTful Web Services directly through Spring Framework rather than creating it through REST implementation such as Jersey. In this article, we will create a REST service which returns XML representation of the Object.

Folder Structure:

Spring RESTful Web Services

  1. Create a simple Maven Project “SpringRestTutorial” and create a package for our source files com.javainterviewpointunder  src/main/java 
  2. Now add the following dependency in the 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%20http://maven.apache.org/maven-v4_0_0.xsd">
     <modelVersion>4.0.0</modelVersion>
     <groupId>com.javainterviewpoint</groupId>
     <artifactId>SpringSecurity</artifactId>
     <packaging>war</packaging>
     <version>0.0.1-SNAPSHOT</version>
     <name>SpringSecurity Maven Webapp</name>
     <url>http://maven.apache.org</url>
     <properties>
     <spring.version>4.1.4.RELEASE</spring.version>
     <jstl.version>1.2</jstl.version>
     </properties>
       <dependencies>
        <!-- Spring mvc 4 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>
       <!-- jstl for jsp page -->
       <dependency>
         <groupId>jstl</groupId>
         <artifactId>jstl</artifactId>
         <version>${jstl.version}</version>
       </dependency>
       <!-- Jackson Dependency -->
       <dependency>
         <groupId>com.fasterxml.jackson.core</groupId>
         <artifactId>jackson-databind</artifactId>
         <version>2.8.1</version>
       </dependency>
      </dependencies>
     <build>
     <finalName>SpringRestTutorial</finalName>
     </build>
    </project>
  3. Create the Java classes SpringRestController.java, Student.java and StudentList.java under  com.javainterviewpoint folder.
  4. Place the SpringRest-servlet.hbm.xml, web.xml under WEB-INF folder

Spring RESTful Web Services XML Example

Student.java

We need to annotate our POJO class with JAXB annotations so that JAXB can marshal the Java Object into XML

package com.javainterviewpoint;

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

@XmlRootElement(name="Student")
@XmlAccessorType(XmlAccessType.NONE)
public class Student
{
    @XmlAttribute
    private int id;
    @XmlAttribute
    private String name;
    @XmlAttribute
    private int age;
    public Student()
    {
        super();
    }
    public Student(int id, String name, int age)
    {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }
    
    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public int getAge()
    {
        return age;
    }
    public void setAge(int age)
    {
        this.age = age;
    }
    
    @Override
    public String toString()
    {
        return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
    }
}

StudentList.java

package com.javainterviewpoint;

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="students")
public class StudentList
{
    List studentList = new ArrayList();

    public List getStudentList()
    {
        return studentList;
    }

    public void setStudentList(List studentList)
    {
        this.studentList = studentList;
    }
}

Spring REST Controller

package com.javainterviewpoint;

import java.util.ArrayList;
import java.util.List;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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
public class SpringRestController
{
    @RequestMapping(value="/student/{id}",method=RequestMethod.GET)
    public ResponseEntity getStudentById(@PathVariable("id") int id)
    {
        if(id == 2)
            return new ResponseEntity((new Student(2,"Student2",22)),HttpStatus.OK);
        
        return new ResponseEntity(HttpStatus.NOT_FOUND);
    }
    @RequestMapping(value="/allstudents",method=RequestMethod.GET)
    public  StudentList getAllStudents()
    {
        System.out.println("asdfasdf");
        Student student1 = new Student(1,"Student1",11);
        Student student2 = new Student(2,"Student2",22);
        Student student3 = new Student(3,"Student3",33);
        Student student4 = new Student(4,"Student4",44);
        
        List studentList = new ArrayList();
        studentList.add(student1);
        studentList.add(student2);
        studentList.add(student3);
        studentList.add(student4);
        
        StudentList sl = new StudentList();
        sl.setStudentList(studentList);
        
        return sl;
    }
}
  • We have used the annotation @RestController to mark our class as a Spring Rest Controller as a Controller, Till Spring 3 we would be using @Controller annotation and it makes the @ResponseBody annotation as a mandatory one. @RestController is a combination of @Controller and @ResponseBody.
  • We have two servers getStudentById() and getAllStudents()
    • getStudentById () – This method returns the Student XML corresponding to the requested id.
    • getAllStudents () – This method returns a List of all Students.
  • All the response returned will be in the XML format we will be relying on the “Jaxb2RootElementHttpMessageConverter” for the marshaling Java Object to XML which is by default provided by Spring.
  • We are returning the response for the method getStudentById() as ResponseEntity so that we can send the HttpStatus along with the response.

web.xml

The web.xml has everything about the application that a server needs to know, which is placed under the WEB-INF directory. <servlet-name> contains the name of the SpringConfiguration , when the DispatcherServlet is initialized the framework will try to load a configuration file [servlet-name]-servlet.xml” under the WEB-INF directory.

<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee%20http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
   <display-name>SpringMVCFormHandling</display-name>
   <welcome-file-list>
       <welcome-file>index.html</welcome-file>
       <welcome-file>index.htm</welcome-file>
       <welcome-file>index.jsp</welcome-file>
       <welcome-file>default.html</welcome-file>
       <welcome-file>default.htm</welcome-file>
       <welcome-file>default.jsp</welcome-file>
   </welcome-file-list>
   <servlet>
       <servlet-name>SpringRest</servlet-name>
       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
   </servlet>
   <servlet-mapping>
      <servlet-name>SpringRest</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>
</web-app>

SpringRest-servlet.xml

The SpringRest-servlet.xml is also placed under the WEB-INF directory.

  • <context:component-scan> will let the Spring Container to search for all the annotation under the package “com.javainteriviewpoint”.
  • <mvc:annotation-driven/> annotation will activate the @Controller, @RequestMapping, @Valid etc annotations.
  • The view is resolved through “org.springframework.web.servlet.view.InternalResourceViewResolver” which searches for the jsp files under the /WEB-INF/Jsp/ directory.
<?xml version="1.0" encoding="UTF-8"?>
<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"
 xmlns:p="http://www.springframework.org/schema/p"
 xmlns:jee="http://www.springframework.org/schema/jee"
 xsi:schemaLocation=
 "http://www.springframework.org/schema/beans%20http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/context%20http://www.springframework.org/schema/context/spring-context.xsd
 http://www.springframework.org/schema/mvc%20http://www.springframework.org/schema/mvc/spring-mvc.xsd
 http://www.springframework.org/schema/jee%20http://www.springframework.org/schema/jee/spring-jee.xsd" >
 
    <mvc:annotation-driven/>
 
    <context:component-scan base-package="com.javainterviewpoint"></context:component-scan>
 
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/Jsp/"></property>
        <property name="suffix" value=".jsp"></property>
     </bean>
 </beans>

Output : 

I will be using POSTMAN client for testing my Restful Web services, you can choose any client of your choice

Hit on the URL : http://localhost:8080/SpringRestTutorial/student/2

Spring REST Web Services - 1

Suppose if we are hitting on the URL for which the Student doesn’t exist, then we will be getting the 404 Status.

URL : http://localhost:8080/SpringRestTutorial/student/3

Spring REST Web Services - 3

Hit on the URL : http://localhost:8080/SpringRestTutorial/allstudents

Spring REST Web Services - 2

 

Leave a Reply

Your email address will not be published. Required fields are marked *