java web filter读取classpath配置文件内容

时间:2022-03-22 15:00:25

 

以下demo,从类路径classpath中获取venus.properties(本项目中用到的文件),思路是在初始化的时候读取,然后放在局部变量里面。

package club.codeapes.web.core.filter;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class WebRootPageFilter implements Filter {

    private String ssoOn;

    public void destroy() {

    }

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        //String effectivePath = request.getRequestURI().substring(request.getContextPath().length());
        System.out.println(ssoOn);
        chain.doFilter(request, response);
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        try {
            Properties configProperties = new Properties();
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("venus.properties");
            configProperties.load(inputStream);
            ssoOn = configProperties.getProperty("sso.on");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在初始化init方法里面使用,一般情况下,这个方法只调用一次,初始化的时候调用。