【JavaWeb】Filter

文章目录

  • 1.Filter过滤器
  • 2.Filter的初体验
  • 3.Filter的生命周期
  • 4.FilterConfig类
  • 5.FilterChain过滤器链
  • 6.Filter的拦截路径

1.Filter过滤器

(1).概念及作用

  • Filter过滤器是JavaWeb的三大组件之一
  • 三大组件分别是:Servlet程序,Listener监听器,Filter过滤器
  • Filter过滤器是JavaEE的规范,也就是接口
  • 作用:拦截请求,过滤响应
    拦截请求的常见应用场景有:权限检查,日记操做,事物管理等

2.Filter的初体验

  • 根据我们之前学过的内容,我们知道,用户登录之后会把用户登录的信息保存到Session域中,所以要检查用户是否登录,可以判断Session中是否包含用户登录的信息即可

Filter过滤器的使用步骤:
(1).编写一个类去实现Filter接口
(2).实现过滤方法doFilter()
(3).到web.xml中去配置Filter的拦截路径

【JavaWeb】Filter_第1张图片

我们部署工程的时候,在浏览器输入我们要访问的资源路径,之后的整个过程就如上图所示
有权限,就会访问到我们要访问的资源

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;

        HttpSession  session = httpServletRequest.getSession();

        Object user = session.getAttribute("user");

        //如果为null,说明还没登录
        if(user == null){
            servletRequest.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse);
            return;
        }else {
            //让程序继续往下访问用户的目标资源
            filterChain.doFilter(servletRequest,servletResponse);
        }

    }
