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;

public class UserController {

@RequestMapping(value="/{screenName}", method = RequestMethod.GET, headers="Accept=*/*")
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.setSelfDescription("Unapologetic, new album out now worldwide Download 'Stay' 777 Tour DVD Available NOW LA BABY! ·");
  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=""
<context:component-scan base-package="org.smarttechies.controller" />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
   <property name="mediaTypes">
        <entry key="html" value="text/html"></entry>
        <entry key="json" value="application/json"></entry>
        <entry key="xml" value="application/xml"></entry>
   <property name="viewResolvers">
        <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"/>

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=""
xsi:schemaLocation="" id="WebApp_ID" version="2.5">

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",
"selfDescription":"Unapologetic, new album out now worldwide  Download 'Stay' 777 Tour DVD Available NOW LA BABY! ·",

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"?>
   <firstName>Robyn Rihanna</firstName>
   <selfDescription>Unapologetic, new album out now worldwide  Download 'Stay' 777 Tour DVD Available NOW LA BABY! ·</selfDescription>

The source code is available here.


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( 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: Logo

You are commenting using your 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.


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