参考答案:
在 Spring Boot 中,想要为所有页面添加通用的 JavaScript 代码,可以通过以下几种方式实现。
如果你的 Spring Boot 应用使用 Thymeleaf 作为模板引擎,你可以在通用布局模板中直接插入 JS 代码。这样,所有使用该布局的页面都会加载这些 JS 代码。
创建一个通用的布局文件(如 layout.html
):
<head>
或 <body>
标签内引用公共的 JS 文件或直接写入 JS 代码。1<!-- src/main/resources/templates/layout.html --> 2<!DOCTYPE html> 3<html xmlns:th="http://www.thymeleaf.org"> 4<head> 5 <meta charset="UTF-8"> 6 <title>Spring Boot Application</title> 7 <script src="/js/common.js"></script> <!-- 引入公共 JS 文件 --> 8 <script> 9 // 通用的 JS 代码 10 console.log("This is a global JS script."); 11 </script> 12</head> 13<body> 14 <div th:replace="~{::body}"></div> <!-- 用于渲染页面内容 --> 15</body> 16</html>
在其他页面中使用该布局模板:
th:replace
或 th:include
标签来引用布局模板,从而继承公共的 JS 代码。1<!-- src/main/resources/templates/home.html --> 2<html xmlns:th="http://www.thymeleaf.org"> 3<head> 4 <title>Home Page</title> 5</head> 6<body> 7 <h1>Welcome to Home Page</h1> 8</body> 9</html>
home.html
渲染在 layout.html
中的 <div>
标签中,自动加载公共的 JS 代码。如果你不使用 Thymeleaf,或者只是需要将通用 JS 代码添加到页面中,可以将 JavaScript 代码放在 static
目录下,然后通过 <script>
标签引用。
将通用的 JS 文件放在 src/main/resources/static/js
目录下。
1src/ 2└── main/ 3 └── resources/ 4 └── static/ 5 └── js/ 6 └── common.js
在每个 HTML 页面中通过 <script>
标签引用该 JS 文件:
1<!-- src/main/resources/templates/home.html --> 2<html> 3<head> 4 <title>Home Page</title> 5</head> 6<body> 7 <h1>Welcome to Home Page</h1> 8 <script src="/js/common.js"></script> <!-- 引入公共 JS 文件 --> 9</body> 10</html>
common.js
文件会在每个页面中加载。如果你需要对静态资源路径进行更多自定义配置(例如,动态处理 JavaScript 文件),可以通过实现 WebMvcConfigurer
接口来设置静态资源的路径。
1import org.springframework.context.annotation.Configuration; 2import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; 3import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 4 5@Configuration 6public class WebConfig implements WebMvcConfigurer { 7 @Override 8 public void addResourceHandlers(ResourceHandlerRegistry registry) { 9 // 配置静态资源路径 10 registry.addResourceHandler("/js/**") 11 .addResourceLocations("classpath:/static/js/"); 12 } 13}
这样,你可以自定义静态资源路径,使其适应不同的项目需求。
如果你使用了 Spring Boot 的 JSP 或 Freemarker 作为模板引擎,可以通过类似的方法在全局模板中引入 JS 文件。
最近更新时间:2024-12-11