filter过滤器的使用

过滤器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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值