spring boot 入门(八)filter、servlet、listener

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq447995687/article/details/79979968

spring boot 入门(八)servlet、filter、listener

1. filter

spring boot有两种方式来配置filter

1.1 Servlet 3.0新特性,以注解方式配置Filter,需在启动类上加入@ServletComponentScan注解

@WebFilter
public class MyAnnotationFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init MyAnnotationFilter...");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        chain.doFilter(request, response);
        System.out.println("do MyAnnotationFilter...");
    }

    @Override
    public void destroy() {
        System.out.println("destroy MyAnnotationFilter...");
    }

}

1.2 利用springboot的FilterRegistrationBean手动注册

  • 实现filter类
@Component
public class MyBeanFilter implements Filter{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init MyBeanFilter...");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        chain.doFilter(request, response);
        System.out.println("do MyBeanFilter...");
    }

    @Override
    public void destroy() {
        System.out.println("destroy MyBeanFilter...");
    }

}
  • 注册filter实现
@Configuration
public class FilterConfiguration {

    @Bean
    public FilterRegistrationBean myFilterRegistrationBean(MyBeanFilter myBeanFilter){
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(myBeanFilter);
        registration.setUrlPatterns(Arrays.asList("/index"));
        return registration;
    }
}

启动主类

@SpringBootApplication
@ServletComponentScan
public class SimpleApplicationStarter {

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

2. servlet

servlet与filter的配置类似也有两种配法

  • 使用@WebServlet注解和filter一样需在启动类加上@ServletComponentScan注解
  • 利用ServletRegistrationBean 手动注入

    由于与filter代码类似在此不贴详细代码,我们以druid的监控页面为例子,手动注入servlet

    @Bean
    public ServletRegistrationBean druidServlet() {
        return new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
    }

当springboot应用启动过后,通过(默认8080端口)localhost:8080/druid/index.html就能访问到druid的监控页面。

3. listener

与servlet、filter的配置类似
- 使用@WebListener注解和servlet、filter一样需在启动类加上@ServletComponentScan注解
- 利用ServletListenerRegistrationBean手动注入

ps:通过手动注入和注解实现使得springboot可以兼容新老系统
示例代码:https://github.com/Json-Lin/spring-boot-practice/tree/master/spring-boot-practice-filter
end

阅读更多

没有更多推荐了,返回首页