在spring-boot应用程序中,如何从本地文件夹而不是资源文件夹将静态内容(例如图像)加载到jsp中?

时间:2019-10-14 23:30:52

标签: spring-boot static

我正在尝试将图像从桌面上的本地系统文件夹加载到jsp页面中。但是在spring-boot中,只有将映像放入资源文件夹后,映像才会被加载。如何解决此问题?

我已经尝试过https://www.baeldung.com/spring-mvc-static-resources中的以下代码,但是没有运气。

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry
      .addResourceHandler("/files/**")
      .addResourceLocations("file:/opt/files/");
 }

我说错了

javax.servlet.ServletException: Circular view path [error]: would dispatch back to the current handler URL [/error] again. Check your ViewResolver setup!

我的文件夹设置如下: 只有资源/ static / img中的图像被加载到jsp中,我希望加载桌面上存在的图像。请帮忙。

enter image description here

2 个答案:

答案 0 :(得分:1)

您需要配置更多。首先是资源处理程序,然后是viewresolver

@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/test/**")
                .addResourceLocations("file:D://tmp2/");
    }

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/jsp/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
}

这是win10中的一个运行示例,您需要相应地更改路径addResourceLocations。在这里您可以找到项目https://github.com/ozkanpakdil/spring-examples/tree/master/spring-boot-jsp,不要忘记签出pom.xml。为了在Spring Boot中运行jsp。需要一些额外的提供的依赖关系,在其中嵌入碧玉。

答案 1 :(得分:1)

我找到了解决方法。这可以通过使用application.properties文件中的属性来完成

spring.resources.static-locations=file:PATH OF THE FOLDER

例如,如果项目文件夹位于桌面上,则将是这样

spring.resources.static-locations=file:/Users/sandeepamarnath/Desktop/

在HTML或Jsp页面中,可以为静态文件(如CSS,JS和图像)提供完整的路径