SpringBoot使用过滤器、拦截器和监听器的案例代码(Springboot搭建java项目)

   2023-02-09 学习力0
核心提示:目录SpringBoot使用过滤器、拦截器和监听器一、SpringBoot使用过滤器Spring boot过滤器的使用(两种方式)方式一:方式二:二、SpringBoot使用拦截器三、过滤器和拦截器的执行顺序四、SpringBoot使用监听器1、统计网站最多在线人数监听器的例子2、springboot

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

一、SpringBoot使用过滤器

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

  • 使用spring boot提供的FilterRegistrationBean注册Filter
  • 使用原生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<<<<<<<");
    }
原文地址:https://blog.csdn.net/m0_46616045/article/details/128823964
 
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

  • Springboot + mybatis + React+redux+React-rou
    前言:            后台搭建完以后开始搭建前端,使用create-react-app搭建项目非常方便。           前端主要是如何向后台请求数据,以及如何使用redux管理state,路由的配置.           前端github地址:  https://github.com
    02-09
  • 微信小程序获取openId  SpringBoot
    微信小程序获取openId SpringBoot
    官方文档wx.login:【穿梭门】https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.htmlauth.code2Session【穿梭门】https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html案例小
    02-09
  • 微信小程序 springboot nginx 做图片存储 上传
    微信小程序前端-springboot后端-nginx图片存储前言本人小白一名,这是第一次学习微信小程序,特此做个记录。首先准备nginx做图片存储选择一个地址存放图片#我的地址[root@VM_0_16_centos images]# pwd/home/photos/images[root@VM_0_16_centos images]#然后配
    02-09
  • SpringBoot + nodeJS + zookeeper 搭建微服务示
    总体来说该项目由服务注册 + 服务发现 + 服务代理 + 服务调用四部分组成。使用java客户的开发服务注册组件,它是整个微服务架构中的服务注册表,使用Node.js客户端开发服务发现组件,它用于在服务注册表中根据具体的服务名称获取对应的服务配置。  由项目1
    02-09
  • 微信小程序 部署(后台是springboot项目  前后台分离)
    微信小程序 部署(后台是springboot项目 前后
     微信小程序的部署需要https 和证书:   https 需要反向代理:   这里用 nginx,无论linux,windows 系统都可以安装:1.安装nginx ,这步自己去做;   linux 安装nginx 可以使用宝塔,或自己下载安装;2.配置nginx,把证书放在nginx安装目录conf 文件
    02-09
点击排行