Search code examples
javascriptjavaspringspring-bootthymeleaf

Cannot find related JS from Html with Thymeleaf


I am trying to setup a simple application based on Spring. This is the current folder structure of my project:

src
 |
  --main
      |
       --java
      |
       --resources
            |
             -- templates
                    |
                     -- Index.html
                     -- Index.js

My dependencies are the folliwing:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.0.3.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    <version>2.0.3.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    </exclusions>
</dependency>

If I place the logic of my Index.js into the Index.html everything works perfectly. Instead if I reference the Index.js on my console I see 404, cause it cannot find the js.

This is the code of the html:

<!DOCTYPE html>
<html>
<head>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script
            src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js">
    </script>
</head>
<body>

        <html>
        <head>
            <link rel="stylesheet" href="index.css">
        </head>
        <body>

        <div id="app">
            {{ message }}
        </div>

        <script src="index.js"></script>
        </body>
        </html>

</body>
</html>

and the js just for your reference:

var app = new Vue({
    el: '#app',
    data: {
        message: 'Hello Vue!'
    }
});

Solution

  • Found the solution, hope it helps everyone having my same problem. In practice Thymeleaf is a viewresolver that searches for views inside the resources/template folder.

    If we want to use the related JS script from the view, it has to be placed inside the Resources/static folder and still be referenced from the html as:

    <script src="index.js"></script>