Spring 和 Thymeleaf:如何将 javascript 移动到单独的.js文件

Spring and Thymeleaf: How to move javascript to a separate .js file

本文关键字:移动 单独 文件 js javascript Thymeleaf Spring      更新时间:2023-09-26

示例:

这行得通

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head lang="en">
    <meta charset="UTF-8"/>
    <title></title>
</head>
<body>
    <button th:onclick="'javascript:sayHello(''hello'')'">Say Hello</button>
</body>
<script>
    function sayHello(text) {
        alert(text);
    }
</script>
</html>

但是,如果我将js移动到文件hello.js在同一文件夹中,则脚本不起作用。

我尝试像这样嵌入:

<script type="text/javascript" th:src="@{hello.js}"></script>

像这样:

<script type="text/javascript" src="hello.js"></script>

我做错了什么?

假设你使用的是 Spring Boot 的默认配置,你应该有你的 thymeleaf 文件src/main/resources/templates/所以你应该把 javascript 文件放在:

/src/main/resources/static

说明:您的构建工具(Maven 或 Gradle)将复制应用程序类路径中/src/main/resources/的所有内容,并且正如 Spring Boot 文档中所写的那样,类路径中名为 /static 的目录中的所有内容都将作为静态内容提供。


此目录也可以工作,但不鼓励这样做:

/src/main/webapp/

不要使用 src/main/webapp 目录,如果你的应用程序将是 包装成罐子。虽然这个目录是一个通用标准,但它 只能与战争包装一起使用,并且会被默默忽略 大多数构建工具,如果你生成一个 jar。

根据 Spring Boot 文档,静态资源是从/static、/public 或类路径外提供的。

http://docs.spring.io/spring-boot/docs/1.2.0.RELEASE/reference/htmlsingle/#boot-features-spring-mvc-static-content

还简要提到了如何重新加载静态内容和模板文件。

http://docs.spring.io/spring-boot/docs/1.2.0.RELEASE/reference/htmlsingle/#howto-reload-static-content