SpringBoot实战之6 注册filter和listener

应用场景

在项目中有些特殊的处理需要用到过滤器及监听器,比如spring框架得字符过滤器CahracterEncodingFilter。

code实现

MyFilter.java

@WebFilter(urlPatterns = "/*",description = "自定义filter")
public class MyFilter implements Filter {
    private final Logger _logger = LoggerFactory.getLogger(this.getClass());
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        _logger.info("MyFilter init ...");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        _logger.info("处理 filter 业务 ...");
        filterChain.doFilter(servletRequest,servletResponse);
    }

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

MyListener.java

@WebListener
public class MyListener implements ServletContextListener {
    private final Logger _logger = LoggerFactory.getLogger(this.getClass()) ;
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        _logger.info("contextInitialized");
        _logger.info(servletContextEvent.getServletContext().getContextPath());
    }
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        _logger.info("contextDestroyed");
    }
}

程序入口 SpringBootFilterListenerApplication.java

@SpringBootApplication
@ServletComponentScan({
        "com.hsy.springboot.filter.listener.filter",
        "com.hsy.springboot.filter.listener.listener"
})
public class SpringBootFilterListenerApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootFilterListenerApplication.class,args);
    }
}

结果展示

SpringBoot实战之6 注册filter和listener_第1张图片

项目结构图

SpringBoot实战之6 注册filter和listener_第2张图片

历史文章

SpringBoot实战之入门

springboot实战之文章汇总

springboot实战之读取配置文件

springboot实战之整合jsp模版引擎

springboot实战之整合freemarker模版引擎

springboot实战之注册自定义Servlet

你可能感兴趣的:(springboot实战,filter,listener,springboot)