Java Web总结十九Filter过滤器

一、Filter简介

  Filter也称之为过滤器,它是Servlet技术中最激动人心的技术,Web开发人员通过Filter技术,对Web服务器管理的所有Web资源:例如Jsp,Servlet,静态图片文件或静态HTML文件等进行拦截,从而实现一些特殊的功能。例如实现URL级别的权限访问控制、过滤敏感词汇、自动登录、压缩响应信息等一些高级功能。

  Servlet API中提供了一个Filter接口,开发Web应用时,如果编写的Java类实现了这个接口,则把这个Java类称之为过滤器Filter。通过Filter技术,开发人员可以实现用户在访问某个目标资源之前,对访问的请求和响应进行拦截,如下所示:

 

Java Web总结十九Filter过滤器

二、Filter开发步骤

  1、编写Java类实现Filter接口,并实现doFilter方法。

  2、在Web.xml文件中使用<filter>和<filter-mapping>元素对编写的Filter类进行注册,并设置它所能拦截的资源。

三、Filter链

  1、在一个Web应用中,可以开发编写多个Filter,这些Filter组合起来称之为Filter链。

  2、Web服务器根据Filter在web.xml文件中的注册顺序,决定先调用哪个Filter,当第一个Filter的doFilter方法被调用时,web服务器会创建一个代表Filter的FilterChain对象传递给该方法。在doFilter方法中,开发人员如果调用了FilterChain对象的doFilter方法,则web服务器会检查FilterChain对象中是否还有Filter,如果有,则调用第2个Filter,如果没有,则调用目标资源。

四、过滤器生命周期

  空参构造() 1次

  init() 1次

  doFilter(请求,响应,过滤器链) N次,与请求次数有关

  destory() 1次

  Filter是一个单例

五、使用Filter读取配置文件信息

  1、web.xml

Java Web总结十九Filter过滤器
<filter>
        <filter-name>FilterDemo4</filter-name>
        <filter-class>com.gnnuit.web.filter.FilterDemo4</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>

    </filter>

    <filter-mapping>
        <filter-name>FilterDemo4</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
Java Web总结十九Filter过滤器

 

  2、FilterDemo4.java

Java Web总结十九Filter过滤器
package com.gnnuit.web.filter;

import java.io.IOException;
import java.util.Enumeration;

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

//使用FilterConfig读取配置文件的信息
public class FilterDemo4 implements Filter {
    private FilterConfig filterConfig;

    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        // 方式一:读取一个
        String encoding = filterConfig.getInitParameter("encoding");
        response.setContentType("text/html;charset=" + encoding);

        // 方式二:读取多个
        Enumeration<String> enums = filterConfig.getInitParameterNames();
        while (enums.hasMoreElements()) {
            String key = enums.nextElement();
            String value = filterConfig.getInitParameter(key);
            System.out.println(key + ":" + value);
        }
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

}
Java Web总结十九Filter过滤器

 

五、Filter应用

1、统一Post请求中文字符编码的过滤器。(通过配置参数encoding指明使用何种字符编码,以处理表单form请求参数的中文问题)

(1)web.xml

Java Web总结十九Filter过滤器
<filter>
        <filter-name>FilterDemo5</filter-name>
        <filter-class>com.gnnuit.web.filter.FilterDemo5</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>

    </filter>

    <filter-mapping>
        <filter-name>FilterDemo5</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
Java Web总结十九Filter过滤器

 

(2)FilterDemo5.java

Java Web总结十九Filter过滤器
package com.gnnuit.web.filter;

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;

//post请求中文字符编码的过滤器
public class FilterDemo5 implements Filter {
    private FilterConfig filterConfig;

    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        // 设置post请求编码
        request.setCharacterEncoding("utf-8");

        // 设置输出编码
        String encoding = filterConfig.getInitParameter("encoding");
        response.setContentType("text/html;charset=" + encoding);

        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

}
Java Web总结十九Filter过滤器

 

2、禁止浏览器缓存所有动态页面的过滤器

(1)web.xml

Java Web总结十九Filter过滤器
<filter>
        <filter-name>FilterDemo6</filter-name>
        <filter-class>com.gnnuit.web.filter.FilterDemo6</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>html</param-name>
            <param-value>86400</param-value>
        </init-param>

    </filter>

    <filter-mapping>
        <filter-name>FilterDemo6</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
Java Web总结十九Filter过滤器

 

(2)FilterDemo6.java

Java Web总结十九Filter过滤器
package com.gnnuit.web.filter;

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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//禁止浏览器缓存所有动态资源[例如JSP资源]
//浏览器缓存所有静态资源,并指定缓存时间[例如html资源]
public class FilterDemo6 implements Filter {
    private FilterConfig filterConfig;

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String uri = httpRequest.getRequestURI();
        if (uri != null && uri.endsWith("jsp")) {
            httpResponse.setHeader("expires", "-1");
            httpResponse.setHeader("cache-control", "no-cache");
            httpResponse.setHeader("pragma", "no-cache");
        } else if (uri != null && uri.endsWith(".html")) {
            String strHtml = filterConfig.getInitParameter("html");
            long time = System.currentTimeMillis() + Integer.parseInt(strHtml)
                    * 1000;
            // time为毫秒值
            httpResponse.setDateHeader("expires", time);
            httpResponse.setHeader("cache-control", time / 1000 + "");
            httpResponse.setHeader("pragma", time / 1000 + "");
        }
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

}
Java Web总结十九Filter过滤器

 

 

Java Web总结十九Filter过滤器,布布扣,bubuko.com

Java Web总结十九Filter过滤器

上一篇:python3.4 编译时提示错误 IndentationError: unexpected indent


下一篇:Spring JPA 缺少 JAR 引起异常