Tomcat提供静态内容 [英] Tomcat serving static content
问题描述
我有一个Spring应用程序,我想知道提供静态内容的最佳方式。我尝试过以下方法:
I have a Spring app and I'm wondering the best way to serve static content. I have tried the following:
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/static/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
这有效,但DefaultServlet的行为意味着任何形式的请求 / static / PATH
从 webapp / PATH
提供文件。这暴露了一个巨大的漏洞,允许使用以下URL显示敏感信息: http:// localhost / app / static / META-INF / context.xml
This works, but the behaviour of the DefaultServlet means that any request of the form /static/PATH
serves the file from webapp/PATH
. This exposes a massive vulnerability, allowing sensitive information to be shown with URLs such as: http://localhost/app/static/META-INF/context.xml
这是什么常见的解决方案?我应该移动敏感文件吗?写我自己的DefaultServlet?或者有更好的方式来提供静态内容吗?
What's the common solution for this? Should I move the sensitive files? Write my own DefaultServlet? Or is there a better way to serve static content?
推荐答案
有几种更好的方式来提供静态内容。
There are several better ways to serve static content.
传统方法是使用 UrlRewriteFilter
重新映射网址,如下所示:
The traditional approach was to use a UrlRewriteFilter
to remap URLs as follows:
web.xml
:
<filter>
<filter-name>UrlRewriteFilter</filter-name>
<filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>UrlRewriteFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
...
<servlet-mapping>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>
urlrewrite.xml
:
<urlrewrite default-match-type="wildcard">
<rule>
<from>/images/**</from>
<to>/images/$1</to>
</rule>
<rule>
<from>/scripts/**</from>
<to>/scripts/$1</to>
</rule>
<rule>
<from>/styles/**</from>
<to>/styles/$1</to>
</rule>
<rule>
<from>/**</from>
<to>/app/$1</to>
</rule>
</urlrewrite>
大多数Spring样本都可以看到这种方法。
Spring 3.0.1引入了更新的apporach - 它可以通过
DispatcherServlet
提供静态内容。可以使用Spring的配置文件中的< mvc:resource>
元素进行配置。在Spring 3.0.4中,它通过支持多个位置和缓存控制选项进行了扩展,请参阅 15.12.4 mvc:resources 。
This approach can be seen in the most of Spring samples.
Spring 3.0.1 introduced a newer apporach - it can serve static content via
DispatcherServlet
. It can be configured using <mvc:resource>
element in Spring's config file. In Spring 3.0.4 it was extended with support of multiple location and cache control options, see 15.12.4 mvc:resources.
这篇关于Tomcat提供静态内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!