---
title: "Tomcat 7.0  在war文件外使用别名去存储静态内容"
author: "cn-done"
date: "2010-09-30T00:43:49Z"
tags: ["Apache", "Comet", "Linux", "Tomcat", "Web"]
categories: ["企业架构"]
slug: "tomcat-7-0-war"
draft: false
lastmod: "2010-09-30T00:43:49Z"
id: 775553
url: "https://cn-done.iteye.com/blog/775553"
---

web应用程序中的静态资源文件，比如象CSS，Javascript和视频文件、图片文件等。通常都把它们打包放在war文件中，这将增加了WAR文件的大小并且导致很多重复的加载静态资源。一个比较好的解决方法是使用Apache HTTP服务器去管理这些静态文件资源，下面是一个apache httpd.conf文件的配置摘录：

&lt; Directory "G:\\images" &gt;  
Order allow,deny  
Allow from all  
&lt; /Directory &gt;  
Alias /img "G:\\images"

　　以上的设置，使得访问[http://localhost:8080/img](http://localhost:8080/img)时，能访问到放在G:\\images下的资源。

　　允许使用新的aliases属性，指出静态文件资源的位置，可以通过使用Classloader.getResourceAsStream('/img/...')或者在链接中嵌入的方法让TOMCAT去解析绝对路径，下面是一个在context.xml中配置的例子：

&lt;Context path="/Test" aliases="/img=G:\\images"&gt;

    &lt;!-- Default set of monitored resources --&gt;  
    &lt;WatchedResource&gt;WEB-INF/web.xml&lt;/WatchedResource&gt;

    &lt;!-- Uncomment this to disable session persistence across Tomcat restarts --&gt;  
    &lt;!--  
    &lt;Manager pathname="" /&gt;  
    --&gt;

    &lt;!-- Uncomment this to enable Comet connection tacking (provides events  
         on session expiration as well as webapp lifecycle) --&gt;  
    &lt;!--  
    &lt;Valve className="org.apache.catalina.valves.CometConnectionManagerValve" /&gt;  
    --&gt;

&lt;/Context&gt;

　　假设g:/images这个文件夹存放有一张图片03105625.jpg，如果war文件以Test的名字部署，那么可以通过以下三个方式去访问这张图片

　　1 直接访问

　　[http://localhost:8080/Test/img/03105625.jpg](http://localhost:8080/Test/img/03105625.jpg)

　　2 在HTML链接中访问：&lt; img src="/Test/img/03105625.jpg" / &gt;

　　3 通过JAVA代码访问： ByteArrayInputStream bais = (ByteArrayInputStream)getServletContext().getResourceAsStream("/img/03105625.jpg");

　　使用aliases的好处是可以代替Apache的httpd.conf的设置，并且可以在servlet容器范围内访问，并且不需要Apache。

 

以上是参考[http://www.iteye.com/news/17928](http://www.iteye.com/news/17928)（linux环境）在windows下做的尝试，测试结果可行。