Spring Boot无法渲染视图返回404错误,求排查原因
解决Spring Boot访问Thymeleaf视图出现404白标错误
1. 确认Thymeleaf依赖是否正确引入
Spring Boot要渲染Thymeleaf视图,必须引入spring-boot-starter-thymeleaf依赖,否则无法识别视图模板。
- Maven项目(pom.xml)添加依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
- Gradle项目(build.gradle)添加依赖:
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
添加后重新构建项目并重启应用。
2. 检查控制器是否被正确扫描
@SpringBootApplication注解默认扫描主类所在包(com.example.demo)及其所有子包,你的控制器在com.example.demo.user子包下,理论上会被自动扫描。可通过启动日志验证:
查看日志中是否存在类似
Mapped GET / onto public java.lang.String com.example.demo.user.UserController.index()的记录,若没有说明控制器未被扫描,可在主类显式指定扫描范围:@SpringBootApplication(scanBasePackages = "com.example.demo") public class Application { ... }
3. 验证视图文件的位置和名称
确保login.html完全符合以下要求:
- 路径:必须放在
src/main/resources/templates目录下(Spring Boot Thymeleaf默认的视图根目录) - 文件名:大小写完全匹配(Linux/macOS环境对文件名大小写敏感,避免出现
Login.html或拼写错误) - 文件本身:无损坏,HTML格式正确
4. 额外提示:表单渲染的后续问题
404问题解决后,页面可能会出现user对象不存在的错误,因为视图中使用了th:object="${user}",但控制器未将User实例传入Model。可修改控制器方法:
@GetMapping public String index(Model model) { // 需确保项目中有对应的User实体类 model.addAttribute("user", new User()); return "login"; }
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

