You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring项目集成Swagger遇HttpServletRequest类缺失错误求助

问题分析与解决方案

错误原因

报错javax.servlet.http.HttpServletRequest找不到,核心原因是Swagger依赖的Servlet API类缺失,可能是项目未引入Servlet相关依赖、依赖范围配置错误;另外SpringFox旧版本与高版本Spring Boot/JDK存在兼容性问题也可能引发这类错误。

具体解决步骤

1. 确保Servlet API依赖存在

  • 如果是Spring Boot项目,确认已引入spring-boot-starter-web依赖(该依赖默认包含Servlet API):
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
  • 如果是普通Spring项目,手动添加Servlet API依赖(注意调整版本与项目匹配):
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <!-- 本地运行需设为compile,若为web容器部署可改为provided -->
        <scope>compile</scope>
    </dependency>
    
    若使用JDK 11+,由于javax包已迁移到jakarta,需替换为:
    <dependency>
        <groupId>jakarta.servlet</groupId>
        <artifactId>jakarta.servlet-api</artifactId>
        <version>5.0.0</version>
        <scope>compile</scope>
    </dependency>
    

2. 解决SpringFox兼容性问题(可选但推荐)

SpringFox 2.x版本已停止维护,与Spring Boot 2.6+、JDK11+兼容性差,建议替换为SpringDoc OpenAPI(Swagger 3.0规范实现):

  • 移除原有springfox依赖,添加SpringDoc依赖:
    <dependency>
        <groupId>org.springdoc</groupId>
        <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
        <version>2.2.0</version>
    </dependency>
    
  • 无需额外配置类(默认自动扫描API),访问地址改为http://localhost:8080/swagger-ui.html或http://localhost:8080/swagger-ui/index.html(依版本而定)。

3. 修正SwaggerConfig路径匹配(若继续使用SpringFox)

你的postPaths()方法中正则表达式有误,/api/v1/*仅匹配/api/v1/后单个字符,改为匹配所有子路径:

private Predicate<String> postPaths() {
    return or(regex("/api/v1/**"), regex("/api/v1/get_all_bookings/**"));
}
// 或更简洁的写法:
// return PathSelectors.ant("/api/v1/**");

4. 验证配置

启动项目后访问Swagger UI地址(SpringFox默认是http://localhost:8080/swagger-ui.html),检查API是否正常显示。


内容的提问来源于stack exchange,提问作者Sandeep Roy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 09:13:07