Spring Boot在某些页面中显示图像,但在其他页面中不显

问题描述 投票:0回答:1

我在Spring Boot + Thymeleaf应用程序中遇到了图像问题。

在阅读了很多修复后,我能够在我的某些应用程序页面中显示图像,但在其他页面中,图像不会显示。

我认为请求中的路径数量是多少。似乎请求/myaction呈现显示图像的页面,同时请求/myaction/other呈现不显示图像的页面。

在前者中,获取图像的成功请求是:

http://localhost:8080/myapp/images/logo.png

在后者中,获取图像的失败请求是:

http://localhost:8080/myapp/myaction/images/logo.png

我追加我的配置:

在我的WebMvcConfigurerAdapter实现中:

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

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

    registry.addResourceHandler("/**")
        .addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
}

控制器类:

@Controller
@RequestMapping(path="/myaction")
public class PagosController {
    @GetMapping(path="")
    public String show(Model model) {
    //...
    }

    @GetMapping(path="/other")
    public String show2(Model model) {
    //...
    }
}

在我的html模板中,我以这种方式加载图像:

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

logo.png

文件logo.png位于src/main/resources/static/images

我不知道为什么会这样。有关为什么在http://localhost:8080/myapp/myaction/images/logo.png要求图像的想法?提前致谢。

spring-boot thymeleaf
1个回答
1
投票

根据您的配置,图像可从根/获得。

所以你应该能够在任何页面中使用<img th:src="@{/images/logo.png}" />

© www.soinside.com 2019 - 2024. All rights reserved.