Tomcat serving static resources on Spring MVC app
I'm building a Spring MVC application, and the frontController servlet is mapped in "/" intercepting all requests, I'd to be able to serve the static contents (.js,.css,.png...) from tomcat and not by Spri开发者_JAVA技巧ng. My app structure is
-webapp/
styles/
images/
WEB-INF/
views/
By default, because the frontController is mapped on the context root of my app its handles all requests but don't serve any static resource. The mvc configurarion for static resources is follow.
<mvc:resources mapping="/resources/**" location="/"/>
And the page's code is:
<img src="resources/images/logo.png" />
I need to configure Tomcat to serve the static resources with no spring interaction.
Any suggestion?
You can remap tomcats default servlet (which handles static content), e.g.
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/images/*</url-pattern>
</servlet-mapping>
Have a look at this mailing list thread and see if that does what you're looking for.
Another potential solution - Just add the following to your Spring DispatcherServlet.xml (Spring Docs)
<mvc:default-servlet-handler/>
This tag allows for mapping the DispatcherServlet to "/" (thus overriding the mapping of the container's default Servlet), while still allowing static resource requests to be handled by the container's default Servlet. It configures a DefaultServletHttpRequestHandler with a URL mapping (given a lowest precedence order) of "/**". This handler will forward all requests to the default Servlet.
Pros (as compared to @nos's solution)
- The URL remapping solution behaves differently depending upon your container. Jetty/Tomcat 6 take that to mean 'map URL/images/* to WEBAPP/images/'. Tomcat < 6 (and maybe others) take that to mean 'map URL/images/ to WEBAPP/*', which is a BIG security breach.
- If you want to serve a favicon.ico, robots.txt etc. from your site, then you'll have to create additional url-mappings for them.
Cons
- Spring is in the loop, which is definitely something that is unnecessary.
Additionally, irrespective of the solution that one prefers, I'd suggest adding the following to your web.xml to prevent directory listings (on, say URL/images)
<servlet>
<servlet-name>default</servlet-name>
<init-param>
<param-name>dirAllowed</param-name>
<param-value>false</param-value>
</init-param>
</servlet>
精彩评论