过滤器学习

一,过滤器

1.1 什么是过滤器

Filter也称之为过滤器,它是Servlet技术中最激动人心的技术,WEB开发人员通过Filter技术,对web服务器管理的所有web资源:例如Jsp, Servlet, 静态图片文件或静态html文件等进行拦截,从而实现一些特殊的功能。例如实现URL级别的权限访问控制、过滤敏感词汇、压缩响应信息等一些高级功能。
  Servlet API中提供了一个Filter接口,开发web应用时,如果编写的Java类实现了这个接口,则把这个java类称之为过滤器Filter。通过Filter技术,开发人员可以实现用户在访问某个目标资源之前,对访问的请求和响应进行拦截。

1.2 如何编写过滤器

1、编写java类实现Filter接口
2、重写doFilter方法
3、设置拦截的url

@WebFilter(filterName ="MyFilter",value="/hello.jsp")
public class MyFilter implements Filter {
    
    

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    
    
        System.out.println("myfilter初始化了。。。。。。。。。");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    
    
        System.out.println("myfilter过滤之前。。。。");
        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("myfilter过滤之后。。。。。");
    }

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

<%--
  Created by IntelliJ IDEA.
  User: Lemosion
  Date: 2020/4/20
  Time: 9:49
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>主页</title>
</head>
<body>
<h2>hello.jsp</h2>
<%
    System.out.println("hello.jsp执行了。。。。。。。。。");
%>
</body>
</html>

1.3 过滤器的配置

1.3.1 注解配置

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

1.3.2 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>

过滤器的拦截匹配路径通常有三种形式:
(1)精确拦截地址匹配 ,比如/index.jsp
(2)后缀拦截地址匹配,比如*.jsp、.html、.jpg
(3)通配符拦截匹配/*,表示拦截所有、注意过滤器不能使用/匹配。

1.4 过滤器链

通常客户端对服务器请求之后,服务器调用Servlet之前会执行一组过滤器(多个过滤器),那么这组过滤器就称为一条过滤器链。
每个过滤器实现某个特定的功能,当第一个Filter的doFilter方法被调用时,web服务器会创建一个代表Filter链的FilterChain对象传递给该方法。在doFilter方法中,开发人员如果调用了FilterChain对象的doFilter方法,则web服务器会检查FilterChain对象中是否还有filter,如果有,则调用第2个filter,如果没有,则调用目标资源。

1.5 过滤器的优先级

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

1.6 过滤器的初始化参数

在过滤器的创建的时候,可以传递初始化参数
第一种:基于注解的

/**
 * 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实现配置:

扫描二维码关注公众号,回复: 12184771 查看本文章
<?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>

1.7 过滤器的优点

可以实现 Web 应用程序中的预处理和后期逻辑处理

<%--
  Created by IntelliJ IDEA.
  User: shiyi
  Date: 2020/3/18
  Time: 21:46
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/loginservlet" method="post">
    <input type="text" name="username" placeholder="请输入用户名"><br/>
    <input type="password" name="password" placeholder="请输入密码"><br/>
    <input type="checkbox" name="aotu">记住我<input type="submit" value="登录">
</form>
</body>
</html>

@WebServlet(name = "LoginServlet",value = "/loginservlet")
public class LoginServlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        request.setCharacterEncoding("utf-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        String auto = request.getParameter("aotu");

        if(username.equals("sanjie")&&password.equals("123")){
    
    
            System.out.println("登录成功");
            request.getSession().setAttribute("username",username);
            //判断是否勾选自动登录
            if(auto!=null){
    
    
                String userinfo= username+"#"+password;
                String base64_userinfo = Base64.getEncoder().encodeToString(userinfo.getBytes());
                Cookie cookie=new Cookie("userinfo",base64_userinfo);
                cookie.setMaxAge(60*60*24*7);
                cookie.setPath("/");
                cookie.setHttpOnly(true);
                response.addCookie(cookie);
                System.out.println("自动登录cookie创建了");
            }
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }



    }

    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 {
    
    
        //1.先判断当前是否已经登录
        HttpServletRequest request= (HttpServletRequest) req;
        HttpServletResponse response= (HttpServletResponse) resp;
        Object username = request.getSession().getAttribute("username");
        if(username!=null){
    
    
            chain.doFilter(req,resp);
        }
        //获取cookie
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
    
    
            for (Cookie cookie:cookies) {
    
    
                if(cookie.getName().equals("userinfo")){
    
    
                    String Base64_userinfo = cookie.getValue();
                    byte[] decode = Base64.getDecoder().decode(Base64_userinfo);
                    String userinfo=new String(decode);
                    System.out.println(userinfo);
                    String[] userinfos = userinfo.split("#");
                    if(userinfos[0].equals("sanjie")&&userinfos[1].equals("123")){
    
    
                        System.out.println("自动登录成功");
                        request.getSession().setAttribute("username",userinfos[0]);
                    }else {
    
    
                        Cookie cookie2=new Cookie("userinfo","");
                        cookie2.setMaxAge(0);
                        cookie2.setPath("/");
                        response.addCookie(cookie2);
                    }
                }
            }
        }
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {
    
    

    }

}

最后给大家推荐一篇博客:
链接: link.

猜你喜欢

转载自blog.csdn.net/weixin_44726976/article/details/105632711
今日推荐