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

Spring Boot中如何在JSP文件中关联外部CSS与JavaScript文件?

问题修复方案

1. 修正application.properties的拼写错误

你的配置项存在拼写错误,spring.web.resources.statstaticic-locations多了两个t,正确配置如下:

spring.mvc.view.prefix=/WEB-INF/views/ 
spring.mvc.view.suffix=.jsp  
spring.web.resources.static-locations=classpath:/static/,classpath:/public/,classpath:/resources/,classpath:/META-INF/resources/ 

2. 修复JSP中c:url标签的语法错误

当前link标签的c:url写法不符合JSTL语法规范,有两种正确使用方式:

方式一:直接嵌入href属性

<head> 
<meta charset="UTF-8"> 
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 
<link rel="stylesheet" type="text/css" href="<c:url value='/css/home.css'/>">     
<title>Project One</title> 
</head> 

方式二:先定义变量再引用

<head> 
<meta charset="UTF-8"> 
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 
<c:url var="homeCssUrl" value="/css/home.css"/>
<link rel="stylesheet" type="text/css" href="${homeCssUrl}">     
<title>Project One</title> 
</head> 

注意:必须在JSP页面顶部引入JSTL核心标签库,否则c:url标签无法生效:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

3. 验证资源路径映射

你的CSS文件路径src/main/resources/static/css/home.css完全符合Spring Boot静态资源的默认映射规则,修正上述配置和标签语法后,Spring Boot会自动将/css/home.css请求映射到该文件。

额外检查:JSP路径配置匹配

你在application.properties中配置了spring.mvc.view.prefix=/WEB-INF/views/,但实际JSP文件位于src/main/webapp/home.jsp。如果控制器返回的是逻辑视图名(比如return "home";),Spring会去/WEB-INF/views/home.jsp查找文件,这与实际路径不匹配。若要保留当前JSP路径,要么将prefix修改为/,要么在控制器中直接返回完整路径return "/home.jsp";。


内容的提问来源于stack exchange,提问作者vaulted xx

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 02:05:28