package example_2_lg;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class BlockFilter implements Filter {

  private FilterConfig config;

  /** 新建一个 BlockFilte */
  public BlockFilter() {
  }

  public void init(FilterConfig filterConfig) throws ServletException {

    this.config = filterConfig;
  }

  public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) throws IOException, ServletException {

    HttpServletRequest req = null;
    boolean authenticated = false;
    PrintWriter out = null;

    if (request instanceof HttpServletRequest) {

      req = (HttpServletRequest) request;
      String user = req.getParameter("user");
      authenticated = authenticateUser(user);
    }

    if (authenticated) {
      chain.doFilter(request, response);
    } else {

      response.setContentType("text/html;charset=gb2312");
      out = response.getWriter();
      out.println("<html><head><title>验证响应</title></head><body>");
      out.println("<h2>对不起，验证失败</h2>");

      out.println("</body></html>");
      out.close();

    }
  }// doFilter

  public void destroy() {
    /*
     * 停用过滤器的实例之前,Web 容器调用了此方法.
     */
  }
  private boolean authenticateUser(String userName) {

    //可以使用各种方法验证，如数据库验证，这里简化为：
    	if(username.equals(“wanghong”))
	return true;
	return false;
  }
}
