Spring MVC return JSON using @ResponseBody

The easiest way to return an object as JSON without using view resolver is to add @ResponseBody before return type.

Objective

  • How to build a REST service using Spring MVC to return json without using view resolver?

Environment

  • Eclipse (Indigo) or any other version
  • Jetty (eclipse-plugin) or any other server

Libraries

( 1 ) Create Java Project

create java project with the following directory structure, copy jar files to “lib” folder and add them to java build path.

( 2 ) Java Classes

MyController.java

This class receives the request. Notice: @ResponseBody

package com.hmkcode.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hmkcode.vo.Person;

@Controller
public class MyController {

	@RequestMapping("/view")
	public @ResponseBody Person getPerson(){
		Person person = new Person();
		person.setId(1);
		person.setName("hmk");
		return person;
	}

}

Person.java

package com.hmkcode.vo;

public class Person {

	private int id;
	private String name;
	//getter and setter

}

( 3 ) web.xml

<?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_2_5.xsd" version="2.5">
 
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>/rest/*</url-pattern>
	</servlet-mapping>
 
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
	</welcome-file-list>
</web-app>

( 4 ) Spring XML Configuration (springmvc-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:mvc="http://www.springframework.org/schema/mvc" 
		xmlns:context="http://www.springframework.org/schema/context"
		xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.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-3.0.xsd">

		<context:component-scan base-package="com.hmkcode.controllers" />
		<mvc:annotation-driven />
</beans>

( 5 ) Deploy and Run