基于springboot搭建java项目(二十三)——springboot使用过滤器拦截器和监听器(代码片段)

dreamer_0423 dreamer_0423     2023-03-04     713

关键词:

SpringBoot使用过滤器、拦截器和监听器

一、SpringBoot使用过滤器

Spring boot过滤器的使用(两种方式)

  1. 使用spring boot提供的FilterRegistrationBean注册Filter
  2. 使用原生servlet注解定义Filter

两种方式的本质都是一样的,都是去FilterRegistrationBean注册自定义Filter

方式一:

第一步:先定义Filter。

import javax.servlet.*;
import java.io.IOException;
public class MyFilter implements Filter 
    @Override
    public void init(FilterConfig filterConfig) throws ServletException 
    
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException 
        // do something 处理request 或response
        System.out.println("filter1");
        // 调用filter链中的下一个filter
        filterChain.doFilter(servletRequest,servletResponse);
    
    @Override
    public void destroy() 
    

第二步:注册自定义Filter

@Configuration
public class FilterConfig 
    @Bean
    public FilterRegistrationBean registrationBean() 
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new MyFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.setOrder(1);//定义过滤器的执行先后顺序  值越小越先执行 不影响Bean的加载顺序
        return filterRegistrationBean;
    

方式二:

// 注入spring容器
@Order(1)//定义过滤器的执行先后顺序  值越小越先执行 不影响Bean的加载顺序
@Component
// 定义filterName 和过滤的url
@WebFilter(filterName = "my2Filter" ,urlPatterns = "/*")
public class My2Filter 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("filter2");
    
    @Override
    public void destroy() 
    

二、SpringBoot使用拦截器

第一步:定义拦截器

public class MyInterceptor implements HandlerInterceptor 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception 
        System.out.println("preHandle");
        return true;
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception 
        System.out.println("postHandle");
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception 
        System.out.println("afterCompletion");
    

第二步:配置拦截器

@Configuration
public class InterceptorConfig implements WebMvcConfigurer 
    @Override
    public void addInterceptors(InterceptorRegistry registry) 
        registry.addInterceptor(new MyInterceptor());
    

三、过滤器和拦截器的执行顺序

过滤器的执行顺序是安装@Order注解中的值,或者是setOrder()中值的进行执行顺序排序的,值越小就越靠前。

拦截器则是先声明的拦截器 preHandle() 方法先执行,而postHandle()方法反而会后执行。也即是:postHandle() 方法被调用的顺序跟 preHandle() 居然是相反的。如果实际开发中严格要求执行顺序,那就需要特别注意这一点。

四、SpringBoot使用监听器

1、统计网站最多在线人数监听器的例子

/**
 * 上下文监听器,在服务器启动时初始化onLineCount和maxOnLineCount两个变量,
 * 并将其置于服务器上下文(ServletContext)中,其初始值都是0。
 */
@WebListener
public class InitListener implements ServletContextListener 
    public void contextDestroyed(ServletContextEvent evt) 
    
    public void contextInitialized(ServletContextEvent evt) 
        evt.getServletContext().setAttribute("onLineCount", 0);
        evt.getServletContext().setAttribute("maxOnLineCount", 0);
    


/**
 * 会话监听器,在用户会话创建和销毁的时候根据情况修改onLineCount和maxOnLineCount的值。
 */
@WebListener
public class MaxCountListener implements HttpSessionListener 
    public void sessionCreated(HttpSessionEvent event) 
        ServletContext ctx = event.getSession().getServletContext();
        int count = Integer.parseInt(ctx.getAttribute("onLineCount").toString());
        count++;
        ctx.setAttribute("onLineCount", count);
        int maxOnLineCount = Integer.parseInt(ctx.getAttribute("maxOnLineCount").toString());
        if (count > maxOnLineCount) 
            ctx.setAttribute("maxOnLineCount", count);
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            ctx.setAttribute("date", df.format(new Date()));
        
    
    public void sessionDestroyed(HttpSessionEvent event) 
        ServletContext app = event.getSession().getServletContext();
        int count = Integer.parseInt(app.getAttribute("onLineCount").toString());
        count--;
        app.setAttribute("onLineCount", count);
    


