文章目录

  • 过滤器与监听器
  • 1.过滤器
  • 1.1 为什么需要过滤器
  • 1.2 使用步骤
  • 2.监听器


过滤器与监听器

1.过滤器

在很多web项目中,都会用到过滤器,例如参数过滤、防止SQL注入、防止页面攻击、参数矫正、Token验证、Session验证等

1.1 为什么需要过滤器

在Web开发中,往往有这样的需求:在所有接口中去除用户输入的非法字符,以防止业务异常,如果需要处理这个问题,会有很多方法

  • 在前端参数传入的时候进行校验,先过滤非法字符
  • 后端接收到前端没有过滤的数据,然后过滤非法字符
  • 利用过滤器处理项目中所有的非法字符

如果利用前两种方法,就需要在每个前端页面或者后端进行处理,会在项目中存在很多重复的代码;但是如果利用过滤器,那只需要在每个接口进行过滤处理,减少了冗余代码。

1.2 使用步骤

  1. 实现Filter抽象类
  2. 重写类方法
  3. 在Spring Boot入口中添加@ServletComponentScan,注册过滤器

编写过滤器代码

package com.example.demo;

import org.springframework.core.annotation.Order;

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

@Order(1)
@WebFilter(filterName = "Filterdemo",urlPatterns = "/*")
public class Filterdemo 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("该页面经过了过滤器");
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}

然后在启动类中加入注解@ServletComponentScan,启动服务

因为在过滤器路由设置中为/*,所以不论访问任何页面都会经过过滤器,控制台都会有输出

spring boot 过滤器作用 springboot中的过滤器_监听器

2.监听器

监听器是用于监听Web应用中某些对象或者信息的创建、销毁、增加、修改、删除等动作,然后作出相应的响应处理。当对象的状态发生变化时,服务器自动调用监听器的方法。

监听器常用于统计在线人数、系统加载时的信息初始化等等

servlet中的监听器分为以下三种类型:

  1. 监听ServletContext、Request、Session作用域的创建和销毁
  • ServletContextListener:监听ServletContext
  • HttpSessionListener:监听新的Session创建事件
  • ServletRequestListener:监听ServletRequest的初始化和销毁
  1. 监听ServletContext、Request、Session作用域中的属性变化(增加、修改、删除)
    对应的AttributeListener监听参数的变化
  2. 监听HttpSession中的对象状态的改变(被绑定、解除绑定、钝化、活化)
  • HttpSessionBindingListener:监听HttpSession,并绑定及解除绑定
  • HttpSessionActivationListener:监听钝化和活动的HttpSession状态的改变

来看看ServletContext监听器的例子

package com.example.demo;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

@WebListener
public class listenerdemo implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("ServletContext 初始化");
        System.out.println(sce.getServletContext().getServerInfo());
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("ServletContext 销毁");
    }
}

spring boot 过滤器作用 springboot中的过滤器_监听器_02

spring boot 过滤器作用 springboot中的过滤器_后端_03