0

Building a very simple Java REST API with Spring 3.x

Today’s topic is about building a super simple Java REST APIs with Spring 3.x. RESTful webservices are pretty much what is powering much of the APIs being built today and many of them are being built using Java. The Spring Framework makes building a RESTful Java webservice almost ridiculously easy.

This will hopefully be a long series where I’ll go through a few examples starting with the very basics and then moving on to some more advanced versions. This first blog post will start off with this super simple example.

Here is my dev environment setup:

  • Platform: 15″ MBP Mac OS X 10.6.8 2.2GHz i7 with 8GB Memory
  • JVM: Java HotSpot(TM) 64-Bit Server VM (build 20.4-b02-402, mixed mode)
  • Springsource Tool Suite (STS): 2.7.1
  1. Simple REST API
package com.fouzi.blog;

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

@Controller
public class SimpleRestController {

	@RequestMapping(value = "/simple", method = RequestMethod.GET)
	@ResponseBody
	public String handleSimple() {
		return "Hello Simple World!";
	}
}

Annotations Breakdown:

  • The first thing to note is the annotation “@Controller“. This to me is reason enough to use the Spring Framework. In the past I have toiled for hours trying to get my Java Servlet to print “Hello World” and would get confused with the web.xml settings and everything else. With Spring Framework all you have to do is use the “@Controller” Java annotation and automagically your Java class becomes a Servlet that requests will be routed to.
  • And that brings us to the next point which is the next annotation, “@RequestMapping“. Having the Servlet is all fine and dandy but you need to define the resource path that your servlet will be servicing. Again, The Spring Framework makes this ridiculously easy with the “@RequestMapping” Annotation. In my example above this code will be run when you browse to “/simple” on this webapp.
  • The next Annotation is the “@ResponseBody”. I’ll go into more detail in later posts about this one but for now all you need to know is that this will take care of all the details of returning a proper HTTP response, so that all you need to do is just return a Java String from your method and it will show up in the browser connecting to this resource.

Dead simple! Right? If not, then let me know why not. Stay tuned for the next entry where we will start to provide some more interesting examples for building a Java RESTful service using the Spring Framework 3.x

Leave a Reply

Copyright © 2009-2026 Fouzi Husaini's Blog All rights reserved.
This site is using the Desk Mess Mirrored theme, v2.5, from BuyNowShop.com.