Simple Spring MVC Form Annotation Configuration Webapp

David Winterfeldt

2008


Simple Spring MVC form using annotation-based configuration. The webapp has basic create, update, delete, and search functionality for a person form. The form basically just has a hidden id (primary key), first name, and last name fields. Tiles is implemented with Spring by Example's Dynamic Tiles Spring MVC Module, Hibernate, and internationalized messages are configured, but this example will focus on explaining the MVC configuration.

1. Web Configuration

Below is the basic web.xml configuration. All Spring contexts in /WEB-INF/spring and end in *-context.xml will be loaded into one context. The default context file specific to the simple-form servlet is overridden to not load anything (/WEB-INF/simple-form-servlet.xml would have been loaded otherwise, the name of of the DispatcherServlet plus '-servlet.xml'). The servlet-mapping for 'simple-form' is configured to handle all requests ending in '.html'. The 'encoding-filter' sets all requests to the encoding type of UTF-8.

/WEB-INF/web.xml
                
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_3_0.xsd"
         version="3.0" metadata-complete="true">
                             
    <display-name>simple-form</display-name>
    
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring/*-context.xml
        </param-value>
    </context-param>

    <filter>
        <filter-name>encoding-filter</filter-name>
        <filter-class>
            org.springframework.web.filter.CharacterEncodingFilter
        </filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>encoding-filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>simple-form</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>simple-form</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
    
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>