JAVA基础辅导(filter过滤器的使用)
来源:优易学  2011-11-19 9:50:59   【优易学:中国教育考试门户网】   资料下载   IT书店
  过滤器Web 服务组件,它能截获请求和响应并作处理,因此它可以在请求和响应到达目的之前向Web应用程序的请求和响应添加功能。
  过滤器生活在Servlet容器中,它也有生命周期,它的生命周期由servlet容器管理。
  过滤器必须是一个实现Filter接口的类的对象,否则不具备过滤器的功能。 Filter接口的主要方法:
  public void init(FilterConfig fg) //被容器调用初始化过滤器
  public void doFilter(ServletRequest req,ServletResponse res, FilterChain chain)// 每当有请求或响应时被容器调用进行过滤
  public void destroy()//被容器调用销毁过滤器
  有时一个Web应用中的过滤器不止一个,如一个过滤器完成编码转换,另一个完成验证。这时就要把它们组成链,按配置的顺序一一进行过滤,就要用到过滤器链接口FilterChain。FilterChain接口用于调用过滤器链中的一系列过滤器,通过该接口把被过滤的任务在Filter间传递,它的主要方法 :
  public void doFilter(ServletRequest req,ServletResponse res) //调用下一个过滤器,若无下一过滤器,则将请求或响应传递到目标。
  过滤器应用可以使很多东西轻松实现:如权限认证,中文编码问题等。
  下面以中文编码问题为例:
  import java.io.IOException;
  import javax.servlet.Filter;
  import javax.servlet.FilterChain;
  import javax.servlet.FilterConfig;
  import javax.servlet.ServletException;
  import javax.servlet.ServletRequest;
  import javax.servlet.ServletResponse;
  public class SetEncodingFilter implements Filter {
  protected String encoding = null;
  protected FilterConfig filterConfig = null;
  protected boolean ignore = true;
  public void destroy() {
  this.encoding = null;
  this.filterConfig = null;
  }
  public void doFilter(ServletRequest request, ServletResponse response,
  FilterChain chain) throws IOException, ServletException {
  if (ignore || (request.getCharacterEncoding() == null)) {
  request.setCharacterEncoding(selectEncoding(request));
  }
  chain.doFilter(request, response);
  }
  public void init(FilterConfig filterConfig) throws ServletException {
  this.filterConfig = filterConfig;
  this.encoding = filterConfig.getInitParameter("encoding");
  String value = filterConfig.getInitParameter("ignore");
  if (value == null)
  this.ignore = true;
  else if (value.equalsIgnoreCase("true")
  || value.equalsIgnoreCase("yes"))
  this.ignore = true;
  else
  this.ignore = false;
  }
  protected String selectEncoding(ServletRequest request) {
  return (this.encoding);
  }
  public FilterConfig getFilterConfig() {
  return filterConfig;
  }
  public void setFilterConfig(FilterConfig filterConfig) {
  this.filterConfig = filterConfig;
  }
  }
  web.xml对应配置如下:
  <filter>
  <filter-name>SetCharsetEncodingFilter</filter-name>
  <filter-class>filter.SetEncodingFilter</filter-class>
  <init-param>
  <param-name>encoding</param-name>
  <param-value>UTF-8</param-value>
  </init-param>
  </filter>
  <filter-mapping>
  <filter-name>SetCharsetEncodingFilter</filter-name>
  <url-pattern>/*</url-pattern>
  </filter-mapping>

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训