JavaWeb之Filter&Listener

知识回顾:
JavaWeb之Java基础知识增强
JavaWeb之JDBC
JavaWeb之数据库连接池
JavaWeb之HTML&CSS
JavaWeb之JavaScript
JavaWeb之Bootstrap
JavaWeb之XML
JavaWeb之web服务器软件
JavaWeb之Servlet
JavaWeb之http协议
JavaWeb之会话技术
JavaWeb之JSP&MVC&EL&JSTL

1.Filter: 过滤器

1.1.概念

  • 生活中的过滤器:净水器,空气净化器
  • web中的过滤器:当访问服务器的资源时,过滤器可以将请求拦截下来,完成一些特殊的功能。
  • 过滤器的作用:一般用于完成通用的操作。如:登录验证、统一编码处理、敏感字符过滤…

1.2.快速入门

  • 步骤:
    • 定义一个类,实现接口Filter
    • 复写方法
    • 配置拦截路径
      • web.xml
      • 注解
package com.weeks.filter;

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

@WebFilter("/*")
public class FilterDemo1 implements Filter {
    
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    
    

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    
    
        System.out.println("filter demo1 execute ...");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
    
    

    }
}

1.3.过滤器细节

  • web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <filter>
        <filter-name>demo1</filter-name>
        <filter-class>com.weeks.filter.FilterDemo1</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>demo1</filter-name>
        <!-- 拦截路径 -->
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>
  • 过滤器执行流程
    • 执行过滤器
    • 执行放行后的资源
    • 回来执行过滤器放行代码下边的代码
package com.weeks.filter;

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

@WebFilter("/*")
public class FilterDemo2 implements Filter {
    
    
    public void destroy() {
    
    
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
    
    
        //对request对象的请求消息进行增强
        System.out.println("filterDemo2执行了...");
        //放行
        chain.doFilter(req, resp);
        //对response对象的响应信息进行增强
        System.out.println("filterDemo2我又回来了...");
    }

    public void init(FilterConfig config) throws ServletException {
    
    

    }

}
  • 过滤器生命周期方法
    • init:在服务器启动后,会创建Filter对象,然后调用init方法。只执行一次。用于加载资源
    • doFilter:每一次请求被拦截资源时,会执行。执行多次
    • destroy:在服务器关闭后,Filter对象被销毁。如果服务器是正常关闭,则会执行destroy方法。只执行一次。用于释放资源
package com.weeks.filter;

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

