Spring MVC- Getting Started

For understanding anything it is best to gets hand on. Let us try creating a simple spring app using spring MVC framework (This tutorial assumes Eclipse IDE)

0. Create a sample J2EE project (or Spring project if you already have it installed)

1. Download Spring http://www.springsource.org/spring-community-download and include jars to lib folder.

2. Modify web.xml to direct all the requests ending with .do to spring MVC’s fromt controller servlet (DispatcherServlet)



3. Spring by default assumes webapplication context to be present in <servletname>-servlet.xml. In this case create springapp-servlet.xml.

4. Spring is mostly annotation driven, to take advantage of same add following to springapp-servlet.xml

<?xml version=”1.0″ encoding=”UTF-8″?>
<beans xmlns=”http://www.springframework.org/schema/beans”
xmlns:mvc=”http://www.springframework.org/schema/mvc” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xmlns:p=”http://www.springframework.org/schema/p” xmlns:context=”http://www.springframework.org/schema/context”

<!– JSR-303 support will be detected on classpath and enabled automatically –>
<mvc:annotation-driven />
<!– Activates various annotations to be detected in bean classes –>
<context:annotation-config />

<!– Tell Spring where to automatically detect controllers –>
<context:component-scan base-package=”spring.sample.controllers” />
<!– Define Simple View Resolvers –>
<bean id=”viewResolver” class=”org.springframework.web.servlet.view.InternalResourceViewResolver”>
<property name=”viewClass” value=”org.springframework.web.servlet.view.JstlView”></property>
<property name=”prefix” value=”/WEB-INF/jsp/”></property>
<property name=”suffix” value=”.jsp”></property>


We have done two things, first, we told spring that all our controllers will be in spring.sample.controllers and second look for view files under /WEB-INF/jsp folder

5. As we are going for annotations driven approach, we can use any POJO file as controller. It just needs to be in spring.sample.controller.

package spring.sample.controllers;

/*this url automatically gets redirected here*/
@RequestMapping(value = “/mylink”)
public class SampleController {

@RequestMapping(method = RequestMethod.GET)
public ModelAndView login() {
String message = “Welcome to the Spring 3.0 version!”;
return new ModelAndView(“welcome”, “message”, message);

6. And finally a simple welcome.jsp

<%@ page language=”java” contentType=”text/html; charset=UTF-8″
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>Welcome to Spring</title>

Leave a Reply

Your email address will not be published. Required fields are marked *