Warm tip: This article is reproduced from stackoverflow.com, please click
spring-boot spring-mvc Thymeleaf

Thymeleaf, Spring Boot 2: invalid path to resources when handle error

发布于 2020-04-23 16:00:19

I have a basic SpringBoot Thymeleaf app with default settings:

id 'org.springframework.boot' version '2.2.2.RELEASE'
compile("org.springframework.boot:spring-boot-starter-web")
compile("org.springframework.boot:spring-boot-starter-thymeleaf")
compile("nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect")

Problem is in invalid path to resources in some cases when handle error and as a result app can't show resoures (css/js/image) on page.

Path to resoures: /src/main/resources/static/assets

For logging path I made RequestInterceptor. It logs the part of request's URL.

I describe 4 cases. Paths and logs in interceptor:

  1. calling the correct path /home - all work fine
[09:02:48.759][INFO] /home
[09:02:48.759][INFO] /assets/img/java60.png
  1. calling the incorrect path /first (expect 404 error) - all work fine
[09:02:48.759][INFO] /first
[09:02:48.777][INFO] /error
[09:02:49.589][INFO] /assets/css/simple.css
[09:02:49.590][INFO] /assets/img/notFound.png
[09:02:49.715][INFO] /favicon.ico
  1. calling the incorrect path /first/second (expect 404 error) - unexpected behavior
[09:03:00.390][INFO] /first/second
[09:03:00.395][INFO] /error
[09:03:00.422][INFO] /first/assets/css/simple.css
[09:03:00.422][INFO] /first/assets/img/notFound.png
[09:03:00.426][INFO] /error
[09:03:00.426][INFO] /error
  1. calling the incorrect path /first/second/third (expect 404 error) - unexpected behavior
[09:39:06.404][INFO] /first/second/third
[09:39:06.409][INFO] /error
[09:39:06.441][INFO] /first/second/assets/css/simple.css
[09:39:06.441][INFO] /first/second/assets/img/notFound.png
[09:39:06.446][INFO] /error
[09:39:06.446][INFO] /error

In third and fourth cases app redirects to error and set up path (request's URL + path to assets on page). Why spring make invalid path to resources in 3 and 4 cases?

The complete source code is available over on Github

Questioner
makson
Viewed
81
MohamedSanaulla 2020-02-12 13:51

You have to link resources using an absolute path. Currently, you are linking using relative paths like <link rel="stylesheet" th:href="@{assets/css/simple.css}">.

Try to update your resources to:

<link rel="stylesheet" th:href="@{/assets/css/simple.css}">
<img th:src="@{/assets/img/java60.png}" sizes="16x16" alt="love">