RestController in Spring 4 MVC Framework

In this article, we will explore about the RestController by using @RestController annotation. One of the new features of API improvements is new @RestController annotation which is inherited from the @Controller annotation.

Prior to the version 4.0, all the Spring MVC components has to use the common @Controller annotation to mark that as the controller servlet. When you implement a RESTful web services, the response would be always sent with the response body. To make this simple, Spring 4.0 has provided a specialized version of controller. Look at the definition of the @RestController implementation.

@Target(value=TYPE)
 @Retention(value=RUNTIME)
 @Documented
 @Controller
 @ResponseBody
public @interface RestController

A convenience annotation that is itself annotated with @Controller and @ResponseBody.

Types that carry this annotation are treated as controllers where @RequestMapping methods assume @ResponseBody semantics by default.

It’s a very common use case to have Controllers implement a REST API, thus serving only JSON, XML or custom MediaType content. For convenience, instead of annotating all your @RequestMapping methods with @ResponseBody, you can annotate your Controller Class with @RestController.

RestController in Spring MVC

@RestController is a stereotype annotation that combines @ResponseBody and @Controller. More than that, it gives more meaning to your Controller and also may carry additional semantics in future releases of the framework.

1. Download Spring MVC 4.0 jar files from this maven repository here.

2. Create Dynamic Web Project and add the libraries you downloaded to WEB-INF/lib folder.

RestController in Spring 4 MVC Framework

3. Open /WEB-INF/web.xml file and add below configuration.

<?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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Spring4RestController</display-name>
  
 <servlet>  
  <servlet-name>spring4</servlet-name>  
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  <load-on-startup>1</load-on-startup>  
 </servlet>  
 <servlet-mapping>  
  <servlet-name>spring4</servlet-name>  
  <url-pattern>/*</url-pattern>  
 </servlet-mapping> 
</web-app>

Note that in the above code,we have named Spring Dispatcher servlet class as “spring4” and the url pattern is given as “/*” which means any uri with the root of this web application will call DispatcherServlet. DispatcherServlet will look for configuration files following this naming convention – [servlet-name]-servlet.xml. In this example, I have named dispatcher servlet class as “spring4” and hence it will look for file named ‘spring4-servlet.xml’.

4. Now create an xml file under WEB-INF folder and name it ‘spring4-servlet.xml‘.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:p="http://www.springframework.org/schema/p" 
 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-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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

 <context:component-scan base-package="com.doj.spring4.controller" />

 <mvc:annotation-driven />
 
</beans>

With ComponentScan tag, Spring auto scans all elements in the provided base package and all its child packages for Controller servlet. Also, we have used <mvc:annotation-driven> tag instead of ViewResolver, with which we can directly send response data from the controller.

5. Let us create a controller servlet in the package mentioned in the component-scan tag.
SpringRestController.java

package com.doj.spring4.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.RestController;

/**
 * @author Dinesh Rajput
 *
 */
@RestController
@RequestMapping("/service/greeting")
public class SpringRestController {
 @RequestMapping(value = "/{name}", method = RequestMethod.GET)
 public String sayHello(@PathVariable String name) {
  String result="Hello "+name+" to dineshonjava.com!!!";  
  return result;
 }
}

@RequestMapping’ annotation is used for defining incoming request urls for class and method levels. In this case all uri’s in the format <root-url>/service/greeting/ will be routed to this Controller class. With @RequestMapping annotation, we can only define generic uri mappings. For dynamic uri mappings in case of passing variables along with the uri, @PathVariable is used. Here in this case, we pass a variable ‘name’ along with the uri such as, <root-url>/service/greeting/Dinesh. Here the last parameter Dinesh in the uri is retrieved using @PathVariable.

I explained that while using <mvc:annotation-config> tag instead of view resolver, we use ‘@ResponseBody’ annotation to return response data directly from controller. But in the above code, I have not used ‘@ResponseBody’. This is because, in Spring MVC 4.0, they have introduced ‘@RestController’ such that we need not use ‘@ResponseBody’ tag in each and every method. ‘@RestController’ will handle all of that at the type level.

This annotation simplifies the controller and it has ‘@Controller’ and ‘@ResponseBody’ annotated within itself.

Let us take a look at the same controller but with Spring MVC 3.0,

@Controller
@RequestMapping("/service/greeting")
public class SpringRestController {
 @RequestMapping(value = "/{name}", method = RequestMethod.GET)
 public @ResponseBody String sayHello(@PathVariable String name) {
  String result="Hello "+name+" to dineshonjava.com!!!";  
  return result;
 }
}

Note that in Spring MVC 3.0 we had to explicitly use @Controller annotation to specify controller servlet and @ResponseBody annotation in each and every method. With the introduction of ‘@RestController’ annotation in Spring MVC 4.0, we can use it in place of @Controller and @ResponseBody annotation.

So now run this application in Apache Tomcat Web Server.

http://localhost:8080/Spring4RestController/service/greeting/Dinesh

RestController in Spring 4 MVC Framework Example

 

Download Source Code with Libs
Spring4@RestController.zip

 

 

<<Previous <<   || Index ||   >>Next >>

 

Previous
Next