John Newell
John Newell

Reputation: 39

How to make Spring Boot see my images from resources

Hi I Have such images in resources/static and put them into my index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8"/>
    <title>Test</title>

</head>
<body>
<div>
    <form method="POST" enctype="multipart/form-data" action="/">
        <p>
            <img src="../static/image1.png" alt="Image 1"/>
            <img src="../static/image2.png" alt="Image 2"/>
            <tr>
                <td></td>
                <td><input type="submit" value="Test"/></td>
            </tr>
        </p>
    </form>
</div>

<div th:if="${success}">
    <img src="/static/result.png"/>
</div>

</body>
</html>

Then, in ResourceConfig

@Configuration
@EnableWebMvc
@ComponentScan
public class ResourceConfig extends WebMvcConfigurerAdapter {

    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
            "classpath:/META-INF/resources/", "classpath:/images/",
            "classpath:/static/", "classpath:/public/" };

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (!registry.hasMappingForPattern("/webjars/**")) {
            registry.addResourceHandler("/webjars/**").addResourceLocations(
                    "classpath:/META-INF/resources/webjars/");
        }
        if (!registry.hasMappingForPattern("/**")) {
            registry.addResourceHandler("/**").addResourceLocations(
                    CLASSPATH_RESOURCE_LOCATIONS);
        }
    }
}

The problem is, that application doesn't see my images. I've added resource handler, but it hasn't worked. The output is

Output

Upvotes: 2

Views: 8321

Answers (2)

Mr. Wrong
Mr. Wrong

Reputation: 510

This line in your html template

<div th:if="${success}">

makes me think you are using Thymeleaf as your template engine. If that is that case, you should use this to refer to static content:

<img th:src="@{/result.png}"}/>

if your png file is indeed in the root of your static folder.

Upvotes: 3

Console Engineer
Console Engineer

Reputation: 307

This @Override method addResourceHandlers shows Spring Framework where are all you static resources. So... your folder which contains images which are also a static resource must be under your root static resource handler. Set it like this and create this folder under WebContent folder in your project.

@Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/assets/**").addResourceLocations("/assets/");
    }

Upvotes: 5

Related Questions