新建一个servlet处理

@WebServlet(name = "SessionServlet",value = "/sessionCount")
public class SessionServlet extends HttpServlet 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException 
        resp.setContentType("text/html");
        //获取上下文对象
        ServletContext servletContext = this.getServletContext();
        Integer onLineCount = (Integer) servletContext.getAttribute("onLineCount");
        System.out.println("invoke doGet");
        PrintWriter out = resp.getWriter();
        out.println("<html><body>");
        out.println("<h1>" + onLineCount + "</h1>");
        out.println("</body></html>");
    


2、springboot监听器的使用(以实现异步Event监听为例子)

定义事件类 Event

创建一个类,继承ApplicationEvent,并重写构造函数。ApplicationEvent是Spring提供的所有应用程序事件扩展类。

public class Event extends ApplicationEvent 
    private static final long serialVersionUID = 1L;
    private String msg ;
    private static final Logger logger=LoggerFactory.getLogger(Event.class);
    public Event(String msg) 
        super(msg);
        this.msg = msg;
        logger.info("add event success! message: ", msg);
    
    public String getMsg() 
        return msg;
    
    public void setMsg(String msg) 
        this.msg = msg;
    

创建一个用于监听指定事件的类,需要实现ApplicationListener接口,说明它是一个应用程序事件的监听类。注意这里需要加上@Component注解,将其注入Spring容器中。

@Component
public class MyListener implements ApplicationListener<Event>
    private static final Logger logger= LoggerFactory.getLogger(MyListener.class);
    @Override
    public void onApplicationEvent(Event event) 
        logger.info("listener get event,sleep 2 second...");
        try 
            Thread.sleep(2000);
         catch (InterruptedException e) 
            e.printStackTrace();
        
        logger.info("event msg is:",event.getMsg());
    

事件发布
事件发布很简单,只需要使用Spring 提供的ApplicationEventPublisher来发布自定义事件

@Autowired 注入ApplicationEventPublisher

 @RequestMapping("/notice/msg")
    public void notice(@PathVariable String msg)
        logger.info("begin>>>>>");
        applicationEventPublisher.publishEvent(new Event(msg));
        logger.info("end<<<<<<<");
    

java网络商城项目springboot+springcloud+vue网络商城(ssm前后端分离项目)二十三(项目打包和部署)(代码片段)

Java网络商城项目SpringBoot+SpringCloud+Vue网络商城(SSM前后端分离项目)二十三(项目打包和部署)选择要打包的服务1、在这里我们打包商品微服务选择当前项目对应的依赖项目(1)在pom.xml当中引入对... 查看详情

springboot入门二十三,整合redis

  项目基本配置参考文章SpringBoot入门一,使用myEclipse新建一个SpringBoot项目,使用MyEclipse新建一个SpringBoot项目即可,此示例springboot升级为2.2.1版本。1.pom.xml添加Redis支持<!--5.引入redis依赖--><dependency><groupId>org.springframe... 查看详情

springboot和vue集成视频播放组件——基于springboot和vue的后台管理系统项目系列博客(二十二)(代码片段)

系列文章目录系统功能演示——基于SpringBoot和Vue的后台管理系统项目系列博客(一)Vue2安装并集成ElementUI——基于SpringBoot和Vue的后台管理系统项目系列博客(二)Vue2前端主体框架搭建——基于SpringBoot和Vue的后... 查看详情

springboot+springcloud实现权限管理系统后端篇(二十三):配置中心(configbus)

在线演示演示地址:http://139.196.87.48:9002/kitty用户名:admin密码:admin技术背景如今微服务架构盛行,在分布式系统中,项目日益庞大,子项目日益增多,每个项目都散落着各种配置文件,且随着服务的增加而不断增多。此时,往... 查看详情

前端(二十三)——vue环境搭建(代码片段)

