Configuration

Configure dispatcher server in web.xml

DispatcherServlet is mapped in web.xml to handle Spring URLs. Here is sample configuration code:

<servlet>

<servlet-name>st-dispatcher</servlet-name>

<servlet-class>

org.springframework.web.servlet.DispatcherServlet

</servlet-class>

<load-on-startup>0</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>st-dispatcher</servlet-name>

<url-pattern>*.do</url-pattern>

</servlet-mapping>

When DispatcherServlet is initialized, the framework will try to load the application context from a file named [servlet-name]-servlet.xml located in the /WEB-INF directory. In above case file name will be /WEB-INF/st-dispatcher-servlet.xml.

Tag <servlet-mapping> contains the URL pattern that is handled by DispatcherServlet. Here all the HTTP URLs suffixed by .do will be handled by the DispatcherServlet. In most of the cases, all URLs are handled by DispatcherServlet so pattern will be specified as:

<url-pattern>/</url-pattern>

If you do not want to go with default filename as [servlet-name]-servlet.xml and default location as /WEB-INF, you can customize this file name and location by adding the servlet listener ContextLoaderListener in your web.xml file as follows:

<web-app...>

....

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>/WEB-INF/st-dispatcher-servlet.xml</param-value>

</context-param>

<listener>

<listener-class>

org.springframework.web.context.ContextLoaderListener

</listener-class>

</listener>

</web-app>

Create [servlet-name]-servlet.xml configuration file:

Create Spring configuration file [servlet-name]-servlet.xml to define beans.

<!--Scan @Repository, @Service, @Component and @Controller spring beans -->

<context:component-scan base-package="in.co.sunrays.spring" />

<!--Enables MVC annotation like @Valid, @RequestMapping etc. -->

<mvc:annotation-driven />

<!-- enable the configuration of transactional behavior based on annotations -->

<tx:annotation-driven transaction-manager="hibernateTransactionManager" />

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix">

<value>/WEB-INF/pages/</value>

</property>

<property name="suffix">

<value>.jsp</value>

</property>

</bean>

The <context:component-scan...> tag will be used to activate Spring MVC annotation scanning capability which allows to make use of annotations like @Controller and @RequestMapping etc. Sometimes it is also called auto-discovery.

The InternalResourceViewResolver will be defined to resolve the view names. As per the above defined rule, a logical view named "login" is delegated to a view implementation located at /WEB-INF/pages/login.jsp .

The <mvc:annotation-driven /> tag declares explicit support for annotation-driven MVC controllers (i.e. @RequestMapping, @Controller), as well as adding support for declarative validation via @Valid and message body marshalling with @RequestBody/ResponseBody.