什么是过滤器?什么时候使用过滤器?如何使用过滤器?过滤器的原理?

一、什么是过滤器?

含义:用于拦截数据源和目的数据之间的消息,并且过滤二者之间的传递的数据

 举例:比如过滤某一个格式的文件,然后对这个文件做一些修改

 

二、什么时候要用到过滤器?

 1、 认证过滤:对用户的请求进行统一认证

2、登陆和审核过滤:对用户的访问请求进行记录和审核

3、图像转换过滤

4、数据压缩过滤

 当然还有:

1、  过滤字符编码

2、  进行网站访问人数的统计

 

三、如何使用过滤器?

1、首先需要在web.xml中进行配置 

<filter>

    <display-name>Afilter</display-name>

    <filter-name>Afilter</filter-name>

    <filter-class>过滤器类所在的全路径 </filter-class>

  </filter>

  <filter-mapping>

    <filter-name>Afilter</filter-name>

    <url-pattern>/*</url-pattern><!-- 拦截所有请求 -->

  </filter-mapping>

2、然后直接编写一个实现过滤器接口的类,就是一个过滤器

 例如:如下是统计某一个网站被访问的次数的代码

package com.kgc.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class Afilter implements Filter {
    FilterConfig fConfig;
    public void destroy() {
        // TODO Auto-generated method stub
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获得与天地同寿的application
        ServletContext app = fConfig.getServletContext();
        //取出application中的map
        Map<String,Integer> map  = (Map<String, Integer>) app.getAttribute("map");
        //获取访问者的ip
        String ip = request.getRemoteAddr();
        //判断这个ip是否曾经来过
        if(map.containsKey(ip)){//来过,次数加1
            Integer count = map.get(ip);
            count+=1;
            map.put(ip, count);
        }else{//没来过,次数赋值为1
            map.put(ip, 1);
        }
        //map再次存到application中
        app.setAttribute("map", map);
        chain.doFilter(request, response);//放行
    }

    
    public void init(FilterConfig fConfig) throws ServletException {
        this.fConfig=fConfig;
    }
}

理解:

实现了Filter接口的类,需要实现三个方法,分别是init、doFilter、destroy

1、init方法:用于过滤器的初始化

2、doFilter方法:用于对请求进行过滤处理

3、destory方法:用于销毁方法用于释放资源

其中,doFilter方法有三个参数,分别是:ServletRequest request, ServletResponse response, FilterChain chain

 

 四、这三个参数分别有什么用?

1、request对象用于获取请求

2、response对象用于在调用chain.doFilter(request, response);时传入

3、chain对象就是用来调用doFilter方法的。

FilterChain接口中只有一个方法,就是doFilter(request, response),用于将过滤后的请求传递给下一个过滤器,如果当前过滤器就是最后一个过滤器,那么就把请求传递给目标资源。

 

五、如何读取配置文件中的初始化参数?

 FilterConfig接口中定义的getInitParameter方法,可以用于读取配置文件,在init方法中使用

public void init(FilterConfig fConfig) throws ServletException {

      String encoding = fConfig.getInitParameter("encoding");

   }

 

六、过滤器是如何运行的?

前文提到的在web.xml中配置好了拦截的请求路径,访问该路径,然后请求被发送到对应的过滤器进行处理

posted @ 2019-09-04 15:34  Java精进之路  阅读(2483)  评论(0编辑  收藏  举报