Spring : Spring MVC Quick Start

This page last changed on Apr 17, 2006 by Kees de Kooter

web.xml modifications:

<servlet>
    <servlet-name>spring-dispatcher</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>spring-dispatcher</servlet-name>
    <url-pattern>*.action</url-pattern>
</servlet-mapping>

This servlet finds its configuration in the following bean configuration file: WEB-INF/spring-dispatcher-servlet.xml

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

    <bean id="simpleUrlMapping"
        class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="/search.action">searchController</prop>
            </props>
        </property>
    </bean>
    
    <bean id="searchController"
        class="nl.quel.view.SearchController">
        <property name="objectFinder" ref="objectFinder"/>
        <property name="commandClass" value="nl..command.QueryCommand"/>
        <property name="queryFactory" ref="queryFactory"/>
    </bean>

</beans>

We are using a CommandContoller is this example. Spring MVC tries to put all posted (form)variables in the object specified by the commandClass property.

public class SearchController extends AbstractCommandController {

    private Logger logger = LoggerFactory.getLogger(getClass());
    private ObjectFinder objectFinder;
    private QueryFactory queryFactory;
    
    @Override
    protected ModelAndView handle(HttpServletRequest request, 
            HttpServletResponse response, Object object, 
            BindException bindException) throws Exception {
        
        QueryCommand queryCommand = (QueryCommand)object;
         
        if (queryCommand.getQuery() != null) {
            
            Query query = queryFactory.createQuery(queryCommand.getType(), 
                    queryCommand.getQuery());
            
            SearchResult searchResult = objectFinder.find(query,
                    queryCommand.getCurrentPageNumber(), 
                    queryCommand.getHitsPerPage());
            
            request.setAttribute("searchResult", searchResult);
        } else {
            queryCommand = new QueryCommand();
        }
        
        request.setAttribute("queryCommand", queryCommand);
        
        return new ModelAndView("/WEB-INF/jsp/search-result.jsp");
    }

    public void setObjectFinder(ObjectFinder objectFinder) {
        this.objectFinder = objectFinder;
    }

    public void setQueryFactory(QueryFactory queryFactory) {
        this.queryFactory = queryFactory;
    }

}