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 a 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 a 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 the 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.

Advertisement

Siva Janapati is an Architect with experience in building Cloud Native Microservices architectures, Reactive Systems, Large scale distributed systems, and Serverless Systems. Siva has hands-on in architecture, design, and implementation of scalable systems using Cloud, Java, Go lang, Apache Kafka, Apache Solr, Spring, Spring Boot, Lightbend reactive tech stack, APIGEE edge & on-premise and other open-source, proprietary technologies. Expertise working with and building RESTful, GraphQL APIs. He has successfully delivered multiple applications in retail, telco, and financial services domains. He manages the GitHub(https://github.com/2013techsmarts) where he put the source code of his work related to his blog posts.

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 )

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Dzone.com
DZone

DZone MVB

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