Search code examples
imagespring-bootthymeleafsrc

How to load corectly image in thymeleaf (spring boot project)?


I want to display the image after an error has occurred in my spring boot application. I read the documentation and tried several ways and it still doesn't work.

I read the documentation and tried several ways and it still doesn't work. I try this:

<img th:src="@{/images/error_image.jpg}"/>

and this:

<img src="../static/images/error_image.jpg" th:width="1000" th:src="@{/images/error_image.jpg}"/>

This is my project structure:

project structure

Hovering over a photo with ctrl directs me to a photo, so the path is good.

link

but all the time I see this:

error


Solution

  • [EDIT]

    The issue is with below controller method, you should provide mapping below.

    @GetMapping   // add mapping here
    public String showSignUpForm()
    {
        return "register";
    }
    

    Make sure static resource is not configured to different path other static/ at your end. If you have below configuration in application.properties, remove it.

    spring.resources.static-locations=
    

    Make sure you have below configurations in application.properties, spring boot's auto-configuration will set it to resource/static/

    spring.thymeleaf.enabled=true
    spring.thymeleaf.prefix=classpath:/templates/
    spring.thymeleaf.suffix=.html
    

    It's not an issue but still, change /images/ to images/

    <img src="../static/images/error_image.jpg" th:width="1000" th:src="@{images/error_image.jpg}"/>