06.过滤器(Filter)

六、过滤器
6.1 概念

什么是过滤器

过滤器(Filter)是处于客户端与服务器目标资源之间的一道过滤技术。

过滤器作用

在访问目标资源文件之前,通过一系列的过滤器对请求进行修改、判断等,把不符合规则的请求在中途拦截或修改。也可以对响应进行过滤,拦截或修改响应。

例如:实现权限访问控制、过滤敏感词汇、压缩响应信息功能。

6.2 如何编写过滤器

Servlet API中提供了一个Filter接口,开发人员编写一个Java类实现了这个接口即可,这个Java类称之为过滤器(Filter)

步骤如下:

1、编写Java类实现Filter接口
2、在doFilter方法中编写拦截逻辑
3、设置拦截路径

案例

package com.qf.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * @author wgy 2018/11/28 9:23
 * @version 1.0
 */
@WebFilter("/myservlet1")//过滤路径
public class MyFilter1 implements Filter {

    //初始化过滤器
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器初始化了........init...  "+filterConfig);
    }

    //执行过滤
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("过滤前........doFilter ");
        //放行
        chain.doFilter(request, response);

        System.out.println("过滤后.......doFilter");

    }

    //销毁
    @Override
    public void destroy() {
        System.out.println("销毁了.....destroy");
    }
}

Servlet执行过程

Filter0

6.3 过滤器配置
6.3.1 注解配置

在自定义的Filter类上使用注解@WebFilter(“/*”)

6.3.2 xml配置

在web.xml中进行过滤器的配置

<!--过滤器的xml配置  -->
  <filter>
  <!--名称-->
    <filter-name>sf</filter-name>
    <!--过滤器类全称-->
    <filter-class>com.qf.web.filter.SecondFilter</filter-class>
  </filter>
 <!--映射路径配置-->
  <filter-mapping>
     <!--名称-->
    <filter-name>sf</filter-name>
     <!--过滤的url匹配规则和Servlet类似-->
    <url-pattern>/*</url-pattern>
  </filter-mapping>
6.3.3 关于拦截路径
过滤器的拦截路径通常有三种形式:
(1)精确拦截匹配 ,比如/index.jsp   /myservlet1
(2)后缀拦截匹配,比如*.jsp、*.html、*.jpg
(3)通配符拦截匹配/*,表示拦截所有、注意过滤器不能使用/匹配。
	/aaa/bbb/* 允许
6.4 过滤器链和优先级

过滤器链

Filter

客户端对服务器请求之后,服务器调用Servlet之前会执行一组过滤器(多个过滤器),那么这组过滤器就称为一条过滤器链。

每个过滤器实现某个特定的功能,当第一个Filter的doFilter方法被调用时,Web服务器会创建一个代表Filter链的FilterChain对象传递给该方法。在doFilter方法中,开发人员如果调用了FilterChain对象的doFilter方法,则Web服务器会检查FilterChain对象中是否还有filter,如果有,则调用第2个filter,如果没有,则调用目标资源。

过滤器优先级

在一个Web应用中,可以开发编写多个Filter,这些Filter组合起来称之为一个Filter链。这些过滤器的执行顺序由filter-mapping的顺序决定,前面filter-mapping优先级高于后面的。
​ 注意:
​ 1、如果为注解的话,是按照类全名称的字符串顺序进行起作用的
​ 2、如果web.xml,按照 filter-mapping注册顺序,从上往下
​ 3、web.xml配置高于注解方式
​ 4、如果注解和web.xml同时配置,会创建多个过滤器对象,造成过滤多次。

6.5 过滤器初始化参数

在创建过滤器时,可以传递初始化参数

方式一、基于注解配置
/**
 * Servlet Filter implementation class FirstFilter 创建过滤器
 */
@WebFilter(value="/*",initParams= {@WebInitParam(name = "version", value = "1.0")})
public class FirstFilter implements Filter {

	/**
	 * Default constructor.
	 */
	public FirstFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy() 销毁
	 */
	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("destroy销毁……");
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) 过滤
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
		System.out.println("doFilter……过滤");
		// 是否继续---访问下一个
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 * 初始化
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("init……初始化");
		System.out.println("初始化参数:版本号:"+fConfig.getInitParameter("version"));
	}
}
方式二、基于xml配置
/**
 *  创建过滤器
 */
public class SecondFilter implements Filter {

	/**
	 * Default constructor.
	 */
	public SecondFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy() 销毁
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) 过滤
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// 是否继续---访问下一个
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 * 初始化
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("初始化参数:版本号:"+fConfig.getInitParameter("version"));
	}

}

