//WEB-INF/classes/NoteFilter.class
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class NoteFilter implements Filter{
private FilterConfig config=null;
private String blackList=null;
public void init(FilterConfig config)throws ServletException{
this.config=config;
blackList=config.getInitParameter(“blacklist”);
}
public void destroy(){
config=null;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException{
String userName=((HttpServletRequest)request).getParameter(“user_name”);
if(userName!=null)
userName=new String(userName.getBytes(“ISO-8859-1”),”GB2312”);
if(userName!=null && userName.indexOf(blackList)!=-1){
PrintWriter out=response.getWriter();
out.print(“<html><body>”);
out.print(“<h1>对不起,”+userName+”,你没有权限留言</h1>”);
out.print(“</body></html>”);
out.flush();
return;
}
long before=System.currentTimeMillis();
config.getServletContext().log(“NoteFilter:before call chain.doFilter()”);
chan.doFilter(request, response);
config.getServletContext().log(“NoteFilter:after call chain.doFilter()”);
logn after=System.currentTimeMillis();
String name=””;
if(request instanceof HttpServletRequest)
name=((HttpServletRequest)request).getRequestURL();
config.getServletContext().log(“NoteFilter:”+name+”:”+(after-before)+”ms”);
}
}
。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
发布Servlet过滤器,必须在web.xml文件中加入<filter>和<filter-mapping>元素,如下:
<filter>
<filter-name>NoteFilter</filter>
<filter-class>NoteFilter</filter-class>
<init-param>
<param-name>blackList</param-name>
<param-value>捣蛋鬼</param-value>
</init-param>
<filter>
<filter-mapping>
<filter-name>NoteFilter</filter-name>
<url-pattern>/note</url-pattern>
</filter-mapping>