How to load an image in spring boot with thymeleaf?

Viewed 1313

I want to simply display an image in an html file in a spring boot application.

But for some reason I can't get it to work in one specific application.

I say "one specific application" because I could get it to work in the exact same way in another application.

This is how it is:

Placed tempLogo.jpg in the folder /src/main/resources/static/images.

In src/main/resources/templates/home.html:

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

None of this worked in app1. All of these worked in app2 with the same code and paths.

Interesting enough, in app1 I can successfully access .css and .js files in the /static folder like this:

<link rel="stylesheet" type="text/css" href="/css/styles.css"/>
<script src="/scripts/scripts.js"></script>

These are under:

/src/main/resources/static/css

/src/main/resources/static/scripts

Not sure what's going on since, like I said, in app2 that has the same exact path and code it did work.

1 Answers

After some digging found out that the issue was that Spring security was not enabled for the images folder. So added web.ignoring().antMatchers("/images/**"); in the configure method of the class that extends WebSecurityConfigurerAdapter and it worked.

@Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/css/**");      
        web.ignoring().antMatchers("/scripts/**");
        web.ignoring().antMatchers("/images/**");
    }
Related