Web.xml实现配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
  <display-name>Web_Day</display-name>
  
  <!--过滤器的xml配置  -->
  <filter>
    <filter-name>myfilter</filter-name>
    <filter-class>com.qf.web.filter.SecondFilter</filter-class>
     <!--过滤器的初始化参数  -->
    <init-param>
      <param-name>version</param-name>
      <param-value>1.0</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>myfilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
</web-app>
6.6 过滤器典型应用
案例1、过滤器解决编码
public class CharacterEncodingFilter implements Filter {

	//filter配置
	private FilterConfig config;
	//默认编码
	private String defaultcharset="utf-8";
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		this.config=filterConfig;
	}
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		String charset=config.getInitParameter("charset");
		if(charset==null){
			charset=defaultcharset;
		}
		//1设置请求和响应的编码
		request.setCharacterEncoding(charset);
		//response.setContentType("text/html;charset="+charset);
		//2放行
		chain.doFilter(request, response);
		System.out.println("xxxxxxxxxxxxxxxx");
	
	}

	@Override
	public void destroy() {
		
	}
}
案例2、自动登录

login.jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>用户登录</title>
</head>
<body>
    <h2>用户登录</h2>
    <form action="${pageContext.request.contextPath}/login" method="post">
        用户名:<input type="text" name="username"><br/>
        密码:<input type="password" name="pwd"><br/>
        <input type="submit" value="登录"> <input type="checkbox" name="auto">自动登录

    </form>
</body>
</html>

User类:

public class User {
	private int id;
	private String username;
	private String pass;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPass() {
		return pass;
	}
	public void setPass(String pass) {
		this.pass = pass;
	}
}

LoginServlet代码

@WebServlet(name = "LoginServlet",value = "/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1解决乱码问题
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //2获取数据
        String username = request.getParameter("username");
        String pwd = request.getParameter("pwd");
        String auto = request.getParameter("auto");
        PrintWriter out = response.getWriter();
        if(username==null||username.trim().length()==0){
            out.println("用户名不能为空");
            return;
        }
        if(pwd==null||pwd.trim().length()==0){
            out.println("密码不能为空");
            return;
        }
        //3连接数据库
        if(username.equals("jiangjiang")&&pwd.equals("888")){
            User user=new User(username, pwd);
            //把用户登录信息放入session
            request.getSession().setAttribute("user", user);
            if(auto!=null){//勾选自动登录
                String userinfo=username+"#"+pwd;
                //Base64编码
                userinfo = Base64.getEncoder().encodeToString(userinfo.getBytes());
                Cookie cookie=new Cookie("userinfo", userinfo);
                cookie.setMaxAge(60*60*24*14);
                cookie.setHttpOnly(true);
                response.addCookie(cookie);
            }
            //重定向首页
            response.sendRedirect(request.getContextPath()+"/index.jsp");

        }else{
            out.println("用户名或密码错误");
            return;
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

过滤器代码:

@WebFilter(filterName = "AutoLoginFilter",value = "/index.jsp")
public class AutoLoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //读取cookie
        HttpServletRequest request= (HttpServletRequest) req;
        HttpServletResponse response= (HttpServletResponse) resp;
        //1先判断当前是否登录
        User user = (User) request.getSession().getAttribute("user");
        if(user!=null){//已经登录
            chain.doFilter(req, resp);
            return;
        }
        //2没有登录
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            //遍历cookie
            for (Cookie cookie : cookies) {
                //判断userinfo
                if(cookie.getName().equals("userinfo")){
                    String userinfo = cookie.getValue();
                    //Base64解密
                    byte[] decode = Base64.getDecoder().decode(userinfo);
                    userinfo=new String(decode);
                    System.out.println(userinfo);
                    String[] userinfos = userinfo.split("#");
                    String username=userinfos[0];
                    String pwd=userinfos[1];
                    //判断用户名和密码是否正确
                    if(username.equals("jiangjiang")&&pwd.equals("888")){
                        User user1=new User(username, pwd);
                        request.getSession().setAttribute("user", user1);
                    }else{//删除cookie
                        Cookie cookie1=new Cookie("userinfo", "");
                        cookie1.setMaxAge(0);
                        cookie1.setHttpOnly(true);
                        response.addCookie(cookie1);

                    }
                }
            }
        }

        chain.doFilter(req, resp);
    }
    public void init(FilterConfig config) throws ServletException {
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值