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(返回的是一个字符串)

相关推荐
天天扭码6 分钟前
五天SpringCloud计划——DAY1之mybatis-plus的使用
java·spring cloud·mybatis
程序猿小柒12 分钟前
leetcode hot100【LeetCode 4.寻找两个正序数组的中位数】java实现
java·算法·leetcode
机器之心41 分钟前
全球十亿级轨迹点驱动,首个轨迹基础大模型来了
人工智能·后端
不爱学习的YY酱1 小时前
【操作系统不挂科】<CPU调度(13)>选择题(带答案与解析)
java·linux·前端·算法·操作系统
丁总学Java1 小时前
Maven项目打包,com.sun.tools.javac.processing
java·maven
kikyo哎哟喂1 小时前
Java 代理模式详解
java·开发语言·代理模式
Doker 多克1 小时前
Spring AI 框架使用的核心概念
人工智能·spring·chatgpt
duration~1 小时前
SpringAOP模拟实现
java·开发语言
小码ssim1 小时前
IDEA使用tips(LTS✍)
java·ide·intellij-idea
潜洋2 小时前
Spring Boot教程之五:在 IntelliJ IDEA 中运行第一个 Spring Boot 应用程序
java·spring boot·后端