Spring Boot Security自定义登录页面加载失败报404错误如何解决
Controller包扫描失败
Spring Boot默认只会扫描启动类所在包及其子包下的Bean。如果你的启动类没有放在controller包的父层级(例如启动类包路径是com.example.demo,但TemplateController放在了根路径下的controller包而非com.example.demo.controller),@Controller注解不会被Spring识别,/login接口自然不存在。
解决方案:要么调整Controller的包路径到启动类子包下,要么在启动类上添加@ComponentScan(basePackages = "controller")指定扫描范围。缺失web starter依赖
你贴出的pom.xml仅包含thymeleaf依赖,若未引入spring-boot-starter-web,Spring不会启动Web容器,也不会解析Controller接口,所有请求都会404。
解决方案:在pom中添加web依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
- 视图解析配置异常
检查application.properties/yml是否修改过Thymeleaf的默认视图规则,默认规则是前缀classpath:/templates/、后缀.html,如果自定义了错误的前缀/后缀,会导致Spring找不到templates下的login.html。如果没有自定义配置,可以加如下配置强制匹配:
spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html
项目配置了上下文根路径
如果配置文件中指定了server.servlet.context-path(例如值为/myproject),直接访问http://localhost:8080/login会404,需要改为访问http://localhost:8080/myproject/login。文件名大小写不匹配
核对templates下的登录页文件名是否完全是login.html,注意大小写,Linux环境下大小写敏感,Login.html、login.HTML都无法匹配Controller返回的"login"字符串。
内容的提问来源于stack exchange,提问作者Guillaume_96

