首页 > 其他分享 >SpringBoot 过滤器、监听器、拦截器

SpringBoot 过滤器、监听器、拦截器

时间:2022-10-20 17:13:41浏览次数:54  
标签:拦截器 SpringBoot void 监听 过滤器 监听器 Override public

过滤器

过滤器Filter,是Servlet的的一个实用技术了。可通过过滤器,对请求进行拦截,比如读取session判断用户是否登录、判断访问的请求URL是否有访问权限(黑白名单)等。主要还是可对请求进行预处理。接下来介绍下,在springboot如何实现过滤器功能。

1.利用WebFilter注解配置

  1. 编写Filter类:
  2. 然后在启动类加入@ServletComponentScan注解即可。
//注册器名称为customFilter,拦截的url为所有
@WebFilter(filterName="customFilter",urlPatterns={"/*"})
@Slf4j
public class CustomFilter implements Filter{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("filter 初始化");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        log.info("doFilter 请求处理");
        //对request、response进行一些预处理
        // 比如设置请求编码
        // request.setCharacterEncoding("UTF-8");
        // response.setCharacterEncoding("UTF-8");
        //TODO 进行业务逻辑
        //链路 直接传给下一个过滤器
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        log.info("filter 销毁");
    }
}

2.FilterRegistrationBean方式

  1. 修改Filter类:@WebFilter(filterName="customFilter",urlPatterns={"/*"}) 这个注解不要了
  2. 设置FilterRegistrationBean
	@Bean
    public FilterRegistrationBean  filterRegistrationBean() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        //当过滤器有注入其他bean类时,可直接通过@bean的方式进行实体类过滤器,这样不可自动注入过滤器使用的其他bean类。
        //当然,若无其他bean需要获取时,可直接new CustomFilter(),也可使用getBean的方式。
        registration.setFilter(customFilter());
        //过滤器名称
        registration.setName("customFilter");
        //拦截路径
        registration.addUrlPatterns("/*");
        //设置顺序
        registration.setOrder(10);
        return registration;
    }

    @Bean
    public Filter customFilter() {
        return new CustomFilter();
    }

小结:FilterRegistrationBean注册多个时,就注册多个FilterRegistrationBean即可

想比WebFilter注解的优点是 可以设置filter链的执行顺序

监听器

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

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

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

监听ServletContext、Request、Session作用域的创建和销毁

  • ServletContextListener:监听ServletContext
  • HttpSessionListener:监听新的Session创建事件
  • ServletRequestListener:监听ServletRequest的初始化和销毁

监听ServletContext、Request、Session作用域中的属性变化(增加、修改、删除)对应的AttributeListener监听参数的变化

监听HttpSession中的对象状态的改变(被绑定、解除绑定、钝化、活化)

  • HttpSessionBindingListener:监听HttpSession,并绑定及解除绑定
  • HttpSessionActivationListener:监听钝化和活动的HttpSession状态的改变

1.利用WebListener注解配置

  1. 创建一个ServletRequest监听器(其他监听器类似创建)
  2. 在启动类中加入@ServletComponentScan进行自动注册即可。
@WebListener
@Slf4j
public class Customlister implements ServletRequestListener{

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        log.info("监听器:销毁");
    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        log.info("监听器:初始化");
    }

}

2.ServletListenerRegistrationBean方式

  1. WebListener这个注解不要了
  2. 设置ServletListenerRegistrationBean
@Bean
public ServletListenerRegistrationBean servletListenerRegistrationBean(){
    ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean();
    bean.setListener(new HttpSessionListener() {
        @Override
        public void sessionCreated(HttpSessionEvent se) {
            HttpSessionListener.super.sessionCreated(se);
        }

        @Override
        public void sessionDestroyed(HttpSessionEvent se) {
            HttpSessionListener.super.sessionDestroyed(se);
        }
    });
    return bean;
}

拦截器

以上的过滤器、监听器都属于Servlet的api,我们在开发中处理利用以上的进行过滤web请求时,还可以使用Spring提供的拦截器(HandlerInterceptor)进行更加精细的控制。

编写自定义拦截器类

@Slf4j
public class CustomHandlerInterceptor implements HandlerInterceptor{

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        log.info("preHandle:请求前调用");
        //返回 false 则请求中断
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        log.info("postHandle:请求后调用");

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        log.info("afterCompletion:请求调用完成后回调方法,即在视图渲染完成后回调");

    }

}

通过继承WebMvcConfigurerAdapter注册拦截器

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter{
    
    @Override
     public void addInterceptors(InterceptorRegistry registry) {
         //注册拦截器 拦截规则
        //多个拦截器时 以此添加 执行顺序按添加顺序
        registry.addInterceptor(getHandlerInterceptor()).addPathPatterns("/*");
     }
    
    @Bean
    public static HandlerInterceptor getHandlerInterceptor() {
        return new CustomHandlerInterceptor();
    }
}

标签:拦截器,SpringBoot,void,监听,过滤器,监听器,Override,public
From: https://www.cnblogs.com/Acaak/p/16810517.html

相关文章

  • SpringBoot2 集成xJar插件 动态解密jar包,避免源码泄露或反编译
    一、集成1.官方介绍地址手动加密:https://github.com/core-lib/xjarmaven插件集成:https://github.com/core-lib/xjar-maven-plugin2.添加仓库和插件第一种(不推荐使用)......
  • React + Springboot + Quartz,从0实现Excel报表自动化
    一、项目背景企业日常工作中需要制作大量的报表,比如商品的销量、销售额、库存详情、员工打卡信息、保险报销、办公用品采购、差旅报销、项目进度等等,都需要制作统计图表以......
  • springboot +redis+token
    1、pom.xml<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId......
  • 前后端分离数组传递问题(springboot)(Vue)
    前后端分离数组传递问题昨天与前端对接时,我后端需要List的数据,就是找不到参数,我看了前端代码也没发现问题。绝问题解决过程我的后端代码:@Transactional@PostM......
  • 断点SpringBoot-断点续传-大文件断点上传
    ​ 一、功能性需求与非功能性需求要求操作便利,一次选择多个文件和文件夹进行上传;支持PC端全平台操作系统,Windows,Linux,Mac支持文件和文件夹的批量下载,断点续传。刷......
  • 1、初始SpringBoot
    什么是springSpring是一个开源框架,2003年兴起的一个轻量级的java开发框架,作者:RodJohnson.Spring是为了解决企业级应用开发的复杂性而创建的,简化开发       ......
  • SpringBoot项目部署
    我们要想在linux系统上运行这个项目,就要保证他运行所用的端口没有被占用,不然运行就会报错查看端口使用情况netstat-anp|grep9999可以看到这个端口被占用了(没被占用的......
  • 手写自定义springboot-starter,感受框架的魅力和原理
    一、前言Springboot的自动配置原理,面试中经常问到,一直看也记不住,不如手写一个starter,加深一下记忆。看了之后发现大部分的starter都是这个原理,实践才会记忆深刻。核心思......
  • SpringBoot+MybatisPlus--使用
    1、在entity包下面创建数据实体类,添加注解@Data,如果和数据库名字不一样的话,还需要+@TableField注解。字段名字不一样也需要添加此注解@TableName(value="user")publi......
  • SpringBoot对接口请求参数(@RequestBody 和 @ Request Param)进行解密过滤
      /***@Description:拦截所有请求过滤器,并将请求类型是HttpServletRequest类型的请求替换为自定义*/@javax.servlet.annotation.WebFilter(filterName="Web......