SpringBoot学习遇404错误:接口无法返回JSON数据求助
SpringBoot Whitelabel Error Page(404)问题解决
问题原因排查与修复步骤
1. 显式指定@GetMapping的请求路径
你的@GetMapping未设置具体路径,虽然Spring Boot默认会映射到根路径(/),但可能因环境配置或上下文路径问题导致匹配失败,直接指定路径可避免此类问题:
@GetMapping("/students") public List<Student> getStudents(){ return List.of( new Student( 1L, "Mohamed", "Mohamed@gmail.com", LocalDate.of(1999, Month.MARCH, 28), 23 ) ); }
修改后访问http://localhost:8080/students即可触发接口。
2. 确保Student类支持JSON序列化
即使路径正确,如果Student类没有属性访问方法,Spring Boot的消息转换器无法将对象序列化为JSON格式。需为Student类添加所有属性的getter方法,或用Lombok的@Data注解自动生成:
手动添加getter的Student类示例:
package com.example.demo.Student; import java.time.LocalDate; public class Student { private Long id; private String name; private String email; private LocalDate dob; private Integer age; public Student(Long id, String name, String email, LocalDate dob, Integer age) { this.id = id; this.name = name; this.email = email; this.dob = dob; this.age = age; } // 必须添加所有属性的getter方法 public Long getId() { return id; } public String getName() { return name; } public String getEmail() { return email; } public LocalDate getDob() { return dob; } public Integer getAge() { return age; } }
使用Lombok简化的示例:
先在pom.xml中添加Lombok依赖(若未添加):
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
再修改Student类:
package com.example.demo.Student; import java.time.LocalDate; import lombok.Data; @Data // 自动生成getter、setter、toString等方法 public class Student { private Long id; private String name; private String email; private LocalDate dob; private Integer age; public Student(Long id, String name, String email, LocalDate dob, Integer age) { this.id = id; this.name = name; this.email = email; this.dob = dob; this.age = age; } }
3. 检查应用上下文路径配置
若你的application.properties/application.yml中配置了server.servlet.context-path(如server.servlet.context-path=/demo),访问时需加上该前缀,例如http://localhost:8080/demo/students。
验证步骤
- 重启Spring Boot应用
- 访问修改后的URL(如
http://localhost:8080/students) - 页面应返回JSON格式的学生列表数据
内容的提问来源于stack exchange,提问作者LAKHDAR Mohamed
相关产品推荐
相关产品推荐

