Spring REST Webservices Tutorial

In this tutorial we will see how to implement Spring REST  Web services? Spring MVC framework also produces REST resources with content type as JSON or XML. Click here to access Spring MVC tutorial before stepping into this tutorial so that will get idea on using MVC framework.

What is REST?

  • Representational State Transfer  and that  are built around Resources. REST services are Stateless and uses a Uniform Interface
  • Click here to study REST concepts and JAX-RS annotation
  • Spring will not use JAR-RS annotations and it uses Spring web MVC annotation to map URI resources

 

URL1: http://localhost:8080/spring-rest-tutorial/rest/student/getstudentinfo/30303

Spring REST XML Response:

<Response xmlns="http://localhost/spring-rest-tutorial/rest/getdetails">
 <description>Spring REST Annotation tutorial</description>
 <name>Javasavvy</name>
 <productId>1222</productId>
</Response>

Spring REST JSON Response:

HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Mon, 21 Nov 2016 11:01:48 GMT
{"studentId":30303,"name":"Javasavvy","description":"Spring REST Annotation tutorial"}

Spring REST JSON or XML Tutorial:

  1. In this tutorial, we will create spring rest maven project. In the eclipse, Click on File->New-> Maven->Maven Project and select “Create Simple Project” in the selectionSpring REST Tutorial
  2. spring 4 maven pom file: Create the project structure as shown below and copy the below pom.xml dependencies
    • <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/xsd/maven-4.0.0.xsd">
       <modelVersion>4.0.0</modelVersion>
       <groupId>org.javasavvy.rest</groupId>
       <artifactId>spring-rest-tutorial</artifactId>
       <version>0.0.1-SNAPSHOT</version>
       <packaging>war</packaging>
       <properties>
       <springframework.version>4.0.6.RELEASE</springframework.version>
       <hibernate.version>4.3.6.Final</hibernate.version>
       <mysql.version>5.1.31</mysql.version>
       <joda-time.version>2.3</joda-time.version>
       <log4j.version>1.2.17</log4j.version>
       <mail.version>1.4.1</mail.version>
       </properties>
       <build>
       <finalName>spring-rest-tutorial</finalName>
       <directory>target</directory>
       <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
       <outputDirectory>target/classes</outputDirectory>
       <resources>
       <resource>
       <directory>${project.basedir}/src/main/resources</directory>
       <filtering>false</filtering>
       </resource>
       </resources>
       </build>
       <dependencies>
       <!-- Spring -->
       <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-core</artifactId>
       <version>${springframework.version}</version>
       </dependency>
       <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-context</artifactId>
       <version>${springframework.version}</version>
       </dependency>
       <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-tx</artifactId>
       <version>${springframework.version}</version>
       </dependency>
       <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-orm</artifactId>
       <version>${springframework.version}</version>
       </dependency>
       <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-web</artifactId>
       <version>${springframework.version}</version>
       </dependency>
       <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-webmvc</artifactId>
       <version>${springframework.version}</version>
       </dependency>
       <!-- Hibernate -->
       <dependency>
       <groupId>org.hibernate</groupId>
       <artifactId>hibernate-core</artifactId>
       <version>${hibernate.version}</version>
       </dependency>
       <dependency>
       <groupId>org.hibernate</groupId>
       <artifactId>hibernate-c3p0</artifactId>
       <version>${hibernate.version}</version>
       </dependency>
       <dependency>
       <groupId>org.hibernate</groupId>
       <artifactId>hibernate-entitymanager</artifactId>
       <version>${hibernate.version}</version>
       </dependency>
       <!-- MySQL -->
       <dependency>
       <groupId>mysql</groupId>
       <artifactId>mysql-connector-java</artifactId>
       <version>${mysql.version}</version>
       </dependency>
       <dependency>
       <groupId>org.apache.tomcat</groupId>
       <artifactId>tomcat-dbcp</artifactId>
       <version>8.0.15</version>
       </dependency>
       <!-- Joda-Time -->
       <dependency>
       <groupId>joda-time</groupId>
       <artifactId>joda-time</artifactId>
       <version>${joda-time.version}</version>
       </dependency>
      
       <!-- To map JodaTime with database type -->
       <dependency>
       <groupId>org.jadira.usertype</groupId>
       <artifactId>usertype.core</artifactId>
       <version>3.0.0.CR1</version>
       </dependency>
      
       <!-- Java Servlet -->
       <dependency>
       <groupId>javax.servlet</groupId>
       <artifactId>servlet-api</artifactId>
       <version>2.5</version>
       <scope>provided</scope>
       </dependency>
       <dependency>
       <groupId>javax.servlet.jsp</groupId>
       <artifactId>jsp-api</artifactId>
       <version>2.1</version>
       <scope>provided</scope>
       </dependency>
       <dependency>
       <groupId>jstl</groupId>
       <artifactId>jstl</artifactId>
       <version>1.2</version>
       </dependency>
       <!-- Apapche Commons -->
       <dependency>
       <groupId>javax.mail</groupId>
       <artifactId>mail</artifactId>
       <version>${mail.version}</version>
       <exclusions>
       <exclusion>
       <groupId>javax.activation</groupId>
       <artifactId>activation</artifactId>
       </exclusion>
       </exclusions>
       </dependency>
       <dependency>
       <groupId>commons-fileupload</groupId>
       <artifactId>commons-fileupload</artifactId>
       <version>1.2</version>
       </dependency>
       <dependency>
       <groupId>commons-io</groupId>
       <artifactId>commons-io</artifactId>
       <version>1.3</version>
       </dependency>
      
       <!-- Google JSON -->
       <dependency>
       <groupId>javax.servlet</groupId>
       <artifactId>jstl</artifactId>
       <version>1.2</version>
       <scope>compile</scope>
       </dependency>
       <dependency>
       <groupId>com.google.code.gson</groupId>
       <artifactId>gson</artifactId>
       <version>2.2.2</version>
       </dependency>
       <dependency>
       <groupId>org.codehaus.jackson</groupId>
       <artifactId>jackson-mapper-asl</artifactId>
       <version>1.9.10</version>
       </dependency>
       <!-- LOG4J -->
       <dependency>
       <groupId>log4j</groupId>
       <artifactId>log4j</artifactId>
       <version>${log4j.version}</version>
       </dependency>
       </dependencies>
      </project>
  3. Run the maven install target (Right click on project -> Select Run As ->Maven Install). It will download all required  dependencies
  4. Create web.xml file and add  dispatcher servlet entry there
    • <servlet>
           <servlet-name>rest-dispatcher</servlet-name>
               <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
               <init-param>
                        <param-name>contextConfigLocation</param-name>
                         <param-value>/WEB-INF/config/mvcConfig.xml</param-value>
                  </init-param>
               <load-on-startup>1</load-on-startup>
           </servlet>
       <servlet-mapping>
             <servlet-name>rest-dispatcher</servlet-name>
              <url-pattern>/rest/*</url-pattern>
       </servlet-mapping>
  5. Spring REST webservices is enabled with annotation mapping with below configuration:
    1. <?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:p="http://www.springframework.org/schema/p"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
       <context:annotation-config /> 
       <mvc:annotation-driven />
       <context:component-scan base-package="org.javasavvy.rest.controller" />
       <mvc:resources mapping="/resources/**" location="/resources/" />
       <bean
       class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
       <bean
       class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
      
      </beans>
  6. Create Rest Controller that should annotated with @Controller
    • Add @RequestMapping annotation with “/student”
    • Add @ResponseBody on method declaration and return object
    • Spring 4 Users new @RestController annotation, which marks the class as a controller where  returns a domain object instead of a view.  @RestController is equivalant to  @Controller and @ResponseBody together.
    • In this tutorial, we are exposing below web services:
      • http://localhost:8080/spring-rest-tutorial/rest/student/getstudentinfo/30303  – getStudentInfo method will be invoked
      • It will return student as Object (JSON or XML) by default it returns XML, you may need to provide content-type as application/json in header to get JSON content:
    • Sample Code:
    • package org.javasavvy.rest.controller;
      import java.util.ArrayList;
      import java.util.List;
      import org.javasavvy.rest.modal.Student;
      import org.springframework.http.MediaType;
      import org.springframework.stereotype.Controller;
      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.ResponseBody;
      
      @Controller
      @RequestMapping("/student")
      public class StudentController {
      
       @RequestMapping(value="/get-all-students")
       public @ResponseBody List<Student> getAllStudents(){
       
       List<Student> list = new ArrayList<Student>();
        Student st = new Student();
       st.setDescription("Spring REST Annotation tutorial");
       st.setStudentId(1001L);
       st.setName("Jay");
       list.add(st);
        Student st2 = new Student();
       st2.setDescription("Spring REST JSON Response Tutorial");
       st2.setStudentId(1001);
       st2.setName("vijay");
       list.add(st2);
       
       return list;
       }
       @RequestMapping(value="/getstudentinfo/{studentId}")
       public @ResponseBody Student getStudent(@PathVariable("studentId") Long studentId){
        Student st = new Student();
       st.setDescription("Spring REST Annotation tutorial");
       st.setStudentId(studentId);
       st.setName("Javasavvy");
       return st;
       }
       @RequestMapping(value="/add-student",method=RequestMethod.POST,consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE},
       produces={MediaType.APPLICATION_JSON_VALUE,MediaType.APPLICATION_JSON_VALUE})
       public @ResponseBody Student addProduct(@RequestBody Student st){
       
       System.out.println("pr"+st.getName());
       return st;
       }
      }
       
      
  7. Now configure the tomcat server
  8. Right click – > Select Run As -> Run on Server
  9. Now you can access below url in brower: http://localhost:8080/spring-rest-tutorial/rest/student/getstudentinfo/30303
  10. You can use SOAP UI client to test the web services

Spring REST JSON Tutoria

 

Download Spring REST JSON Maven Example:

 Click Here to download Spring REST MVC tutorial

3 Comments

  1. Pingback: spring rest tutorial, spring json rest example,Spring REST JSON example

  2. Pingback: Jersey Spring integration,Jersey + Spring Tutorial,Jersey spring 4 maven

  3. Bala

    Have you done same in liferay DXP

    Reply

Leave a Comment

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