Spring Boot - Spring Boot 静态资源延迟响应(使用拦截器、使用过滤器、使用 ResourceResolver)

需求概述

yaml 复制代码
spring:
  mvc:
    static-path-pattern: /file/download/**
  web:
    resources:
      static-locations: file:D:/files/
  • 在 Spring Boot 中,在上述静态资源映射的基础上,实现延迟响应,用于测试请求超时

一、使用拦截器

java 复制代码
@Component
public class DelayInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 对静态资源请求进行延迟
        if (handler instanceof ResourceHttpRequestHandler) {
            Thread.sleep(20 * 1000);
        }

        return true;
    }
}
java 复制代码
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private DelayInterceptor delayInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        // 配置拦截器
        registry.addInterceptor(delayInterceptor)
                .addPathPatterns("/file/download/**");
    }
}

二、使用过滤器

java 复制代码
@Component
@Order(1)
public class DelayFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;

        String path = httpRequest.getRequestURI();

        if (path.startsWith("/file/download/")) {
            try {
                Thread.sleep(20 * 1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }
}

三、使用 ResourceResolver

java 复制代码
public class DelayResourceResolver extends PathResourceResolver {

    @Override
    protected Resource getResource(String resourcePath, Resource location) throws IOException {
        
        // 对静态资源请求进行延迟
        try {
            Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return super.getResource(resourcePath, location);
    }
}
java 复制代码
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        // 配置 ResourceResolver
        registry.addResourceHandler("/file/download/**")
                .addResourceLocations("file:D:/files/")
                .resourceChain(true)
                .addResolver(new DelayResourceResolver());
    }
}
  • 注:有了上述 WebConfig 配置类,就不需要在 application.yaml 配置文件中配置相关的静态资源映射了
相关推荐
uzong11 小时前
我研读了 500 个 Spring Boot 生产级代码库,90% 都犯了这 7 个致命错误
后端
野生技术架构师12 小时前
金三银四面试总结篇,汇总 Java 面试突击班后的面试小册
java·面试·职场和发展
xiaobaoyu12 小时前
ssm知识点梳理
后端
小袁拒绝摆烂12 小时前
多表关联大平层转JSON树形结构
java·json
IT_陈寒13 小时前
Vite的public文件夹放静态资源?这坑我替你踩了
前端·人工智能·后端
浮游本尊13 小时前
合同同步逻辑
后端
子兮曰13 小时前
别让爬虫白嫖你的导航站了:纯免费,手把手实现加密字体防爬
前端·javascript·后端
阿苟13 小时前
JAVA重点难点
后端
uzong13 小时前
TIOBE 指数:2026 年编程语言排行榜
后端