Beginning Spring MVC 3

It’s been awhile since I used Spring framework. It has evolved and gotten simpler & easier to work with. This tutorial will walk through how to setup a simple Spring MVC project and to return JSON object to client browser. In this tutorial I will be using SpringSource Tool Suite, its project template helps to reduce the time to get a Spring MVC project up and running.

In order to start the tutorial, you will need

  1. JDK installed. SpringSource Tool Suite requires full JDK, and
  2. SpringSource Tool Suite (STS). The installer includes the IDE and tc Server Developer Edition.

Let’s start with creating the Spring MVC project in STS.

Step 1: Create a new project:  File -> New -> Spring Template Project. You will be prompted to download the template, go ahead and download.

Step 2: Define project and top-level package name, then click “Finish”

Step 3: After the project created you will see the file structure and default controller (HomeController). The dependencies are defined in pom.xml and you will need to add Jackson JSON Processor to complete the tutorial. Without the library you will get HTTP 406 when getting JSON object. Add the following to pom.xml.

<!-- Jackson JSON Processor -->
<dependency>
 <groupId>org.codehaus.jackson</groupId>
 <artifactId>jackson-mapper-asl</artifactId>
 <version>1.6.4</version>
</dependency>


Step 4: Deploy the project into SpringSource tc Server. It cannot get easier then this.

Step 5: Deploy the project then start the server.


Step 6: Once the server is ready. Test you configuration by opening http://localhost:8080/spring-mvc-basic/ in your browser. That is all for the setup, now we move on to add a simple function to get JSON data and to get request information.

Step 7: Open HomeController and add 2 methods. The displayRequest() is a simple GET method which take an input parameter “input”, servlet request and request header. The content will be passed back to the view, in this case display.jsp. The 2nd method is getJsonData(), a simple method that return JSON object.

	@RequestMapping(value="/display", method=RequestMethod.GET)
	public String displayRequest(HttpServletRequest request,
		@RequestHeader(value="Accept") String accept,
		@RequestHeader("Accept-Encoding") String encoding,
		@RequestHeader("Accept-Charset") String charset,
                @RequestParam("input") String input,
                Model model)  {
	  logger.info("Calling displayRequest");
	  model.addAttribute("RemoteAddress", request.getRemoteAddr());
	  model.addAttribute("HeaderAccept", accept);
	  model.addAttribute("HeaderAcceptEncoding", encoding);
	  model.addAttribute("HeaderAcceptCharset", charset);
	  model.addAttribute("Output", input);
	  return "display";
	}

	@RequestMapping(value="/extractJson", method=RequestMethod.GET)
	public @ResponseBody Map<String,String> getJsonData(@RequestParam("input") String input)  {
	  logger.info("Calling extractJson");
	  person.put("name", "Simba");
	  person.put("website", "http://www.tanbh.net");
	  person.put("output", input);
	  return person;
	}

Step 8: Let’s work on the views now, by adding the link to call the controller “/display” and jQuery code to get JSON.

<!-- home.jsp -->
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
	<title>Home</title>
	<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.min.js"></script>
</head>
<body>
<h1>Hello Spring MVC 3!</h1>
<a href="<c:url value="/display?input=HelloWorldEcho" />">Click to Get Request Info</a>
<br/><br/>
<div id="result"></div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function() {

	$.getJSON('<c:url value="extractJson?input=HelloWorldEcho" />', function(data) {
	    $('#result').append('Result from ajax/json<br/>');
	    $('#result').append('Name: ' + data.name);
	    $('#result').append('<br/>');
	    $('#result').append('Website: ' + data.website);
	    $('#result').append('<br/>');
	    $('#result').append('Input Parameter: ' + data.output);
	});
});
</script>
<!-- display.jsp -->
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<strong><c:out value="Remote Address: ${RemoteAddress}"></c:out></strong><br/>
<strong><c:out value="Accept ${HeaderAccept}"></c:out></strong><br/>
<strong><c:out value="Accept-Encoding: ${HeaderAcceptEncoding}"></c:out></strong><br/>
<strong><c:out value="Accept-Charset: ${HeaderAcceptCharset}"></c:out></strong><br/><br/>
<strong><c:out value="Input Parameter: ${Output}"></c:out></strong><br/>

<br/>
<br/>
<br/>
<a href="<c:url value="/" />">Home</a>

</body>
</html>

Now save all the file and sit back and wait for tc Server to reload. Once reloaded, launch trigger http://localhost:8080/spring-mvc-basic/. I also observed, I need to restart the tc Server after compilation error in the controller. Anyway, you should see your result:

Update: the source is downloadable at myGit.

Advertisements