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

Spring Boot端点变更后CSS/JS失效问题求助及解决方案咨询

问题原因分析
  1. 相对路径解析错误
    你当前使用的是相对路径css/style.css,当页面URL为localhost:8080/Library/write时,浏览器会解析为localhost:8080/Library/css/style.css,刚好匹配Spring Boot静态资源的默认访问规则(resources/static下的文件会映射到应用根路径/)。但当页面URL变为localhost:8080/Library/blogwriting/write时,浏览器会把相对路径解析为localhost:8080/Library/blogwriting/css/style.css,这个路径不存在,服务器返回403权限错误;同时因为实际返回的不是CSS内容,浏览器会报MIME类型不匹配。

  2. Spring Security拦截(潜在原因)
    如果你的项目配置了Spring Security,默认会拦截所有请求,包括静态资源。当请求错误路径时,Security可能直接返回403而非404,这也会导致你看到的错误。


解决方案

方案1:使用Thymeleaf的URL表达式(推荐)

Thymeleaf的@{...}语法会自动基于当前应用的上下文路径生成正确的绝对路径,不管页面处于哪个端点都能正确指向静态资源。修改你的CSS引入代码:

<link rel="stylesheet" th:href="@{/css/style.css}">

JS文件的引入也用同样的方式:

<script th:src="@{/js/xxx.js}"></script>

注意:确保HTML文件的根标签(比如<html>)添加了Thymeleaf命名空间:xmlns:th="http://www.thymeleaf.org",否则th:href属性不会生效。

方案2:放行静态资源(针对Spring Security)

如果项目使用了Spring Security,需要在Security配置类中明确放行静态资源路径,避免被拦截。添加以下配置:

import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    // ... 其他配置

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 放行所有静态资源路径
        web.ignoring().antMatchers("/css/**", "/js/**", "/images/**");
    }
}

方案3:使用绝对路径(不推荐)

直接写死基于应用上下文的绝对路径,这种方式不够灵活,当应用上下文路径(比如Library)改变时需要手动修改:

<link rel="stylesheet" href="/Library/css/style.css">

内容的提问来源于stack exchange,提问作者minhson Bui

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 20:02:40