Spring MVC Template

Spring Framework is arguably the most popular and flexible open-source Java framework available and it is heavily used by our development teams at Credera.  I have been anxious to get some hands-on experience with Spring so in this series I will create a prototype application with Spring MVC, and then enhance it with Spring Data MongoDB.

My Development Environment

I like to build my client and research projects in each in a separate VMWare virtual machine so that I can neatly close them up and return to them later.  I build this machine on Windows 7, with Java JDK 7, Mongo DB, and Spring Tools Suite  3.0.0.  STS 3.0.0 comes bundled with the vmWare Tomcat Server for running web applications, m2Eclipse for Maven Build project management, and Git which allows me to version-control and publish to GitHub.

The STS Spring MVC Template

I chose the Spring MVC Project as my template.  Nearly a dozen different templates are available, each will establish the project with a different pom.xml which will include and download the relevant dependencies.

  1. Start up STS and use File > New Spring Template Project > Spring MVC Project
  2. Enter a project name such as my-spring-mvc, and a package name such as my.spring.mvc.

STS will show a project in the Navigator view.  If there are any build errors such as classes not found, you may need to right-click on the project and choose Maven > Enable Dependency Management.

My project will reflects the packaging structure for an MVC project, including source folders for main, and main resource directories (the actual application code), source folders for test and test resource directories (for unit tests), a pom.xml for the definition of Maven dependencies, and then the visualization of those dependencies.

STS has created the files necessary to run this as an MVC application on the Tomcat server.  Let’s inspect a few of these files more closely:

web.xml

When this application is deployed to a servlet container such as Tomcat, the web.xml file will ‘bootstrap’ the application with it’s contextConfigLocation information about how to start the container on lines 7,8,21,22, and servlet mappings in response to browser requests on lines 18,28.

<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">

	<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>
	
	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
		
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

</web-app>

root-context.xml

The bean definitions here enable our dependency injection. In the next example Integrating Spring with MongoDB, we’ll see how this is done. In this application, no further customization is required.

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
		
</beans>

servlet-context.xml

With Spring 3.0, the container may be configured via xml, or via Java Annotations. Here we see the directive to the container to use the Annotation-Driven approach on line 12, and on line 23 we see the base level package to begin scanning for [annotations] in java classes.

<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
		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-3.0.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	
	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
	<context:component-scan base-package="my.spring.mvc" />
</beans:beans>

HomeController.java

Our controller class utilizes two Java Annotations to interact with the Spring container, the @Controller annotation on line 5 which designates this class to act as a servlet, capable of receiving servlet requests, and the @RequestMapping annotation on line 12 to indicate that this method should respond to HTTP GET request from the root (e.g. ‘/’) context. The Model that is passed into the container allows us to attach attributes to the HTTP request, and the method returns the name of the .jsp to be displayed on the request.


/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {

 private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

 /**
 * Simply selects the home view to render by returning its name.
 */
 @RequestMapping(value = "/", method = RequestMethod.GET)
 public String home(Locale locale, Model model) {
 logger.info("Welcome home! the client locale is "+ locale.toString());

 Date date = new Date();
 DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

 String formattedDate = dateFormat.format(date);

 model.addAttribute("serverTime", formattedDate );

 return "home";
 }

}

home.jsp

An http request from the root of our context will now as we’ve seen, execute the HomeController.java which carries request attributes and redirects to home.jsp. The home.jsp page displays the serverTime on line 4 by using JSTL to read the request attribute by name (set in HomeController).

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<h1>Hello world!</h1>

The time on the server is ${serverTime}.

Run the Application on the server

To deploy and run the application, right-click on the project name, choose ‘Run On Server’, select the existing vmWare vFabric tc server, and watch the console. Typically STS will automatically launch the internal browser but if not you can open the server view via Window > Show View > Servers, and then from the the jar file resource click ‘Open Home Page’ to see the Hello World with the server time displayed.

Now that we have validated and have our basic framework in place, the next step will be to add Spring Data, MongoDB. Follow along in this next post, Spring Data with MongoDB.

Leave a comment