Spring @ResponseBody Annotation Example
Welcome readers, in this tutorial we will show how to implement the Spring @ResponseBody Annotation to return a Json response from a Spring Mvc Controller.
1. Introduction
1.1 Spring Framework
- Spring is an open-source framework created to address the complexity of an enterprise application development
- One of the chief advantages of the Spring framework is its layered architecture, which allows a developer to be selective about which of its components they can use while providing a cohesive framework for
J2EE
application development - Spring framework provides support and integration to various technologies for e.g.:
- Support for Transaction Management
- Support for interaction with the different databases
- Integration with the Object Relationship frameworks for e.g. Hibernate, iBatis etc
- Support for Dependency Injection which means all the required dependencies will be resolved with the help of containers
- Support for
REST
style web-services
1.2 Spring Mvc Framework
Model-View-Controller (Mvc) is a well-known design pattern for designing the GUI based applications. It mainly decouples the business logic from UI by separating the roles of Model, View, and Controller in an application. This pattern divides the application into three components to separate the internal representation of the information from the way it is being presented to the user. The three components are:
- Model (M): Model’s responsibility is to manage the application’s data, business logic, and the business rules. It is a
POJO
class which encapsulates the application data given by the controller - View (V): A view is an output representation of the information, such as displaying information or reports to the user either as a text-form or as charts. Views are usually the
JSP
templates written with Java Standard Tag Library (JSTL
) - Controller (C): Controller’s responsibility is to invoke the Models to perform the business logic and then update the view based on the model’s output. In the spring framework, the controller part is played by the Dispatcher Servlet
Now, open up the Eclipse IDE and let us see how to implement this tutorial.
2. Spring @ResponseBody Annotation Example
Here is a systematic guide for implementing this tutorial in the Spring Mvc framework.
2.1 Tools Used
We are using Eclipse Kepler SR2, MySQL, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.
2.2 Project Structure
Firstly, let us review the final project structure, in case you are confused about where you should create the corresponding files or folder later!
2.3 Project Creation
This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project
.
In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.
Select the Maven Web App archetype from the list of options and click next.
It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT
.
Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml
file will be created. It will have the following code:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.spring.mvc</groupId> <artifactId>SpringResponseBodyAnnotation</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> </project>
Developers can start adding the dependencies they want like Servlet API, Spring Mvc. Let us start building the application!
3. Application Building
Below are the steps involved in developing this application.
3.1 Maven Dependencies
Here, we specify the dependencies for the spring mvc framework. The rest dependencies such as Jackson API, Spring Beans, Spring Core etc. will be automatically resolved by Maven. The updated file will have the following code:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.spring.mvc</groupId> <artifactId>SpringResponseBodyAnnotation</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SpringResponseBodyAnnotation Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <!-- Servlet API Dependency --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>3.0-alpha-1</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.8.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.6</version> </dependency> </dependencies> <build> <finalName>SpringResponseBodyAnnotation</finalName> </build> </project>
3.2 Configuration Files
Let us write all the configuration files involved in this application.
3.2.1 Web Deployment Descriptor
The web.xml
file declares one servlet (i.e. Dispatcher Servlet) to receive all kind of the requests. Dispatcher servlet here acts as a front controller. Add the following code to it:
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>SpringResponseBodyAnnotation</display-name> <servlet> <servlet-name>responsebodydispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>responsebodydispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
3.2.2 Spring Configuration File
To configure the spring framework, developers need to implement a bean configuration file i.e. responsebodydispatcher-servlet.xml
which provide an interface between the basic Java class and the outside world. Put this XML file in the SpringResponseBodyAnnotation/src/main/webapp/WEB-INF
folder and add the following code to it:
responsebodydispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:annotation-config /> <!-- for the stereotype annotation to work --> <context:component-scan base-package="com.spring.mvc.controller" /> <context:component-scan base-package="com.spring.mvc.component" /> <mvc:annotation-driven /> </beans>
3.3 Java Class Creation
Let us write the Java classes involved in this application.
3.3.1 Model Class
This pojo class defines company bean. Add the following code to it:
MyCompany.java
package com.spring.mvc.component; import org.springframework.stereotype.Component; @Component public class MyCompany { private int id; private String fullname; private String email; public MyCompany() { } public MyCompany(int id, String fullname, String email) { this.id = id; this.fullname = fullname; this.email = email; } public int getId() { return id; } public String getFullname() { return fullname; } public String getEmail() { return email; } }
3.3.2 Controller Class
Let us create a simple class where the @RestController
annotation specifies this class as a spring controller and is responsible for handling the incoming requests. In here,
- The controller methods are annotated with the
@ResponseBody
annotation which binds the return value to a web response body.- The response is not interpreted as a view-name
- The annotation uses the HTTP message converters to convert the return value to the HTTP request body, based on the content-type in the HTTP request header
- The controller methods are mapped to HTTP GET request which fetches the resources
Add the following code to it:
MyCtrl.java
package com.spring.mvc.controller; import java.util.ArrayList; import java.util.List; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.spring.mvc.component.MyCompany; @RestController public class MyCtrl { @RequestMapping(value="/company", method=RequestMethod.GET) public @ResponseBody MyCompany getCompany() { return new MyCompany(12, "John Greece", "john.greece@test.com"); } @RequestMapping(value="/companies", method=RequestMethod.GET) public @ResponseBody List<MyCompany> getCompanies() { List<MyCompany> companies = new ArrayList<MyCompany>(); companies.add(new MyCompany(3, "Andrew Strauss", "andrew.strauss@test.com")); companies.add(new MyCompany(12, "John Greece", "john.greece@test.com")); companies.add(new MyCompany(101, "Robert Parera", "robert.parera@test.com")); companies.add(new MyCompany(153, "Charlotte O' Neil", "charlotte.neil@test.com")); companies.add(new MyCompany(239, "Eddy Knight", "eddy.knight@test.com")); return companies; } }
4. Run the Application
As we are ready with all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server
.
Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it on the browser.
5. Project Demo
We will test this sample application using a GUI based client. Launch the Postman tool and hit the different URL’s to fetch the data and display the results in the JSON format.
5.1 Get all Companies
Hit the following HTTP GET URL in the Postman tool to display the list of companies in the Json format.
http://localhost:8088/SpringResponseBodyAnnotation/companies
Java object’s list as Json response
[ { "id": 3, "fullname": "Andrew Strauss", "email": "andrew.strauss@test.com" }, { "id": 12, "fullname": "John Greece", "email": "john.greece@test.com" }, { "id": 101, "fullname": "Robert Parera", "email": "robert.parera@test.com" }, { "id": 153, "fullname": "Charlotte O' Neil", "email": "charlotte.neil@test.com" }, { "id": 239, "fullname": "Eddy Knight", "email": "eddy.knight@test.com" } ]
5.2 Get Company
Hit the following HTTP GET URL in the Postman tool to display the Java object as Json response.
http://localhost:8088/SpringResponseBodyAnnotation/company
Java Object as Json response
{ "id": 12, "fullname": "John Greece", "email": "john.greece@test.com" }
Do note, server name (localhost) and port (8088) may vary as per your tomcat configuration. That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!
6. Conclusion
In this section, developers learned how to implement the @ResponseBody
annotation in the spring framework. Developers can download the sample application as an Eclipse project in the Downloads section.
7. Download the Eclipse Project
This was an example of the @ResponseBody
annotation in the Spring Mvc framework.
You can download the full source code of this example here: SpringResponseBodyAnnotation
Use SpringBoot and save yourself a LOT of configuration. No web.xml, etc, etc.