Spring和Thymeleaf:如何将javascript移动到单独的.js文件
例如: 这很有效Spring和Thymeleaf:如何将javascript移动到单独的.js文件,javascript,spring,thymeleaf,Javascript,Spring,Thymeleaf,例如: 这很有效 <!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> <but
<!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>
打招呼
函数sayHello(文本){
警报(文本);
}
但是,如果我将js移动到同一文件夹中的hello.js文件中,脚本将无法工作
我试着这样做:
<script type="text/javascript" th:src="@{hello.js}"></script>
<script type="text/javascript" src="hello.js"></script>
就像这样:
<script type="text/javascript" th:src="@{hello.js}"></script>
<script type="text/javascript" src="hello.js"></script>
我做错了什么?根据Spring引导文档,静态资源是从/static、/public或类路径之外提供的 还简要介绍了如何重新加载静态内容和模板文件
假设您使用的是Spring Boot的默认配置,您应该在
src/main/resources/templates/
中有您的thymeleaf文件,因此您应该将javascript文件放入:
/src/main/resources/static
解释:构建工具(Maven或Gradle)将复制应用程序类路径中/src/main/resources/
的所有内容,如中所述,类路径中名为/static
的目录中的所有内容将作为静态内容
此目录也可以使用,但不建议使用:
/src/main/webapp/
如果您的应用程序将被删除,请不要使用src/main/webapp目录
包装成罐子。虽然此目录是一个通用标准,但它
只适用于战争包装,它将被默默地忽略
如果您生成一个jar,那么大多数构建工具都是可用的
您能检查一下在浏览器中使用开发人员工具时出现的错误吗?可能没有加载hello.js文件,将其更改为如果根上下文中有它,斜杠没有帮助。消息说“ReferenceError:sayHello未定义”确实如此!非常感谢安德里亚。