Tomcat serving static resources on Spring MVC app

橙三吉。 提交于 2019-12-01 03:48:32

问题


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 Spring. 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?


回答1:


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>



回答2:


Have a look at this mailing list thread and see if that does what you're looking for.




回答3:


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>


来源:https://stackoverflow.com/questions/3743932/tomcat-serving-static-resources-on-spring-mvc-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!