@WebFilter("/*")
public class FilterDemo3 implements Filter {
    
    
    public void destroy() {
    
    
        //在服务器关闭后,Filter对象被销毁。如果服务器是正常关闭,则会执行destroy方法。只执行一次。用于释放资源
        System.out.println("destroy...");
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
    
    
        //每一次请求被拦截资源时,会执行。执行多次
        System.out.println("doFilter...");
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {
    
    
        //在服务器启动后,会创建Filter对象,然后调用init方法。只执行一次。用于加载资源
        System.out.println("init...");
    }

}
  • 过滤器配置详解
    • 拦截路径配置有四种:
拦截路径 作用
具体资源路径: /index.jsp 只有访问index.jsp资源时,过滤器才会被执行
拦截目录: /user/* 访问/user下的所有资源时,过滤器都会被执行
后缀名拦截: *.jsp 访问所有后缀名为jsp资源时,过滤器都会被执行
拦截所有资源:/* 访问所有资源时,过滤器都会被执行
@WebFilter("/index.jsp") //1. 具体资源路径: /index.jsp   只有访问index.jsp资源时,过滤器才会被执行
@WebFilter("/user/*") //2. 拦截目录: /user/*	访问/user下的所有资源时,过滤器都会被执行
@WebFilter("*.jsp")   //3. 后缀名拦截: *.jsp		访问所有后缀名为jsp资源时,过滤器都会被执行
  • 拦截方式配置:资源被访问的方式
    • 注解配置:
      • REQUEST:默认值。浏览器直接请求资源
      • FORWARD:转发访问资源
      • INCLUDE:包含访问资源
      • ERROR:错误跳转资源
      • ASYNC:异步访问资源
    • web.xml配置
      • 设置<dispatcher></dispatcher>标签即可
//浏览器直接请求index.jsp资源时,该过滤器会被执行
@WebFilter(value="/index.jsp",dispatcherTypes = DispatcherType.REQUEST)
//只有转发访问index.jsp时,该过滤器才会被执行
@WebFilter(value="/index.jsp",dispatcherTypes = DispatcherType.FORWARD)

//浏览器直接请求index.jsp或者转发访问index.jsp。该过滤器才会被执行
@WebFilter(value="/*",dispatcherTypes ={
    
     DispatcherType.FORWARD,DispatcherType.REQUEST})
<filter>
        <filter-name>demo1</filter-name>
        <filter-class>com.weeks.filter_.FilterDemo1</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>demo1</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>
  • 过滤器链(配置多个过滤器)
    • 执行顺序:如果有两个过滤器:过滤器1和过滤器2
      • 过滤器1
      • 过滤器2
      • 资源执行
      • 过滤器2
      • 过滤器1
    • 过滤器先后顺序问题:
      • 注解配置:按照类名的字符串比较规则比较,值小的先执行
        * 如: AFilter 和 BFilter,AFilter就先执行了。
      • web.xml配置: <filter-mapping>谁定义在上边,谁先执行

index.jsp

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
  <title>JSP - Hello World</title>
</head>
<body>
<h1><%= "Hello World!" %></h1>
<br/>
<a href="hello-servlet">Hello Servlet</a>
<%
  System.out.println("index.jsp...");
%>
</body>
</html>

Filter1.java

package com.weeks.filter_;

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

@WebFilter("/*")
public class Filter1 implements Filter {
    
    
    public void init(FilterConfig config) throws ServletException {
    
    
    }

    public void destroy() {
    
    
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
    
    
        System.out.println("filter1 executed...");
        chain.doFilter(request, response);
        System.out.println("filter1 come back...");
    }
}

Filter2.java

package com.weeks.filter_;

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

@WebFilter("/*")
public class Filter2 implements Filter {
    
    
    public void init(FilterConfig config) throws ServletException {
    
    
    }

    public void destroy() {
    
    
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
    
    
        System.out.println("filter2 executed...");
        chain.doFilter(request, response);
        System.out.println("filter2 come back...");
    }
}

在这里插入图片描述

1.4.案例

案例代码汇总

1.4.1.案例1_登录验证

  • 需求
    • 访问day17_case案例的资源。验证其是否登录
    • 如果登录了,则直接放行。
    • 如果没有登录,则跳转到登录页面,提示"您尚未登录,请先登录"。

1.4.2.案例2_敏感词汇过滤

  • 需求:
    • 对day17_case案例录入的数据进行敏感词汇过滤
    • 敏感词汇参考《敏感词汇.txt》
    • 如果是敏感词汇,替换为 ***
  • 分析:
    • 对request对象进行增强。增强获取参数相关方法
    • 放行。传递代理对象
  • 增强对象的功能:
    • 设计模式:一些通用的解决固定问题的方式
      • 概念:
        • 真实对象:被代理的对象
        • 代理对象:
        • 代理模式:代理对象代理真实对象,达到增强真实对象功能的目的
      • 实现方式:
        • 静态代理:有一个类文件描述代理模式
        • 动态代理:在内存中形成代理类
          • 实现步骤:
            • 代理对象和真实对象实现相同的接口
            • 代理对象 = Proxy.newProxyInstance();
            • 使用代理对象调用方法
            • 增强方法
          • 增强方式:
            • 增强参数列表
            • 增强返回值类型
            • 增强方法体执行逻辑

SaleComputer.java

package com.weeks.proxy;

public interface SaleComputer {
    
    
    public String sale(double money);

    public void show();
}

Lenovo.java

package com.weeks.proxy;

public class Lenovo implements SaleComputer{
    
    

    @Override
    public String sale(double money) {
    
    
        System.out.println("花了" + money + "元买了一台联想电脑");
        return "联想电脑";
    }

    @Override
    public void show() {
    
    
        System.out.println("展示电脑...");
    }
}

ProxyTest.java

package com.weeks.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyTest {
    
    
    public static void main(String[] args) {
    
    
        //1.创建真实对象
        Lenovo lenovo = new Lenovo();

        //2.动态代理增强lenovo对象
        /*
            三个参数:
                1. 类加载器:真实对象.getClass().getClassLoader()
                2. 接口数组:真实对象.getClass().getInterfaces()
                3. 处理器:new InvocationHandler()
         */
        SaleComputer lenovo_proxy = (SaleComputer) Proxy.newProxyInstance(lenovo.getClass().getClassLoader(), lenovo.getClass().getInterfaces(), new InvocationHandler() {
    
    
            /*
                代理逻辑编写的方法:代理对象调用的所有方法都会触发该方法执行
                    参数:
                        1. proxy:代理对象
                        2. method:代理对象调用的方法,被封装为的对象
                        3. args:代理对象调用的方法时,传递的实际参数
             */
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    
    
//                System.out.println("该方法执行了...");
//                System.out.println(method.getName());
//                System.out.println(args[0]);

                //判断是否是sale方法
                if(method.getName().equals("sale")){
    
    
                    //1.增强参数
                    double money = (double) args[0];
                    money = money * 0.85;
                    //3.增强方法体
                    System.out.println("原厂拿货...");
                    String goods = (String) method.invoke(lenovo, money);
                    System.out.println("包邮到家...");
                    //2.增强返回值
                    goods = goods + "_电脑包";
                    return goods;
                }else{
    
    
                    Object obj = method.invoke(lenovo, args);
                    return obj;
                }

            }
        });

        //3.调用方法
        String goods = lenovo_proxy.sale(8000);
        System.out.println(goods);