<!--filter标签用于配置一个Filter过滤器-->
    <filter>
        <!--给filter起一个别名-->
        <filter-name>AdminFilter</filter-name>
        <!--配置filter的全类名-->
        <filter-class>filter.AdminFilter</filter-class>
    </filter>
     <!--filter-mapping配置Filter过滤器的拦截路径-->
    <filter-mapping>
        <!--filter-name表示当前的拦截路径给哪个filter使用-->
        <filter-name>AdminFilter</filter-name>
        <!--url-pattern配置拦截路径
        / 表示请求地址为:http://ip:port/工程路径/ 映射到IDEA的web目录
        /admin/* 表示请求地址为:http://ip:port/工程路径/admin/*
        -->
        /admin/*
    

没有权限就会返回到下图界面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
这是登陆页面,login.jsp页面
</body>
</html>

注意:
利用jsp也可以起到拦截的作用,但是这种方法有一定的局限性,servlet程序只能写在jsp(只能拦截访问当前jsp资源),所以使用的是Filter用于拦截路径.

  • 完整的用户登录和权限检查
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=UTF");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if("wyl168".equals(username) && "123456".equals(password)){
            req.getSession().setAttribute("user",username);
            resp.getWriter().write("登陆 成功! ! !");
        }else{
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }
    }
}
<servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>filter.servlet.LoginServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/loginServlet</url-pattern>
    </servlet-mapping>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
这是登陆页面,login.jsp页面</br>
<form action="http://localhost:8080/15_filter/loginServlet" method="get">
    用户名: <input type="text" name="username"/></br>
    密  码: <input type="password" name="password"/></br>
    <input type="submit" />
</form>
</body>
</html>

说明:当用户提交完正确的用户名和密码,点击提交,就会执行Servlet程序,执行Servlet程序就会保存用户信息到Session域中,此时再次在浏览器输入要访问的资源路径,会执行Filter程序,执行Filter程序就会在Session中找到用户信息,所以就能访问到相应的资源了.

3.Filter的生命周期

Filter的生命周期包含的方法:

(1).构造器方法

public AdminFilter(){

        System.out.println("1.Filter构造器方法AdminFilter()");
    }

(2).init初始化方法

 public void init(FilterConfig filterConfig) throws ServletException {

        System.out.println("2.Filter的init(FilterConfig filterConfig)初始化");

    }

第(1)(2)步在web工程启动的时候执行(Filter已经创建)

(3).doFilter过滤方法

 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        System.out.println("3.Filter的doFilter()过滤方法");

        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;

        HttpSession  session = httpServletRequest.getSession();

        Object user = session.getAttribute("user");

        //如果为null,说明还没登录
        if(user == null){
            servletRequest.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse);
            return;
        }else {
            //让程序继续往下访问用户的目标资源
            filterChain.doFilter(servletRequest,servletResponse);
        }

    }

第(3)步每次拦截到请求,就会执行

(4).destroy销毁

 public void destroy() {
        System.out.println("4.Filter的destroy()销毁方法");
    }

第(4)步,停止web工程的时候,就会执行(停止web工程,也会销毁Filter过滤器)

4.FilterConfig类

基本介绍:

(1)见名知意,它是Filter过滤器的配置文件类
(2)Tomcat每次创建Filter的时候,也会同时创建一个FilterConfig类,这里包含了Filter配置文件的配置信息

作用:获取Filter过滤器的配置内容(filter-name,init-param,ServletContext对象)

 public void init(FilterConfig filterConfig) throws ServletException {

        System.out.println("2.Filter的init(FilterConfig filterConfig)初始化");

        //1.获取Filter的名称filter-name
        System.out.println("filter-name的值是: " + filterConfig.getFilterName());
        //2.获取Filter的初始化参数init-param
        System.out.println("初始化参数username的值是: " + filterConfig.getInitParameter("username"));
        System.out.println("初始化参数url的值是: " + filterConfig.getInitParameter("url"));
        //3.获取ServletContext对象
        System.out.println(filterConfig.getServletContext());
    }

5.FilterChain过滤器链

FilterChain过滤器链(多个过滤器在一起工作)

【JavaWeb】Filter_第2张图片

  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        System.out.println("Filter1 前置代码");

        filterChain.doFilter(servletRequest,servletResponse);

        System.out.println("Filter1 后置代码");

    }
 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {


        System.out.println("Filter2 前置代码");

        filterChain.doFilter(servletRequest,servletResponse);

        System.out.println("Filter2 后置代码");

    }
<filter>
        <filter-name>Filter1</filter-name>
        <filter-class>filter.Filter1</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>Filter1</filter-name>
        <url-pattern>/target.jsp</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>Filter2</filter-name>
        <filter-class>filter.Filter2</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>Filter2</filter-name>
        <url-pattern>/target.jsp</url-pattern>
    </filter-mapping>

【JavaWeb】Filter_第3张图片
如果是下面这种情况:

  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {


        System.out.println("Filter2 前置代码");

  //      filterChain.doFilter(servletRequest,servletResponse);

  //      System.out.println("Filter2 后置代码");

    }

那么最后的结果是:

【JavaWeb】Filter_第4张图片
如果是这种情况:

 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        System.out.println("Filter1 前置代码");

       // filterChain.doFilter(servletRequest,servletResponse);

       // System.out.println("Filter1 后置代码");

    }

那么结果就是:

在这里插入图片描述

注意:Filter1和Filter2的执行顺序,是根据web.xml里面的配置顺序有关

多个Filter过滤器执行的特点:

  • 所有filter目标资源默认都执行在同一个线程
 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        System.out.println("Filter1 前置代码");

        System.out.println("Filter1 线程: " + Thread.currentThread().getName());

        filterChain.doFilter(servletRequest,servletResponse);

        System.out.println("Filter1 线程: " + Thread.currentThread().getName());

        System.out.println("Filter1 后置代码");

    }
 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {


        System.out.println("Filter2 前置代码");

        System.out.println("Filter2 线程: " + Thread.currentThread().getName());

        filterChain.doFilter(servletRequest,servletResponse);

        System.out.println("Filter2 线程: " + Thread.currentThread().getName());

        System.out.println("Filter2 后置代码");

    }
<body>
<%
    System.out.println("target.jsp页面执行了");

    System.out.println("target.jsp 线程: " + Thread.currentThread().getName());
%>
</body>
  • 多个Filter共同执行的时候,它们都使用同一个Request对象
 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        System.out.println("Filter1 前置代码");

        System.out.println("Filter1 线程: " + Thread.currentThread().getName());

        servletRequest.setAttribute("key1","value1");

        filterChain.doFilter(servletRequest,servletResponse);

        System.out.println("Filter1 线程: " + Thread.currentThread().getName());

        System.out.println("Filter1 后置代码");

    }
 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        
        System.out.println("Filter2 前置代码");

        System.out.println("Filter2 线程: " + Thread.currentThread().getName());

        System.out.println("Filter2取Filter1中保存的数据: " + servletRequest.getAttribute("key1"));

        filterChain.doFilter(servletRequest,servletResponse);

        System.out.println("Filter2 线程: " + Thread.currentThread().getName());

        System.out.println("Filter2 后置代码");

    }

在这里插入图片描述

6.Filter的拦截路径

  • 精确匹配
 <url-pattern>/target.jsp</url-pattern>

以上配置的路径,表示请求地址必须为:http://ip:port/工程路径/target.jsp

  • 目录匹配
 <url-pattern>/admin/</url-pattern>

以上配置的路径,表示请求地址必须为:http://ip:port/工程路径/admin/*

  • 后缀名匹配
<url-pattern>*.html</url-pattern>

以上配置的路径,表示请求地址必须以.html结尾才会拦截到

这种匹配方式,后缀名可以自定义,Filter过滤器只关心请求的地址是否匹配,不关心请求的资源是否存在

你可能感兴趣的:(Java,Web,servlet,java,Filter,web)