If you know Spring, you know what place DispatcherServlet holds in this framework as it is the one for handling View mapping in Spring MVC and the files. I recently had my play with this framework along-with couple of others and there I faced a problem in Spring MVC when I was done with multiple sections in a specific project. I wanted to define mapping for different sections separately so that if I access any file using http://localhost:8080/module1/index.html, I should be getting completely different section mapped in module1-servlet.xml which is defined in web deployer web.xml as –
<servlet> <servlet-name>module1</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>module1</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping>
Bean declaration in module1-servlet.xml is like –
<bean name="/module1/index.html" class="org.springframework.showcase.module1.web.IndexController"> <property name="viewName" value="module1/index"/> </bean>
And then I try to create DispatcherServlet for another section – module2, with same signature as for module1 in web.xml –
<servlet> <servlet-name>module2</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>module2</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping>
With this mapping, I create another servlet named module2-servlet.xml and there bean declaration looks like –
<bean name="/module2/index.html" class="org.springframework.showcase.module1.web.IndexController"> <property name="viewName" value="module2/index"/> </bean>
With this configuration, when I try to open http://localhost:8080/module2/index.html, 404 error is displayed which means Page Not Found. If you have worked on Struts framework, you might already be knowing the work-around.
This is because we are using same <url-pattern> tag for both modules with same servlet class – DispatcherServlet which is not correct. We can have multiple DispatcherServlets with distinct <url-pattern> tag values. So in order to sort out this issue, I changed module2 entry in web.xml as –
<servlet> <servlet-name>module2</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>module2</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping>
And bean entry in module2-servlet.xml was changed to –
<bean name="/module2/index.htm" class="org.springframework.showcase.module1.web.IndexController"> <property name="viewName" value="module2/index"/> </bean>
After this, I was able to open http://localhost:8080/module2/index.htm