spring-boot整合filter和listener

spring-boot整合filter和listener

github源码:https://github.com/superRabbitMan/spring-bood-filter-listener

filter和listener的整合方式有多种,在没有使用spring-boot之前,习惯使用web.xml配置文件中配置filter和listener。但是在spring-boot中推荐去配置,所有这里使用注解的方式将spring-boot和filter/listener整合。

项目结构

引入依赖

<dependencies>
   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
   </dependency>

   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
   </dependency>
</dependencies>

创建Filter,并添加注解

@WebFilter(filterName = "myFilter", urlPatterns = "/*")
public class MyFilter implements Filter{

    private static final Logger LOG = LoggerFactory.getLogger(MyFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOG.info("MyFilter init method");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        LOG.info("MyFilter doFilter method");
    }

    @Override
    public void destroy() {
        LOG.info("MyFilter destroy method");
    }
}

创建Listener,并添加注解

@WebListener
public class MyListener implements ServletContextListener {

    private static final Logger LOG = LoggerFactory.getLogger(MyListener.class);

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        LOG.info("MyListener contextInitialized method");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        LOG.info("MyListener contextDestroyed method");
    }
}

Application类添加扫描Servlet功能

@Controller
@SpringBootApplication
@ServletComponentScan(basePackages = {"com.example.demo.filter", "com.example.demo.listener"})//添加servlet扫描
public class SpringBoodFilterListenerApplication {

   public static void main(String[] args) {
      SpringApplication.run(SpringBoodFilterListenerApplication.class, args);
   }

   @RequestMapping(value = "/test")
   public void testFilterAndListener() {

   }

}

最后启动项目打开浏览器访问http://localhost:8080/test就可以看到打印的日志

关注微信公众号(程序员小兔)不定期分享技术

发布了222 篇原创文章 · 获赞 189 · 访问量 39万+

猜你喜欢

转载自blog.csdn.net/sinat_32366329/article/details/84575234