【发布时间】:2011-10-05 11:21:16
【问题描述】:
我想知道是否可以访问放在tomcat conf 文件夹中的文件。 通常我会在这个文件中放置多个 webapp 的配置,在战争之外。
我想使用独立于文件系统的类路径。
我过去使用过 lib 文件夹。它工作得很好。 但是用lib文件夹放conf文件有点没意思。
有人可以帮我解决这个问题吗?
【问题讨论】:
标签: file tomcat configuration classpath
我想知道是否可以访问放在tomcat conf 文件夹中的文件。 通常我会在这个文件中放置多个 webapp 的配置,在战争之外。
我想使用独立于文件系统的类路径。
我过去使用过 lib 文件夹。它工作得很好。 但是用lib文件夹放conf文件有点没意思。
有人可以帮我解决这个问题吗?
【问题讨论】:
标签: file tomcat configuration classpath
我已经看到人们在 webapps 中进行配置的许多不好的方式,要么使其无法真正配置(更改配置时必须重新部署/发布),要么灵活性很小。
我解决这个问题的方法是将 Spring 用于property placeholder,但通常你需要引导 Spring 或任何你的 MVC 堆栈,然后才能加载一个说明在哪里加载配置的属性。我为此使用了一个监听器:
package com.evocatus.util;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class SimpleContextListenerConfig /*extend ResourceBundle */ implements ServletContextListener{
private ServletContext servletContext;
@Override
public void contextInitialized(ServletContextEvent sce) {
servletContext = sce.getServletContext();
servletContext.setAttribute(getClass().getCanonicalName(), this);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
public static String getProperty(ServletContext sc, String propName, String defaultValue) {
SimpleContextListenerConfig config = getConfig(sc);
return config.getProperty(propName, defaultValue);
}
public static SimpleContextListenerConfig getConfig(ServletContext sc) {
SimpleContextListenerConfig config =
(SimpleContextListenerConfig) sc.getAttribute(SimpleContextListenerConfig.class.getCanonicalName());
return config;
}
public String getProperty(String propName, String defaultValue)
{
/*
* TODO cache properties
*/
String property = null;
if (property == null)
property = servletContext.getInitParameter(propName);
if (property == null)
System.getProperty(propName, null);
//TODO Get From resource bundle
if (property == null)
property = defaultValue;
return property;
}
}
https://gist.github.com/1083089
属性将首先从 servlet 上下文中提取,然后是系统属性,从而允许您覆盖某些 web 应用程序。 您可以通过更改 web.xml(不推荐)或 creating a context.xml
来更改某些 webapp 的配置您可以使用静态方法获取配置:
public static SimpleContextListenerConfig getConfig(ServletContext sc);
【讨论】: