web.xml中webAppRootKey
------------------------------------------------------------------------------------------------
1、 web.xml配置
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>webapp.root</param-value>
</context-param>
"webapp.root"這個字符串可以隨便寫任何字符串。如果不配置默認值是"webapp.root"。
可以用System.getProperty("webapp.root")來動態獲項目的運行路徑。
一般返回結果例如:/usr/local/tomcat6/webapps/項目名
2、解決以下報錯
部署在同一容器中的Web項目,要配置不同的<param-value>,不能重複,否則報類似下面的錯誤:
Web app root system property already set to different value: 'webapp.root' = [/home/user/tomcat/webapps/project1/] instead of [/home/user/tomcat/webapps/project2/] - Choose unique values for the 'webAppRootKey' context-param in your web.xml files!
意思是“webapp.root”這個key已經指向了項目1,不可以再指向項目2.
3、加載方式
Spring通過org.springframework.web.util.WebAppRootListener 這個監聽器來運行時的項目路徑。
但是如果在web.xml中已經配置了 org.springframework.web.util.Log4jConfigListener這個監聽器,
則不需要配置WebAppRootListener了。因爲Log4jConfigListener已經包含了WebAppRootListener的功能
一般配置類型下面的例子:
- <!-- 加載Log4J 配置文件 -->
- <context-param>
- <param-name>log4jConfigLocation</param-name>
- <param-value>WEB-INF/conf/log4j.properties</param-value>
- </context-param>
- <context-param>
- <param-name>log4jRefreshInterval</param-name>
- <param-value>3000</param-value>
- </context-param>
- <listener>
- <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
- </listener>
4、在運行時動態的找出項目的路徑
在log4j.properties配置文件,就可以按下面的方式使用${webapp.root}:
log4j.appender.file.File=${webapp.root}/WEB-INF/logs/sample.log
就可以在運行時動態的找出項目的路徑
5、默認配置
public static void setWebAppRootSystemProperty(ServletContext servletContext) throws IllegalStateException {
String param = servletContext.getInitParameter(WEB_APP_ROOT_KEY_PARAM);
String key = (param != null ? param : DEFAULT_WEB_APP_ROOT_KEY);
String oldValue = System .getProperty(key);
if (oldValue != null ) {
throw new IllegalStateException ("WARNING: Web app root system property already set: "
+ key + " = " + oldValue + " - Choose unique webAppRootKey values in your web.xml files!" );
}
String root = servletContext.getRealPath("/" );
if (root == null ) {
throw new IllegalStateException ("Cannot set web app root system property when WAR file is not?expanded");
}
System .setProperty(key, root);
servletContext.log("Set web app root system property: " + key + " = " + root);
}
最後將webAppRootKey項配置好。