代码如下,Javax.Servet包中提供了一个FilterCofig接口,容器将它作为参数传入过滤器的init()方法中,在浏览器地址栏中输入“http://localhost:8080/filterDemo/login.html”,循环遍历黑名单while(blackListNames.hasMoreElements()){//若登录账号是黑名单账号则不允许登录if(fConfig.getInitParameter(blackListNames.nextElement()).equals(name)){successde=false;}}if(successde){chain.doFilter(request,response);}else{response.getWriter().write("
示例在net.biancheng.www.filter包中,EnumerationgetInitParameterNames()返回过滤器的所有初始化参数名的枚举,如下表,创建名称为LoginServlet的类,FilterConfig接口(Servlet),FilterConfig接口由容器实现,在FilterConfig接口中,暂时不能为您提供服务\n");}}}publicvoidinit(FilterConfigfConfig)throwsServletException{this.fConfig=fConfig;}}在net.biancheng.www.servlet包中,代码如下,定义了4个方法,返回值类型方法描述StringgetInitParameter(Stringname)根据初始化参数名name,返回对应的初始化参数值,StringgetFilterName() 返回过滤器的名称,代码如下,packagenet.biancheng.www.filter;importjavax.servlet.*;importjava.io.IOException;importjava.util.Enumeration;/***黑名单过滤器**@author编程帮www.biancheng.net*/publicclassBlackListFilterimplementsFilter{privateFilterConfigfConfig;publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,FilterChainchain)throwsIOException,ServletException{response.setContentType("text/html;charset=UTF-8");Booleansuccessde=true;//获取前台登录的账号信息Stringname=request.getParameter("username");//获取过滤器中的初始化参数Enumeration账号 密码 启动Tomcat,packagenet.biancheng.www.servlet;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.io.IOException;/***@author编程帮www.biancheng.net*/@WebServlet("/login")publicclassLoginServletextendsHttpServlet{privatestaticfinallongserialVersionUID=1L;publicLoginServlet(){super();}protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{response.setContentType("text/html;charset=UTF-8");response.getWriter().write("
通过filterConfig对象就可以获得Filter的初始化参数,ServletContextgetServletContext()返回Servlet上下文对象的引用,。