skip to Main Content

I just set up a very basic Spring Boot Web Application with Thymeleaf, but I can’t access my external JS file from the corresponding HTML file of my template and can’t figure out why.

My resource folder structure is as follows:

  • static/
    • index.html
    • css/
      • graph.css
    • js/
      • createGraph.js
  • templates/
    • visualizeGraph.html

Within my visualizeGraph.html I try to call the createGraph.js using following snippet within the <body> element:

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

In the <head> element of visualizeGraph.html, I added my stylesheet using following snippet:

    <link rel="stylesheet" type="text/css" media="all"
          href="/css/graph.css" th:href="@{/css/graph.css}" />

My Spring Boot Web Container runs on Port :8082, so I access my webapplication from localhost:8082 and access the visualizeGraph template from localhost:8082/visualizeGraph

When I check the Developer Console (F12), it throws a 404 for the createGraph.js file, but not for the graph.css file -> it can find the css successfully.

I can even access the css through localhost:8082/css/graph.css but CAN’T access the js-file using localhost:8082/js/createGraph.js (throws a 404 – as expected)

I can’t figure, what’s the cause for this phenomenon as my application.properties also has no additional parameters for modifying the resource source folder etc.

2

Answers


  1. Chosen as BEST ANSWER

    Okay, this was VERY weird. I found the solution, but I am not sure, whether it's IntelliJ, which was responsible for this problem or something else.

    What I did was to edit my <script> element in my HTML file to the following:

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

    and my intention was solely to try out, whether it would change anything. Somehow, IntelliJ told me, that it was not able to find the path (neither the js folder, nor the createGraph.js file within it) so what it suggested was to create the folder and the file (so I did, using ALT+Enter). What I did afterwards is to just copy the content of my old createGraph.js to the new file and to delete the (very strangely the same named) old folder and file and voila, everything works as expected... Very weird.


  2. You can call your JS files present in resources/static folder like below:

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

    No need to give the forward slash before the js folder.

    below I am attaching screenshot for my code:
    enter image description here

    Here, I was having images folder inside the static folder so we can directly call that folder.

    If you have any further doubts please feel free to visit my github amisham96

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search