SpringBoot 集成原生 Servlet、Filter、Listener

注解方式集成 Servlet、Filter、Listener

启动类添加 @ServletComponentScan 注解
@SpringBootApplication
@ServletComponentScan
public class BlogApplication {

    public static void main(String[] args) {
        SpringApplication.run(BlogApplication.class);
    }
}
创建 Servlet (类上添加 @WebServlet 注解)
@Slf4j
@WebServlet(urlPatterns = {"/native_servlet"})
public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String message = "MyServlet doGet";

        log.info(message);

        response.setContentType("text/html");

        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h1>" + message + "</h1>");
        out.println("</body></html>");
    }
}
创建 Filter (类上添加 @WebFilter 注解)
@Slf4j
@WebFilter
public class MyFilter implements Filter {

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

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info("MyFilter doFilter");
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        log.info("MyFilter destroy");
    }
}
创建 Listener(类上添加 @WebListener 注解)
@Slf4j
@WebListener
public class MyListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        log.info("MyListener contextInitialized");
        ServletContextListener.super.contextInitialized(sce);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        log.info("MyListener contextDestroyed");
        ServletContextListener.super.contextDestroyed(sce);
    }
}
启动项目,访问链接:http://localhost:8080/native_servlet

Servlet、Filter、Listener 都生效了

使用 RegistrationBean 集成 Servlet、Filter、Listener

将方式1类上的相关注解(@ServletComponentScan、@WebServlet、@WebFilter、@WebListener)都注释掉

创建配置类 RegistrationConfig
@Configuration
public class RegistrationConfig {

    @Bean
    public ServletRegistrationBean<MyServlet> myServlet() {
        MyServlet myServlet = new MyServlet();
        return new ServletRegistrationBean<>(myServlet, "/registration_servlet");
    }

    @Bean
    public FilterRegistrationBean<MyFilter> myFilter() {
        MyFilter myFilter = new MyFilter();
        FilterRegistrationBean<MyFilter> filterRegistrationBean = new FilterRegistrationBean<>(myFilter);
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/registration_servlet", "/css/*", "/js/*"));
        return filterRegistrationBean;
    }

    @Bean
    public ServletListenerRegistrationBean<MyListener> myListener() {
        MyListener myListener = new MyListener();
        return new ServletListenerRegistrationBean<>(myListener);
    }
}
启动项目,访问链接:http://localhost:8080/registration_servlet
Servlet、Filter、Listener 都生效了

Interceptor 是否对原生 Servlet 生效?

创建拦截器 FirstInterceptor
@Slf4j
public class FirstInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("FirstInterceptor preHandle");
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("FirstInterceptor postHandle");
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("FirstInterceptor afterCompletion");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
创建配置文件 InterceptorConfig
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new FirstInterceptor());
    }
}
创建 DispatcherServletController
@RestController
@RequestMapping
public class DispatcherServletController {

    @RequestMapping("/dispatcher_servlet")
    public String dispatcherServlet() {
        return "dispatcher servlet";
    }

}
访问链接:http://localhost:8080/dispatcher_servlet

FirstInterceptor 生效

再次访问链接:http://localhost:8080/registration_servlet

FirstInterceptor 对原生 servlet 不生效

Servlet 路径匹配

默认情况下,SpringBoot 只有一个 Servlet (DispatcherServlet),当我们配置了原生的 servlet ,web 容器中就存在两个 Servlet,web 容器根据最佳匹配原则,映射到指定的 Servlet 上

如果 MyServlet 的的匹配路径也是 / ,会发生什么现象?
将 MyServlet 的拦截路径改成 /
在 DispatcherServletController 中添加接口
访问链接 : http://localhost:8080/

通过响应我们可以知道,选择的是 MyServlet(返回的是一个 html)

为什么选择MyServlet?
ServletWebServerApplicationContext#selfInitialize

getServletContextInitializerBeans 的返回值中 MyServlet 的优先级最高且满足最佳匹配,所以会选择 MyServlet

getServletContextInitializerBeans 方法是如何排序的

getServletContextInitializerBeans 方法是通过 AnnotationAwareOrderComparator 排序的,规则如下:

  1. ServletContextInitializer 实现类是否继承 PriorityOrdered 接口,如果都继承 PriorityOrdered 接口,比较 getOrder 方法返回的值,值越小,优先级越高
  2. ServletContextInitializer 实现类是否继承 Ordered 接口,如果都继承 Ordered 接口,比较 getOrder 方法返回的值,值越小,优先级越高
  3. ServletContextInitializer 实现类所属class上是否存在 @Order 注解,如果存在,比较注解设置的值,值越小,优先级越高
  4. ServletContextInitializer 实现类所属class上是否存在 @Priority 注解,如果存在,比较注解设置的值,值越小,优先级越高

DispatcherServletRegistrationBean 继承 RegistrationBean ,RegistrationBean 的 getOrder 方法返回值是 Ordered.LOWEST_PRECEDENCE,对于同样继承 RegistrationBean 的 ServletRegistrationBean 优先级一致,但是 ServletRegistrationBean 解析时机稍后,所以默认情况下优先级更高。

修改 DispatcherServletRegistrationBean 优先级

创建 FirstPostProcessor

@Component
public class FirstPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if ("dispatcherServletRegistration".equals(beanName) && (bean instanceof DispatcherServletRegistrationBean)) {
            DispatcherServletRegistrationBean dispatcherServletRegistrationBean = (DispatcherServletRegistrationBean) bean;
            dispatcherServletRegistrationBean.setOrder(-1);
        }

        return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}

访问链接 : http://localhost:8080/

通过响应我们可以知道,选择的是 DispatcherServlet(返回的是一个字符串)

相关推荐
激流丶11 分钟前
【Kafka 实战】如何解决Kafka Topic数量过多带来的性能问题?
java·大数据·kafka·topic
Themberfue15 分钟前
Java多线程详解⑤(全程干货!!!)线程安全问题 || 锁 || synchronized
java·开发语言·线程·多线程·synchronized·
让学习成为一种生活方式32 分钟前
R包下载太慢安装中止的解决策略-R语言003
java·数据库·r语言
晨曦_子画37 分钟前
编程语言之战:AI 之后的 Kotlin 与 Java
android·java·开发语言·人工智能·kotlin
假装我不帅1 小时前
asp.net framework从webform开始创建mvc项目
后端·asp.net·mvc
南宫生1 小时前
贪心算法习题其三【力扣】【算法学习day.20】
java·数据结构·学习·算法·leetcode·贪心算法
神仙别闹1 小时前
基于ASP.NET+SQL Server实现简单小说网站(包括PC版本和移动版本)
后端·asp.net
Heavydrink1 小时前
HTTP动词与状态码
java
ktkiko111 小时前
Java中的远程方法调用——RPC详解
java·开发语言·rpc