2016-01-20 25 views
0

我正在构建一个简单的Java过滤器,最终将配置在不同的WEB应用程序中。该WEB应用程序将在web.xml中配置此过滤器,并提供一个init-param,其值是一个属性文件的路径。自定义过滤器不是读取属性文件,它放置在一个WEB应用程序中,使用该过滤器

自定义过滤器假设读取此属性文件。虽然我无法阅读这个属性文件。

这里是CustomFilter的代码。这是maven安装到jar文件中的。

public class CustomFilter implements Filter{ 
 
    ... 
 
    // invoked from init() 
 
\t Properties loadProperties(FilterConfig filterConfig) { 
 
\t \t 
 
\t \t String initParamName = "someParamName"; 
 
\t \t String pathToProperties = filterConfig 
 
\t \t \t \t .getInitParameter(initParamName); 
 
\t \t 
 
\t \t LOG.info("Path to Properties File is:" + pathToProperties); 
 
\t \t InputStream input = null; 
 
\t \t Properties properties = new Properties(); 
 
\t \t try { 
 
\t \t \t // Read the Properties file a Stream 
 
\t \t \t /*input = Thread.currentThread().getContextClassLoader() 
 
\t \t \t \t \t .getResourceAsStream(pathToProperties);*/ // input is null 
 
\t \t \t 
 
\t \t \t /*input = this.getClass() 
 
\t \t \t \t \t .getResourceAsStream(pathToProperties);*/ // input is null 
 

 
\t \t \t ServletContext servletContext = filterConfig.getServletContext(); 
 
\t \t \t 
 
\t \t \t LOG.info("servletContext.getContextPath(): " + servletContext.getContextPath()); 
 
\t \t \t 
 
      //LOG.info("servletContext.getContextPath(): " + servletContext.get; 
 
\t \t \t //input = servletContext.getResourceAsStream(pathToProperties); //input is null 
 
\t \t \t 
 
\t \t \t input = servletContext.getClass().getClassLoader().getResourceAsStream(pathToProperties); 
 
//input is null 
 
\t \t \t 
 
\t \t \t 
 
\t \t \t LOG.info("+++++++++++++++++++++++++==" + input); 
 
\t \t \t // Load Stream to Properties, key=value in properties file gets 
 
\t \t \t // converted to [key:value] prop 
 
\t \t \t properties.load(input); 
 

 
\t \t } catch (IOException e) { 
 
\t \t \t ... 
 
\t \t } 
 
\t \t 
 
\t \t 
 
\t \t return null; 
 
\t } 
 

 

 

 

 
}

上面创建的JAR文件中包含的Maven经由POM一个REST服务项目内。 REST服务内的过滤器的web.xml配置是

\t <filter> 
 
\t \t <filter-name>customFilter</filter-name> 
 
\t \t <filter-class>com.abc.xyz.CustomFilter</filter-class> 
 
\t \t <init-param> 
 
\t \t \t <param-name>someParamName</param-name> 
 
\t \t \t <param-value>hello.properties</param-value> 
 
\t \t </init-param> 
 
\t </filter> 
 
\t <filter-mapping> 
 
\t \t <filter-name>customFilter</filter-name> 
 
\t \t <url-pattern>/*</url-pattern> 
 
\t </filter-mapping>

属性文件hello.properties保持REST服务项目内,在相同的位置,其中,所述的web.xml驻留。

请注意: 当同一属性文件保持在第一罐子内,在创建CustomFilter包,代码工作完美无缺。但是,这不是我们打算做的。

此外,我无法使用基于SPRING的解决方案来读取属性文件。只有基于Java的。

回答

1

你想加载文件夹中的资源/WEB-INF(你说它位于在与web.xml相同的位置)。

ServletContext.getResourceAsStream是要走的路,但你需要/WEB-INF/前缀资源名称:

String pathToProperties = "/WEB-INF/" + filterConfig.getInitParameter("someParamName"); 
InputStream input = filterConfig.getServletContext().getResourceAsStream(pathToProperties); 
+0

谢谢。它按照你的建议工作。 – DolphinJava

相关问题