简体   繁体   English

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

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

Example: 例:

This works 这有效

<!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>

But, if I move js to the file hello.js in the same folder, script is not working. 但是,如果我将js移动到同一文件夹中的文件hello.js,则脚本无效。

I tried embed like this: 我尝试嵌入这样的:

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

And like this: 像这样:

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

What I'm doing wrong? 我做错了什么?

Assuming you are using default configurations from Spring Boot you should have your thymeleaf file in src/main/resources/templates/ so you should put the javascript file in: 假设您使用Spring Boot的默认配置,您应该在src/main/resources/templates/包含您的thymeleaf文件,因此您应该将javascript文件放入:

/src/main/resources/static

Explanation : your build tool (Maven or Gradle) will copy all the content from /src/main/resources/ in the application classpath and, as written in Spring Boot's docs , all the content from a directory called /static in the classpath will be served as static content. 说明 :您的构建工具(Maven或Gradle)将复制应用程序类路径中/src/main/resources/所有内容,并且如Spring Boot的文档中所述,类路径中名为/static的目录中的所有内容都将是作为静态内容。


This directory could works also, but it is discouraged: 这个目录也可以,但不鼓励:

/src/main/webapp/

Do not use the src/main/webapp directory if your application will be packaged as a jar. 如果您的应用程序将打包为jar,请不要使用src / main / webapp目录。 Although this directory is a common standard, it will only work with war packaging and it will be silently ignored by most build tools if you generate a jar. 虽然这个目录是一个通用标准,但它只适用于war包装,如果你生成一个jar,它将被大多数构建工具默默忽略。

According to the Spring Boot documentation, static resources are served from /static, /public or off the classpath. 根据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/#boot-features-spring-mvc-static-content

There is also a brief mention of how to reload your static content and template files. 还简要提到了如何重新加载静态内容和模板文件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM