Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn
Srivatsan Sundararajan
Quality Assurance Manager for MyEclipse and Webclipse.
Contributions by Swapna Sagi

Spring MVC Framework and REST

Spring’s annotation based MVC framework simplifies the process of creating RESTful web services. The key difference between a traditional Spring MVC controller and the RESTful web service controller is the way the HTTP response body is created. While the traditional MVC controller relies on the View technology, the RESTful web service controller simply returns the object and the object data is written directly to the HTTP response as JSON/XML.  For a detailed description of creating RESTful web services using the Spring framework, click here.

Figure 1: Spring MVC traditional workflow

Spring development isn’t just about writing Java code. Are you developing a Spring Boot application with an Angular or React frontend? Or maybe you’re using Spring MVC, with JSPs and JSTL. Whatever the case, with advanced support for everything from HTML to Vue.js, CodeMix will significantly boost your development experience. Learn more …

Spring MVC REST Workflow

The following steps describe a typical Spring MVC REST workflow:

  1. The client sends a request to a web service in URI form.
  2. The request is intercepted by the DispatcherServlet which looks for Handler Mappings and its type.
    • The Handler Mappings section defined in the application context file tells DispatcherServlet which strategy to use to find controllers based on the incoming request.
    • Spring MVC supports three different types of mapping request URIs to controllers: annotation, name conventions and explicit mappings.
  3. Requests are processed by the Controller and the response is returned to the DispatcherServlet which then dispatches to the view. 

In Figure 1, notice that in the traditional workflow the ModelAndView object is forwarded from the controller to the client. Spring lets you return data directly from the controller, without looking for a view, using the @ResponseBody annotation on a method. Beginning with Version 4.0, this process is simplified even further with the introduction of the @RestController annotation. Each approach is explained below.

Using the @ResponseBody Annotation

When you use the @ResponseBody annotation on a method, Spring converts the return value and writes it to the http response automatically. Each method in the Controller class must be annotated with @ResponseBody.


Figure 2: Spring 3.x MVC RESTful web services workflow

Behind the Scenes

Spring has a list of HttpMessageConverters registered in the background. The responsibility of the HTTPMessageConverter is to convert the request body to a specific class and back to the response body again, depending on a predefined mime type. Every time an issued request hits @ResponseBody, Spring loops through all registered HTTPMessageConverters seeking the first that fits the given mime type and class, and then uses it for the actual conversion.

Code Example

Let’s walk through @ResponseBody with a simple example.

Project Creation and Setup

  1. Create a Dynamic Web Project with Maven support in your Eclipse or MyEclipse IDE.
  2. Configure Spring support for the project.
    • If you are using Eclipse IDE, you need to download all Spring dependencies and configure your pom.xml to contain those dependencies.
    • In MyEclipse, you only need to install the Spring facet and the rest of the configuration happens automatically. 
  3. Create the following Java class named Employee. This class is our POJO.
  4. Create the following @Controller class:

    Notice the @ResponseBody added to each of the @RequestMapping methods in the return value.

  5. Add the <context:component-scan> and <mvc:annotation-driven /> tags to the Spring configuration file.
    <context:component-scan> activates the annotations and scans the packages to find and register beans within the application context.
    <mvc:annotation-driven/> adds support for reading and writing JSON/XML if the Jackson/JAXB libraries are on the classpath.
    • For JSON format, include the jackson-databind jar and for XML include the jaxb-api-osgi jar to the project classpath.
  6. Deploy and run the application on any server (e.g., Tomcat). If you are using MyEclipse, you can run the project on the embedded Tomcat server.

    JSON—Use the URL: http://localhost:8080/SpringRestControllerExample/rest/employees/Bob and the following output displays:
    output_json-cropFigure 3: JSON output

    XML—Use the URL: http://localhost:8080/SpringRestControllerExample/rest/employees/Bob.xml and the following output displays:
    output_xmlFigure 4: XML output

Using the @RestController Annotation

Spring 4.0 introduced @RestController, a specialized version of the controller which is a convenience annotation that does nothing more than add the @Controller and @ResponseBody annotations. By annotating the controller class with @RestController annotation, you no longer need to add @ResponseBody to all the request mapping methods. The @ResponseBody annotation is active by default. Click here to learn more.
Figure 5: Spring 4.x MVC RESTful Web Services Workflow

To use @RestController in our example, all we need to do is modify the @Controller to @RestController and remove the @ResponseBody from each method. The resultant class should look like the following:

Note that we no longer need to add the @ResponseBody to the request mapping methods. After making the changes, running the application on the server again results in same output as before.


As you can see, using @RestController is quite simple and is the preferred method for creating MVC RESTful web services starting from Spring v4.0. I would like to extend a big thank you to my co-author, Swapna Sagi, for all of her help in bringing you this information! 


Related Posts

Celebrating Success… with You! Happy Holidays! We are excited about closing off another successful chapter! You’ve made 2018 a wonderful year: our Darkest Dark theme is number one on the Eclipse Marketplace with over 600K installs, and CodeMix keeps gaining popularity with over 100K installs - currently number seven.  Thank you for giving us your preference!We are getting ready to celebrate, no...
CodeMix – Better with You! Thanks to detailed feedback from our awesome users, our team has been hard at work adding stability, reliability and performance fixes, and enhancements, to CodeMix. Read on for the deets on what’s new in CodeMix over the last month.Editing & ValidationWhen editing TypeScript files, error markers were sometimes not cleared when the error was fi...
A Day with Dani: Eclipse Plugin for Awesome Worksp... DevStyle Rescued My Workspace!As a new developer working in Eclipse, nothing was worse than doing a project and looking at an outdated, plain workspace. It was boring, and took away from the excitement and learning these projects had to offer. This was an IDE I would be using almost every day, so when I learned about the DevStyle plugin for Eclipse...
Happy Holidays – from Our Family to Yours! It’s that time of the year again - the time to enjoy a break from the everyday duties, accompanied by our loved ones! At Genuitec we would like to wish you a wonderful holiday season filled with great times and awesome food! We already got our party hats out (as you can see)! Our U.S. offices will be closed on December 25th and 26th, as well as Jan...

Posted on Sep 28th 2015