Tomcat 7.0 在war文件外使用别名去存储静态内容
web应用程序中的静态资源文件,比如象CSS,Javascript和视频文件、图片文件等。通常都把它们打包放在war文件中,这将增加了WAR文件的大小并且导致很多重复的加载静态资源。一个比较好的解决方法是使用Apache HTTP服务器去管理这些静态文件资源,下面是一个apache httpd.conf文件的配置摘录:< Directory "G:\images" >
Order allow,deny
Allow from all
< /Directory >
Alias /img "G:\images"
以上的设置,使得访问http://localhost:8080/img时,能访问到放在G:\images下的资源。
允许使用新的aliases属性,指出静态文件资源的位置,可以通过使用Classloader.getResourceAsStream('/img/...')或者在链接中嵌入的方法让TOMCAT去解析绝对路径,下面是一个在context.xml中配置的例子:
<Context path="/Test" aliases="/img=G:\images">
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->
<!-- Uncomment this to enable Comet connection tacking (provides events
on session expiration as well as webapp lifecycle) -->
<!--
<Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
-->
</Context>
假设g:/images这个文件夹存放有一张图片03105625.jpg,如果war文件以Test的名字部署,那么可以通过以下三个方式去访问这张图片
1 直接访问
http://localhost:8080/Test/img/03105625.jpg
2 在HTML链接中访问:< img src="/Test/img/03105625.jpg" / >
3 通过JAVA代码访问: ByteArrayInputStream bais = (ByteArrayInputStream)getServletContext().getResourceAsStream("/img/03105625.jpg");
使用aliases的好处是可以代替Apache的httpd.conf的设置,并且可以在servlet容器范围内访问,并且不需要Apache。
以上是参考http://www.iteye.com/news/17928(linux环境)在windows下做的尝试,测试结果可行。
页:
[1]