Implementing REST API with Spring MVC

Spring MVC helps to build REST API server with minimum code.

The crucial files are as follows.

  • pom.xml (with dependency to spring framework and jackson 2)
  • Spring context xml
  • REST DAO class
  • REST Controller class

pom.xml

pom.xml

  • Dependency to Spring framework and jackson2 is required

spring context xml (servlet-context.xml)

servlet-context.xml

  • Above context don’t have any view resolver. I’m explaining it later.

REST DAO class

package com.test.restapi;

public class RestResult {
	public String value1;
	public int value2;
	public boolean value3;
}

REST Contoller class

package com.test.restapi;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>http.HttpServletRequest;

@RestController
public class TestRestController {
	@RequestMapping("/test_api")
	public RestResult test01(HttpServletRequest request) {
		RestResult restResult = new RestResult();
		restResult.value1 = "String value";
		restResult.value2 = 100;
		restResult.value3 = true;
		return restResult;
	}
}

The result

{"value1":"String value","value2":100,"value3":true}

How it works

  • Controller class is using @RestController ,which is from Spring 4. (@RestController = @Controller + @ResponseBody)
  • @ResponseBody is handled by RequestResponseBodyMethodProcessor inside HandlerAdapter (org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor)
  • Refer to the following post to understand the role of HandlerAdapter
  • RequestResponseBodyMethodProcessor converts response object (RestResult) to String  and return to the client
  • In converting, if response object is not String, default Jackson converter is used (when Jackson 2 is on the classpath)
  • With RequestResponseBodyMethodProcessor, no additional View is needed. (That’s why no view resolver is declared)

Full source code

SimpleRestApiTest

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.