You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Thymeleaf无法找到resources/templates目录下的login.html文件

问题:Spring Boot + Gradle中Thymeleaf无法找到templates下的login.html文件

使用Spring Boot + Gradle开发登录页面时,访问/login出现404白标错误,提示"No static resource .",Thymeleaf无法加载src/main/resources/templates/login.html,已确认目录结构与请求映射配置无误。

排查与解决方案

1. 验证文件路径与打包有效性

  • 确认login.html准确位于src/main/resources/templates/目录下,文件名大小写与控制器返回的"login"完全匹配(Linux/macOS环境对文件名大小写敏感)
  • 执行gradle clean build命令,检查build/resources/main/templates/目录下是否存在login.html,确保文件被正确打包到Classpath中

2. 检查控制器组件扫描与请求映射

  • 确保AuthController所在包是Spring Boot主类(标注@SpringBootApplication的类)的同级或子包,若不在同一包路径下,需在主类添加@ComponentScan(basePackages = "你的控制器包路径")指定扫描范围
  • 启动应用时查看控制台日志,确认存在类似以下的日志条目,证明请求映射已成功注册:
    Mapped GET "/login" to public java.lang.String org.inthisyear.AuthController.login(org.springframework.ui.Model)
    

3. 修正Spring Security配置

当前配置中requestMatchers("/**")会匹配所有请求,导致后续权限规则失效,建议替换为精确路径匹配:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorizeRequests ->
                        authorizeRequests
                                // 替换/**为具体允许的路径
                                .requestMatchers("/home", "/login", "/register", "/webjars/**", "/css/**", "/error")
                                .permitAll()
                                .anyRequest()
                                .authenticated()
                )
                .formLogin(formLogin ->
                        formLogin
                                .loginPage("/login")
                                .loginProcessingUrl("/login")
                                .defaultSuccessUrl("/", true)
                                .permitAll()
                )
                .logout(LogoutConfigurer::permitAll);

        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

4. 简化Thymeleaf配置

Spring Boot默认已配置Thymeleaf的前缀为classpath:/templates/、后缀为.html,可移除application.properties中的自定义配置,避免冲突:

# 移除以下配置,使用默认值即可
# spring.thymeleaf.prefix=classpath:/templates/
# spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false

5. 清理缓存与重启应用

  • 删除项目根目录下的build文件夹,重新执行gradle build
  • 若使用spring-boot-devtools,删除用户目录下的.spring-boot-devtools缓存文件夹,再重启应用

内容的提问来源于stack exchange,提问作者Laura Ferry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 03:03:27