广告
返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBoot使用过滤器、拦截器和监听器的案例代码(Springboot搭建java项目)
  • 370
分享到

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

Python 官方文档:入门教程 => 点击学习

摘要

目录SpringBoot使用过滤器、拦截器和监听器一、springBoot使用过滤器Spring Boot过滤器的使用(两种方式)方式一:方式二:二、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("
@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);
    }
}

@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<<<<<<<");
    }

到此这篇关于SpringBoot使用过滤器、拦截器和监听器(Springboot搭建java项目)的文章就介绍到这了,更多相关SpringBoot使用过滤器、拦截器和监听器内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

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

本文链接: https://www.lsjlt.com/news/193954.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作