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

Spring Boot电商项目仅根路径可访问,其余Controller映射报404

排查Spring Boot电商项目Controller 404问题的实用步骤

针对你遇到的根路径可访问但/admin等Controller映射路径返回404的问题,结合常见场景整理以下排查方向:

1. 核对Controller注解与路径配置

  • 确认Controller类上标注了@Controller(用于返回视图页面)或@RestController(用于返回JSON数据),二者选其一,不要遗漏。
  • 检查类或方法上的@RequestMapping/@GetMapping/@PostMapping注解路径是否拼写正确,比如@RequestMapping("/admin")是否多写/少写斜杠,有没有大小写错误。

2. 确认主启动类的包扫描范围

Spring Boot默认扫描主启动类所在包及其子包的组件,若Controller不在这个范围内,即使手动配置@ComponentScan也可能出错:

  • 比如主启动类在com.shop.ecommerce,Controller在com.shop.admin,需要明确指定扫描路径:
    @SpringBootApplication(scanBasePackages = {"com.shop.ecommerce", "com.shop.admin"})
    public class EcommerceApplication {
        public static void main(String[] args) {
            SpringApplication.run(EcommerceApplication.class, args);
        }
    }
    
    注意@SpringBootApplication已包含@ComponentScan功能,无需重复添加,仅当需要自定义扫描范围时补充即可。

3. 查看启动日志验证Controller是否被加载

启动项目后,搜索日志中是否存在类似Mapped "{[/admin]}" onto public ...的记录:

  • 若无此日志,说明Spring未识别到Controller类,可能是注解错误、包扫描范围不对,或者Controller类未被编译到target/build目录(可检查编译后的目录结构)。
  • 若有此日志,问题大概率出在请求路径拼写(比如多了斜杠、大小写不符),或者静态资源路径与Controller路径冲突。

4. 验证请求URL的正确性

  • 确保请求的是http://localhost:8080/admin,而非http://localhost:8080//admin或带多余后缀的路径。
  • 若Controller方法包含路径变量(如@GetMapping("/admin/{id}")),需携带正确参数访问,比如/admin/1。

5. 排查拦截器/过滤器的拦截规则

检查项目中是否存在自定义的HandlerInterceptor或Filter,这类组件可能拦截了/admin路径的请求,导致无法到达Controller。可以暂时禁用这些组件,测试是否能正常访问。

6. 检查静态资源路径是否冲突

如果src/main/resources/static或templates目录下存在admin文件夹,Spring Boot会优先将/admin解析为静态资源路径,而非Controller映射。解决方法:

  • 修改Controller路径,比如改为/admin-panel;
  • 或在application.properties中调整静态资源映射规则:
    spring.mvc.static-path-pattern=/static/**
    
    这样静态资源只能通过/static/xxx访问,避免与Controller路径冲突。

7. 确认依赖配置无误

  • 确保Maven/Gradle中已引入Spring Web依赖:
    Maven:
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
    Gradle:
    implementation 'org.springframework.boot:spring-boot-starter-web'
    
  • 若使用Thymeleaf等视图模板,需同时引入对应的starter依赖,否则返回视图时会出现404。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 09:50:29