Spring Boot Controller映射失效:请求均跳转至Whitelabel错误页
问题现象
所有请求均返回404错误页,即便已在Controller中配置了请求映射。将代码简化至最小可复现版本后问题依然存在,且项目在另一相同OS系统上可正常运行。
最小复现代码
项目结构如图所示。最初将Controller与主类分离,后为排除结构问题将Controller代码移入主类,两种写法均触发相同错误:
版本1(Controller代码移入主类)
package com.example.demo; @Controller @SpringBootApplication public class TestApplication { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @GetMapping("/greeting") @ResponseBody public String greeting() { return "greeting"; } }
版本2(修改映射路径)
@Controller @SpringBootApplication public class TestApplication { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @GetMapping("/hello") @ResponseBody public String greeting() { return "greeting"; } }
访问http://localhost:8080/greeting与http://localhost:8080/hello均返回404错误页。
依赖配置(pom.xml)
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
无论是否添加tomcat依赖,问题均未解决。
错误信息
浏览器返回:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.Sun Nov 27 00:16:08 CET 2022
There was an unexpected error (type=Not Found, status=404).
调试日志(设置debug=true后)
GET "/greeting", parameters={} Mapped to ResourceHttpRequestHandler [classpath [META-INF/resources/], classpath [resources/], classpath [static/], classpath [public/], ServletContext [/]] Resource not found Completed 404 NOT_FOUND "ERROR" dispatch for GET "/error", parameters={}
解决方案
修正主类启动参数:
主类TestApplication的main方法中,SpringApplication.run(Application.class, args)传入了不存在的Application.class,导致Spring无法加载正确的配置类,进而未扫描到Controller的映射。需修改为:SpringApplication.run(TestApplication.class, args);优化Controller注解:
将@Controller + @ResponseBody替换为@RestController,简化REST接口的代码写法,效果一致。清理冗余依赖:
spring-boot-starter-web已包含嵌入式Tomcat依赖,无需额外引入spring-boot-starter-tomcat,移除该依赖避免潜在冲突。
内容的提问来源于stack exchange,提问作者Ramy670

