Creating RESTful services using Spring

                       Smart Techie

                  Before spring supported REST, we used Jersy, RESTeasy, Restlet kind of spring logoframeworks to build the REST web services. From Spring 3, the support to build RESTful web services has been added. In this article, we will develop a sample REST service using spring framework. The steps are given below.

Step 1:  Create a web project using IDE. In this example, I have created web project called “Sample_Spring_REST_Proj“. After the project creation, create a controller which will be responsible to handle the user requests. The controller code is given below.

package org.smarttechies.controller;
import org.smarttechies.User;
import org.springframework.stereotype.Controller;
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.ResponseBody;

@Controller("/user")
public class UserController {

@RequestMapping(value="/{screenName}", method = RequestMethod.GET, headers="Accept=*/*")
@ResponseBody
public User getUser(@PathVariable String screenName) {

  //Send request to API or DAO layer to get the user information
  User user = new User();
  user.setFirstName("Robyn Rihanna");
  user.setLastName("Fenty");
  user.setSelfDescription("Unapologetic, new album out now worldwide http://smarturl.it/UnapologeticDlx Download 'Stay' http://smarturl.it/RihannaStay 777 Tour DVD Available NOW http://amzn.to/13rkPEU LA BABY! · rihannanow.com");
  user.setAvatar("https://si0.twimg.com/profile_images/3096110144/d097a719dba080cc99ca9dbfba85dfa4.jpeg");
  user.setUserId("rihanna");
  return user;

  }
}

                      In the above controller, we have used couple of the annotations. The explanation about the annotations is given below.

@Controller annotation is used to mark any java class as a controller class. If we use this annotation, we no need to extend any class or implement any interface to create a controller.

@RequestMapping annotation is used to indicate the type of HTTP request and the URI mapping.

 @PathVariable annotation on a method argument to bind it to the value of a URI template variable. In this example, the request URI is /user/{screenName}. The value of {screenName} will be available as part of path variable.

 @ResponseBody the return type is written to the response HTTP body. Based on the HTTP converter type, the response will be converted.

Step 2: Set up Spring MVC configuration in “SampleREST-servlet.xml“.

<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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="org.smarttechies.controller" />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
   <property name="mediaTypes">
      <map>
        <entry key="html" value="text/html"></entry>
        <entry key="json" value="application/json"></entry>
        <entry key="xml" value="application/xml"></entry>
      </map>
   </property>
   <property name="viewResolvers">
      <list>
        <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
           <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
           <property name="prefix" value="/WEB-INF/jsp/"/>
           <property name="suffix" value=".jsp"/>
        </bean>
      </list>
   </property>
</bean>
</beans>

In the code above,

Component-scan enables automatic scan for the class that has Spring annotations. It’s used to detect the @Controller annotation defined in controller classes.

ContentNegotiatingViewResolver to support different representations with different MIME/content types

Step 3: Enable the spring WebApplicationContext in web.xml

<?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 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
  <servlet-name>SampleREST</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>SampleREST</servlet-name>
  <url-pattern>/user/*</url-pattern>
</servlet-mapping>
</web-app>

Step 4: Once the application is ready, deploy the application into apache tomcat or jboss and send the request by setting the “Accept” header to “application/json” to get the response in JSON format or “application/xml” to get the response in XML format.

For example, http:// <host>:<port>/Sample_Spring_REST_Proj/user/Rihana by setting “Accept” header as “application/json” and the response is given below.

{
"firstName":"Robyn Rihanna",
"lastName":"Fenty",
"selfDescription":"Unapologetic, new album out now worldwide http://smarturl.it/UnapologeticDlx  Download 'Stay' http://smarturl.it/RihannaStay 777 Tour DVD Available NOW http://amzn.to/13rkPEU LA BABY! · rihannanow.com",
"avatar":"https://si0.twimg.com/profile_images/3096110144/d097a719dba080cc99ca9dbfba85dfa4.jpeg",
"userId":"rihanna"
}

http:// <host>:<port>/Sample_Spring_REST_Proj/user/Rihana by setting “Accept” header as “application/xml” and the response is given below.

<?xml version="1.0" encoding="UTF-8"?>
<user>
   <firstName>Robyn Rihanna</firstName>
   <lastName>Fenty</lastName>
   <selfDescription>Unapologetic, new album out now worldwide http://smarturl.it/UnapologeticDlx  Download 'Stay' http://smarturl.it/RihannaStay 777 Tour DVD Available NOW http://amzn.to/13rkPEU LA BABY! · rihannanow.com</selfDescription>
   <avatar>https://si0.twimg.com/profile_images/3096110144/d097a719dba080cc99ca9dbfba85dfa4.jpeg</avatar>
   <userId>rihanna</userId>
</user>

The source code is available here.

Advertisements

I am Siva Prasad Rao Janapati. Working as a software developer. Has hands on experience on ATG Commerce(DAS/DPS/DCS), Mozu commerce, Broadleaf Commerce, Java, JEE, Spring, Play, JPA, Hibernate, Velocity, JMS, Jboss, Weblogic,Tomcat, Jetty, Apache, Apache Solr, Spring Batch, JQuery, NodeJS, SOAP, REST, MySQL, Oracle, Mongo DB, Memcached, HazelCast, Git, SVN, CVS, Ant, Maven, Gradle, Amazon Web services, Rackspace, Quartz, JMeter, Junit, Open NLP, Facebook Graph,Twitter4J, YouTube Gdata, Bazzarvoice,Yotpo, 4-Tell, Alatest, Shopzilla, Linkshare. I have hands on experience on open sources and commercial technologies.

Tagged with:
Posted in REST Services, Spring
One comment on “Creating RESTful services using Spring
  1. […] have been building REST services using Spring and Jersy. Both the frameworks are good to implement REST services. But, I was looking for a […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

DZone

DZone MVB

Java Code Geeks
Java Code Geeks
%d bloggers like this: