本文分类:
SpringBoot

在 SpringBootApplication 上使用 @ServletComponentScan 注解后,Servlet、Filter、Listener可以直接通过 @WebServlet、@WebFilter、@WebListener 注解自动注册,无需其他代码,代码类似于:


@SpringBootApplication
@ServletComponentScan
public class DemoApplication {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(DemoApplication.class, args);
    }
}

@WebFilter(urlPatterns = "/*", filterName = "demoFilter")
public class DemoFilter 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

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {}
}

如果不使用 ServletComponentScan,则可以通过定义 ServletRegistrationBean、FilterRegistrationBean、ServletListenerRegistrationBean 注册,代码类似于:

@Bean
public ServletRegistrationBean demoServletRegistration() {
    ServletRegistrationBean registration = new ServletRegistrationBean(new DemoServlet());
    registration.addUrlMappings("/demo");
    return registration;
}
本文来自 [时光记 - 王智超的个人空间](www.hiwzc.com),转载请注明出处。