Spring MVC letting tomcat resolve files

Finally found what I was looking for after much searching…

In your web.xml:


  <!– Handles all requests into the application –>
  <servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>

The problem: 

Spring’s dispatcher servlet handles ALL requests… Yes, you get nice clean urls to your controller request mappings, but simple things like /index.html or / or /someimage.jpg fall apart. Spring attempts to run those requests through it’s own view resolvers, when you most likely want to have the default tomcat servlet handle it. 

It seems this can be fixed with a single line of code. 

  <!– Allows the default servlet to handle unmapped resources by trying to resolve to static resources –>
  <mvc:default-servlet-handler/>

Now, if your request doesn’t match a registered RequestMapping, it will simply pass it through to the underlying servlet. So, /index.html, resolves to /index.html. And is not handled by spring or any view resolver, but by the servlet (in my case tomcat) which is the way it should be… 



Published by and tagged Code using 163 words.