//        lenovo_proxy.show();
    }
}

2.Listener:监听器

2.1.概念:web的三大组件之一

  • 事件监听机制
    • 事件 :一件事情
    • 事件源 :事件发生的地方
    • 监听器 :一个对象
    • 注册监听:将事件、事件源、监听器绑定在一起。 当事件源上发生某个事件后,执行监听器代码

2.2.ServletContextListener

  • ServletContextListener:监听ServletContext对象的创建和销毁
  • 方法
    • void contextDestroyed(ServletContextEvent sce) :ServletContext对象被销毁之前会调用该方法
    • void contextInitialized(ServletContextEvent sce) :ServletContext对象创建后会调用该方法
  • 步骤:
    • 定义一个类,实现ServletContextListener接口
    • 复写方法
    • 配置
      • 注解:@WebListener
      • web.xml

在这里插入图片描述

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!-- 配置监听器 -->
    <listener>
    	<listener-class>com.weeks.listener.ClassLoaderListener</listener-class>
    </listener>
    <!-- 指定配置参数 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/classes/applicationContext.xml</param-value>
    </context-param>
</web-app>

applicationContext.xml

<?xml verson="1.0"  encoding="UTF-8"?>
<bean></bean>

ClassLoaderListener.java

package com.weeks.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

@WebListener
public class ClassLoaderListener implements ServletContextListener {
    
    

    /**
     * 监听ServletContext对象创建。ServletContext对象在服务器启动时创建
     *
     * 在服务器启动后被调用
     * @param sce
     */
    @Override
    public void contextInitialized(ServletContextEvent sce) {
    
    
        //加载资源文件
        //1.获取ServletContext对象
        ServletContext servletContext = sce.getServletContext();

        //2.加载资源文件
        String configConfigLocation = servletContext.getInitParameter("configConfigLocation");

        //3.获取真实路径
        String realPath = servletContext.getRealPath(configConfigLocation);

        //4.加载进内存
        try {
    
    
            FileInputStream fis = new FileInputStream(realPath);
            System.out.println(fis);
        } catch (FileNotFoundException e) {
    
    
            e.printStackTrace();
        }
        System.out.println("servletContext被创建。。。");
    }

    /**
     * 在服务器正常关闭后ServletContext对象被销毁,当服务器正常关闭后该方法被调用
     * @param sce
     */
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    
    
        System.out.println("servletContext被销毁。。。");
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_42284219/article/details/120707987
今日推荐