Add Spring MVC 3 to your Maven webapp

Now that we have created a basic Maven webapp from the archetype template, let’s add some Spring MVC 3 functionality to it. We first need to use Maven to download the right dependencies for our application.

1. Add dependencies for Spring MVC and taglibs to your pom.xml

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-web</artifactId>
	<version>3.0.5.RELEASE</version>
	<type>jar</type>
	<scope>compile</scope>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-webmvc</artifactId>
	<version>3.0.5.RELEASE</version>
	<type>jar</type>
	<scope>compile</scope>
</dependency>
<dependency>
	<groupId>jstl</groupId>
	<artifactId>jstl</artifactId>
	<version>1.1.2</version>
	<type>jar</type>
	<scope>compile</scope>
</dependency>
<dependency>
	<groupId>taglibs</groupId>
	<artifactId>standard</artifactId>
	<version>1.1.2</version>
	<type>jar</type>
	<scope>compile</scope>
</dependency>
<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>servlet-api</artifactId>
	<version>2.5</version>
	<type>jar</type>
	<scope>compile</scope>
</dependency>

Now use Maven to clean Eclipse. (enter in TERMINAL $ mvn eclipse:clean eclipse:eclipse and then refresh the project in Eclipse so that the dependencies are updated)

2. Add the DispatcherServlet to the web.xml file.

Spring MVC revolves around the DispatcherServlet which serves as a Front Controller for handling all incoming requests, locating the appropriate Handler Mapping to map them to an application handler, and then finding the right View Resolver to resolve them to a view before rendering the final result back to the requesting client. To use the DispatcherServlet, we must add it to the web.xml file so that the web application will fire it up when it launches.

src/main/webapp/WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 
	<servlet>
		<servlet-name>greeter</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
 
	<servlet-mapping>
		<servlet-name>greeter</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
 
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener> 
 
</web-app>

3. Add another xml file called greeter-servlet.xml to WEB-INF

Spring requires you to create an xml file with the name of the servlet as defined in web.xml. (The pattern is <servlet name>-servlet.xml) This does seem quite awkward, and I suppose there are ways around having to create this file. But, this is the way that Spring suggests to do things so we will just follow suit. All the xml configuration code for this servlet would normally go into this file, but since we are using annotations we won’t have much xml code.

We named our servlet “greeter” in this example. So, now we must create a file called greeter-servlet.xml.

src/main/webapp/WEB-INF/greeter-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:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	   		http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
    		p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
 
</beans>



We will later create handler methods which will return the view represented as a string. Here we have defined the View Resolver which will add a prefix of “/WEB-INF/jsp/” and a suffix of “.jsp” to our view strings. For example, when the view string “addgreeting” is returned, it will resolve to /WEB-INF/jsp/addgreeting.jsp which means we don’t have to hard code the path to our files in our java classes and there’s no need to add each bean to an xml file. This is a huge time saver!

4. Add another xml file called applicationContext.xml

Here in the applicationContext.xml file we will specify that we will use annotations, and that the base package to scan is com.bitbybit. Now the configurations will be automatically scanned from the java classes.

src/main/webapp/WEB-INF/applicationContext.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:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	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-3.0.xsd
			http://www.springframework.org/schema/mvc 
			http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
 
	<context:annotation-config />
 
	<context:component-scan base-package="com.bitbybit" />
 
	<mvc:annotation-driven /> 
 
</beans>

5. Create a new java source folder

To follow with Maven’s standard directory structure, you must create the main java source folder in a specific way so your projects will conform to other Maven projects. In Eclipse, right click on the project SpringGreetings and select New -> Java -> Source Folder. Leave the defaults and enter “src/main/java” for the folder name.

6. Create the class GreetingController.java and add handler methods

Inside the new source folder, create a new java class in Eclipse called GreetingController.java in the package com.bitbybit.web.controller

GreetingController.java
package com.bitbybit.web.controller;
 
import java.util.Map;
import org.apache.log4j.Logger;
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.RequestParam;
 
@Controller
@RequestMapping("/home")
public class GreetingController {
 
	protected static Logger logger = Logger.getLogger("GreetingController");
 
	//define the same url with GET so users can skip to the greetings page
        //note there is no actual greetings.html file!! 
	@RequestMapping(value = "/greetings.html", method = RequestMethod.POST)
	public String showAllGreetings(@RequestParam(value="greetingText", required=true) String greetingText,
			Map<String, Object> model) {		
 
		logger.info("entering showAllGreetings");	
 
		model.put("greetingText", greetingText);
 
	        // This will resolve to /WEB-INF/jsp/greetings.jsp
	        return "greetings";
	}	
 
	@RequestMapping(value = "/addgreeting.html", method = RequestMethod.GET)
        public String showAddGreetingPage() {		
 
		logger.info("entering showAddGreetingPage");
 
    	        // This will resolve to /WEB-INF/jsp/addgreeting.jsp
    	        return "addgreeting";
	}	
 
}

If you see a lot of errors because the imports are not recognized then remember, go to Terminal and type
$ mvn eclipse:clean eclipse:eclipse
and then refresh the project in Eclipse. There. I think I have said that enough times now ;)

7. Create a jsp folder in WEB-INF and the files addgreeting.jsp and greetings.jsp

src/main/webapp/WEB-INF/jsp/addgreeting.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
 
<!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=UTF-8">
  	<title>Spring Greetings</title>
</head>
 
<body>
 
<h1>Spring Greetings</h1>
<form:form action="greetings.html"> 	
	<table>
		<tr>
			<td>Add your greeting:</td>
			<td><input type="text" name="greetingText" size="100"/></td>
		</tr>	
		<tr>
			<td colspan="2" align="center">
				<input type="submit" value="Submit" />	
			</td>
		</tr>
	</table>
</form:form>
 
</body>
</html>

WEB-INF/jsp/greetings.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
 
<!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=UTF-8">
  	<title>Spring Greetings</title>
</head>
 
<body>
 
<h1>Spring Greetings</h1>
 
Greeting by <b>Anonymous</b><br/>
on <c:out value="<%=new java.util.Date()%>" /><br/>
<c:out value="${greetingText}" /><br/>			
 
<p><a href="/springgreetings/home/addgreeting.html">Add greeting</a><br/>
<a href="/springgreetings/">Home</a>
 
</body>
</html>

This is what your project should look like in Eclipse:

8. Redeploy the application and open it in a web browser

$ mvn tomcat:redeploy
Done! Now you can see the new application here http://localhost:8080/springgreetings/home/addgreeting.html

Now enter a greeting. You should see this:

NOTE you should see the log file appear after invoking the application in your browser and refreshing the project in Eclipse.

NOTE if you have strange problems where it seems that tomcat is caching your old files, then empty the “target” folder in Eclipse and delete the deployed application in tomcat/webapps. This is necessary from time to time.

1 Comment
Clement wrote on 2012-09-28 at 16:55:58:
Work well done... I have decided to try all the following chapters in Spring.


Post a Comment

(required):