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

Spring Boot Security项目中ThymeLeaf加载CSS文件异常求助

Spring Boot登录后跳转异常显示CSS内容的解决方案

问题定位

登录成功后本该跳转到根路径,却显示CSS文件内容,链接变为localhost:8080/style.css?continue...,核心原因大概率是登录成功跳转逻辑被continue参数干扰,或是静态资源未被正确放行,导致请求被错误路由到静态资源路径。

具体解决步骤

  • 修正Spring Security配置(若使用Security)
    确保静态资源完全放行,同时强制登录成功后跳转到根路径,避免continue参数影响:

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                    // 放行所有静态资源路径
                    .antMatchers("/css/**", "/js/**", "/images/**").permitAll()
                    .anyRequest().authenticated()
                .and()
                .formLogin()
                    .loginPage("/login")
                    // 第二个参数设为true,强制跳转到根路径,忽略continue参数
                    .defaultSuccessUrl("/", true)
                    .permitAll()
                .and()
                .logout()
                    .permitAll();
        }
    }
    
  • 简化HTML中的CSS引入
    移除原生href属性,仅保留Thymeleaf的th:href,避免浏览器在渲染前解析错误路径:

    <link rel="stylesheet" media="all" th:href="@{/css/style.css}" type="text/css" />
    
  • 明确登录控制器的跳转逻辑
    在登录处理的Controller中,直接返回重定向到根路径,不依赖默认行为:

    @Controller
    public class LoginController {
    
        @PostMapping("/login")
        public String handleLogin() {
            // 明确重定向到根路径
            return "redirect:/";
        }
    }
    
  • 验证项目结构与缓存

    • 确认CSS文件路径为src/main/resources/static/css/style.css,检查文件名/路径是否有大小写错误(Linux环境下敏感)
    • 按Ctrl+Shift+R强制刷新浏览器,清除缓存的旧请求记录

内容的提问来源于stack exchange,提问作者Kévin Jovanovic

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 18:52:46