Spring 4

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.

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

 

Download Source Code with Libs
Spring4@RestController.zip

 

 

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

 

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago