spring-bootthymeleafstatic-contentcontextpath

Spring Boot Context Path Static Files Not Found


I have a problem with my application not finding my static files. This however only happens on a certain level. As you can see from the code fragments below, the css, images, js, etc works on certain files and not on others. Not sure what I am missing here.

My Stack: Spring Boot, Thymeleaf

Part of my application.yml file:

server:
  port: 8090
  servlet:
    context-path: /myapp

My application public resources directory structure:

/resources
   /public
      /css
      /images
      /js

My application template structure and where the styles and images work:

/resources
  /templates/index.html (works)
  /templates/admin/index.html (works)
  /templates/admin/user/admin/showuser.html (does not work)

Code from /resources/admin/fragments/header.html (Used as a header file for other files)

<!DOCTYPE html>
<html>
<head>
    <link href="css/mycss.css" rel="stylesheet">

Code from /resources/templates/index.html (works) (Does not include the header.html fragment)

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

Code from /resources/templates/admin/index.html (works) (Includes header.html as a fragment using Thymeleaf)

<!--/*/ <th:block th:include="/admin/fragments/header"></th:block> /*/-->

Code from /resources/templates/admin/user/admin/showuser.html (does not work) (Includes header.html as a fragment using Thymeleaf)

<!--/*/ <th:block th:include="/admin/fragments/header"></th:block> /*/-->

Not sure how to fix this. Thank you!


Solution

  • When your urls don't begin with a slash /, they attempt to resolve the current directory. For example:

    Page: /templates/index.html
    Css:  css/mycss.css
    
    The browser tries to locate /templates/css/mycss.css
    

    If the cases that don't work:

    Page: /templates/admin/user/admin/showuser.html
    Css:  css/mycss.css
    
    The browser tries to locate /templates/admin/user/admin/css/mycss.css
    

    If you want to make sure your css works everywhere, you need to make sure the link points consistently to the correct location. I'm guessing something like this would work:

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

    (Using Thymeleaf to add the context, and to make the path absolute.)