Search code examples
spring-bootthymeleaf

Spring Boot, Thymeleaf and CSS


This is really silly but I am not able to get it working.

In my spring boot mvc app, I have let's say 5 thyme leaf templates one of which is error.html.

error.html comes handy when a request is made for any invalid routes.

The issue happens when the invalid routes are nested (like 2 or more level) then the css dont apply.

Eg:

http://localhost:3000/application/index- valid route and css is applied
http://localhost:3000/application/success- valid route and css is applied
http://localhost:3000/application/failure- valid route and css is applied
http://localhost:3000/application/invalidroute- route does not exist but css is applied
http://localhost:3000/application/invalidroute/something - route does not exist and css is also not applied

My CSS is located in css folder under the static folder

All the thymeleaf templates are at the same level and access the css by

 <link rel="stylesheet" href="css/main.css"/>

Error seen in console

GET http://localhost:3000/application/invalidroute/css/main.css net::ERR_ABORTED 404

Solution

  • Instead of

    <link rel="stylesheet" href="css/main.css"/>
    

    Use this :

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

    and make sure this is your file placeholders

    src/main/resource/static/css - for CSS files

    src/main/resource/templates - for HTML templates files