You need to understand how HTTP works. When the browser loads the page by URL
http://some.host/myWebApp/foo/bar.html
and the HTML page contains
<img src="images/test.png"/>
the browser will send a second HTTP request to the server to upload the image. The image URL, since the path is relative, will be http://some.host/myWebApp/foo/images/test.png . Note that the absolute path is made up of the current "directory" of the page, combined with the relative path of the image. The path of the server-side JSP or thimeleaf template is completely irrelevant here. Important is the URL of the page displayed in the address bar of the browser. This URL in a typical Spring MVC application is the URL of the controller to which the original request was sent.
If the image path is absolute:
<img src="/myWebApp/images/test.png"/>
then the browser will send a second request to the URL http://some.host/myWebApp/images/test.png . The browser starts at the root of the web server and concatenates the absolute path.
In order to be able to link to an image, that is, the URL of the page, an absolute path is thus preferred and easier to use.
In the above example, /myWebApp is the application context path, which is usually not required by the hard code in the path, because it can change. Fortunately, according to the documentation of the thymeleaf , the thymeleaf understands this and provides syntax for context-sensitive paths, which thus transforms paths such as /myWebApp/images/test.png to /myWebApp/images/test.png . So your image should look like
<img th:src="@{/images/test.png}"/>
(I never used thimeleaf, but this is what I deduced from the documentation).
And the image test.png should be in the images folder located under the root of webapp.
Jb nizet
source share