Spring Boot项目出现Whitelabel Error Page(404)问题求助
错误信息
Whitelabel Error Page:
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sat Jul 13 13:54:21 IST 2024.
There was an unexpected error (type=Not Found, status=404).
问题分析与解决步骤
1. 检查请求路径与方法是否匹配
你的UserController中定义的两个接口均为POST请求,路径分别是:
POST /users/signupPOST /users/login
如果直接用浏览器访问(默认GET请求)或输入错误路径,必然返回404。必须使用Postman、curl等工具发送POST请求,并在请求体中传入JSON格式的用户数据,示例请求体:
{ "username": "test", "password": "123456", "email": "test@example.com" }
2. 修复UserService的语法错误
你提供的UserService.java代码存在语法错误:类定义未闭合,缺少最后一个大括号。修复后的代码如下:
package com.example.arvrapp.service; import com.example.arvrapp.model.User; import com.example.arvrapp.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired private UserRepository userRepository; public User registerUser(User user) { return userRepository.save(user); } public User findUserByUsername(String username) { return userRepository.findByUsername(username); } }
语法错误会导致编译失败,Spring容器无法正确初始化Bean,进而导致控制器接口无法被映射。
3. 确认启动类位置与组件扫描范围
Spring Boot启动类必须放在根包(如com.example.arvrapp)下,否则@SpringBootApplication默认无法扫描到控制器、Repository等组件。如果启动类在子包中,需手动指定扫描范围:
package com.example.arvrapp.app; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication(scanBasePackages = "com.example.arvrapp") public class ArvrAppApplication { public static void main(String[] args) { SpringApplication.run(ArvrAppApplication.class, args); } }
4. 检查依赖完整性
确保项目依赖中包含以下核心依赖(以Maven为例):
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- 根据使用的数据库添加驱动,例如MySQL --> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <scope>runtime</scope> </dependency> </dependencies>
缺失依赖会导致Web或JPA功能无法正常启用,进而引发接口映射失败。
5. 验证数据库配置
在application.properties或application.yml中配置正确的数据库连接信息,示例:
spring.datasource.url=jdbc:mysql://localhost:3306/arvr_db?useSSL=false&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=your_password spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true
数据库连接异常会导致JPA Repository无法初始化,控制器注入失败,最终影响接口映射。
内容的提问来源于stack exchange,提问作者Akshay Dj

