2

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!

1 Answer 1

3

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

You are absolutely 100% correct with the Thymeleaf solution. After adding it to all my links everything works great. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.