Tuesday, July 31, 2007

"Hello, world" with Spring MVC

Recently I've started using of Srping MVC for my web apps. So what you need to get started with spring MVC:

1) Download Spring framework and put spring.jar to web server lib path.
2) Add DispathServlet mapping to web.xml

3) We have called servler instance as spring, so we should create a spring-servlet.xml at WEB-INF.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">


      <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
              <property name="mappings">
                             <prop key="/*.jsp">dispatchController</prop>

    <bean id="dispatchController" class="my.SimpleController">

      <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
              <property name="prefix">
             <property name="suffix">


We described 3 beans here.
urlMaping - is a mapping bean. It should not be registered manually. Spring will automatically parse it during initialization.
dispatchController - is a bean, which will be dispath all requests of *.jsp pages. We write class="my.SimpleController", so we need to create class SimpleController later.
viewResolver - is a bean? which will add prefix and suffix to views for creating valid request.

4) Create class my.SimpleController
package my;

import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SimpleController implements Controller {
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView mav = new ModelAndView("index");
        return mav;

This class will dispath all requests to the "index" view. Then "index" view will be changed to "/WEB-INF/jsp/index.jsp" by viewResolver bean.

5) Create "/WEB-INF/jsp/index.jsp".
     "Hello, world!" with Spring MVC.

That's all.