Search code examples
javaspring-bootthymeleaf

Thymeleaf and Spring Boot, how to construct assets folder to view html both in runtime and designtime


I have a Spring Boot 2 project and use Thymeleaf template engine. The folder structure is:

main\
  resources\
    static\
      assets\
        css\
          my.css
        js\

    templates\
      index.html

(1) If I refer my.css as ../static/assets/css/my.css in index.html, I can view index.html directly in browser(file:///path/to/main/resources/templates/index.html) but if I run the project in JetBrains IDEA, and browse it as http://localhost:8080/, the browser console tells can not found my.css.

(2) If I refer my.css as assets/css/my.css in index.html, When I view index.html directly in browser(file:///path/to/main/resources/templates/index.html) the browser tells can not found my.css, but if I run the project in JetBrains IDEA, and browse it as http://localhost:8080/, the browser view becomes OK.

Because Thymeleaf site says it is friendly to both design time, runtime and cooperation with programmer and designer, then can anyone tell me how to construct my static resources and html templates folders relationship to achieve this target? Thanks a lot first!


Solution

  • In Spring boot static files are served from the location src/main/resources/static and are available at the root of the application URL. For example, if you have src/main/resources/static/assets/css/my.css, then when you run the application it is available at the location http://localhost:8080/assets/css/my.css.

    So you can include it in your index.html as follows:

    <link rel="stylesheet" href="../static/assets/css/my.css" 
        th:href="@{/assets/css/my.css}" />
    

    This way when you just open index.html in the browser, it will detect the CSS using href and when you launch it via the server i.e by running the app and the opening it in the browser, then Thymeleaf will process the th:href. So it would work in both cases.