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

SpringBoot Web应用部署到Tomcat后无法正确引用CSS和JS文件

SpringBoot War包部署Tomcat后静态资源失效解决方案

核心问题原因

部署到外部Tomcat后,应用会带有上下文路径(即访问URL中的/你的项目名称部分),静态资源引用如果未适配该路径,就会出现404找不到的情况。SpringBoot默认已对静态资源目录做了配置,无需手动创建web.xml。

具体解决步骤

1. 确认静态资源存放位置

确保CSS、JS等静态资源放在src/main/resources/static/目录下,比如:

src/main/resources/
└── static/
    ├── css/
    │   └── style.css
    └── js/
        └── main.js

这是SpringBoot默认的静态资源目录,框架会自动识别并映射。

2. 正确引用静态资源

根据你使用的页面类型选择对应写法:

  • 如果用Thymeleaf模板(推荐):
    使用Thymeleaf的@{}链接表达式,它会自动拼接上下文路径,示例:

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

    部署后会自动生成为/你的项目名/css/style.css,匹配Tomcat的访问路径。

  • 如果是普通HTML:
    手动拼接上下文路径,可通过JS动态获取:

    <script>
        // 获取当前应用的上下文路径
        const contextPath = window.location.pathname.split('/')[1];
        const baseUrl = `/${contextPath}`;
    </script>
    <link rel="stylesheet" href="${baseUrl}/css/style.css">
    <script src="${baseUrl}/js/main.js"></script>
    

3. 统一上下文路径配置

在src/main/resources/application.properties中添加配置,让本地测试和服务器部署的上下文路径保持一致,避免路径混乱:

server.servlet.context-path=/你的项目名称

4. 检查War包打包配置

确保pom.xml中正确配置了war打包及依赖:

<!-- 指定打包方式为war -->
<packaging>war</packaging>

<dependencies>
    <!-- 排除内置Tomcat,避免与外部Tomcat冲突 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <!-- 核心Web依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- 若使用Thymeleaf,添加此依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
</dependencies>

<build>
    <!-- SpringBoot Maven打包插件,确保war包正确生成 -->
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

5. 验证控制台错误

查看Chrome控制台的404请求URL,确认是否缺少上下文路径。比如错误请求是/css/style.css,而正确路径应该是/你的项目名/css/style.css,按照上述步骤修改后即可解决。

内容的提问来源于stack exchange,提问作者Kayd Anderson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 17:01:26