一.Vue环境搭建1.安装node去官网下载node安装包傻瓜式安装万一安装后终端没有node环境,要进行node环境变量的配置(C:ProgramFilesodejs)可以通过node提供的npm包管理器安装vue脚手架通过npm安装淘宝镜像cnpm,将nmp指令都修改为cnpm指令(npmi... 查看详情

springboot系列(二十三):如何实现excel文件导入?这你得会|超级详细,建议收藏(代码片段)

👨‍🎓作者:bug菌🎉简介:在CSDN、掘金等社区优质创作者,全网合计6w粉+,对一切技术都感兴趣,重心偏java方向,目前运营公众号[猿圈奇妙屋],欢迎小伙伴们的加入,一起秃头。... 查看详情

springboot系列(二十三):如何实现excel文件导入?这你得会|超级详细,建议收藏(代码片段)

👨‍🎓作者:bug菌🎉简介:在CSDN、掘金等社区优质创作者,全网合计6w粉+,对一切技术都感兴趣,重心偏java方向,目前运营公众号[猿圈奇妙屋],欢迎小伙伴们的加入,一起秃头。... 查看详情

java网络商城项目springboot+springcloud+vue网络商城(ssm前后端分离项目)二十一(购物车)(代码片段)

Java网络商城项目SpringBoot+SpringCloud+Vue网络商城(SSM前后端分离项目)十九(购物车)1.搭建购物车服务业务分析在需求描述中,不管用户是否登录,都需要实现加入购物车功能,那么已登录和未登... 查看详情

基于dolphindb搭建微服务的springboot项目

SpringBoot是一个基于Spring的快速开发框架,也是SpringCloud构建微服务分布式系统的基础设施。本文主要介绍如何通过SpringBoot快速搭建DolphinDB微服务,并且基于Mybatis操作DolphinDB数据库。本项目实现了物联网中的一个典型场景:终端... 查看详情

重学java基础第二十三课:java基础注释

    查看详情

基于springboot+vue三||项目环境搭建-nacos

1、注册中心Nacos该项目由SpringCloud+Eureka切换为SpringCloud+Nacos,使用Nacos作为服务注册中心。 2、基于Docker安装Nacos2.1、安装docker,安装教程参照作者文章《Docker》分类。 2.2、启动镜像dockerpullnacos/nacos-serverdockerrun--envMODE=standa... 查看详情

java练习题java程序的输出|第二十三套(继承)

查看详情

微服务中基于springboot的maven分布式项目框架的搭建

项目介绍这里搭建的是基于maven的分布式工程,因为在一个项目中,多个微服务是属于同一个工程,只不过是提供不同的服务而已,再加上IDEA是默认一个窗口打开一个项目工程(这点和eclipse不同),如果项目大,不用maven聚合工... 查看详情

react学习案例二十三

React学习案例二十三<!--functionActionLink()functionhandleClick(e)e.preventDefault();console.log('链接被点击');return(<ahref="#"onClick=handleClick>点我</a>);--><!--funct 查看详情

(十三)atp应用测试平台——springboot集成kafka案例实战(代码片段)

...:①削峰填谷②异步解耦。本节我们主要介绍一下如何在springboot项目中集成kafka消息中间键,实现简单的数据分发以及消费的案例。正文kafka集群搭建快速搭建一个kafka集群,我们这里以docker 查看详情

springboot快速搭建基于restful风格的微服务

使用springboot快速搭建基于 Restful风格的微服务,无spring配置文件,纯java工程,可以快速发布,调试项目1.创建一个maven工程2.导入如下配置<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-in 查看详情

使用idea快速搭建基于maven的springboot项目(代码片段)

迫于好久没写博客心慌慌,随便写个简单版的笔记便于查阅。新建项目新建项目然后起名继续nextnetxfinish。首先附上demo的项目结构图配置pom.xml<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://w... 查看详情

api接口自动化测试框架搭建(二十三)-框架主入口main.py设计&测试报告调用和生成(代码片段)

(二十三)-框架主入口main.py设计&测试报告调用和生成1测试目的2测试需求3需求分析4详细设计4.1新建框架主入口脚本4.2设计main.py脚本5调用测试报告主函数main.py源码6运行效果7目前框架结构1测试目的组织运行所有的测试用例... 查看详情