【问题标题】:Problem loading images in Spring Boot / FreeMarker在 Spring Boot / FreeMarker 中加载图像时出现问题
【发布时间】:2019-05-14 23:27:35
【问题描述】:

我一直在开发一个演示应用程序,以了解 Spring Boot 的 FreeMarker 模板。我喜欢 FreeMarker 模板,但我无法在网页上显示图像。就图像和图像目录的位置而言,我已经尝试了所有我能想到的方法,但没有任何效果。我希望有人能指出我的问题,因为如果我不能解决这个问题,我就不能使用 FreeMarker。

我的项目目录如下:

我使用的是 Spring Boot 2.1.1。

我使用 Bootstrap 进行页面格式化。这是引用图像的 Bootstrap/HTML:

		<div class="row">
		    <div class="col-md-12">
			    <img src="/img/snowy_egret_thumb.jpg" />
		    </div>
	    </div> <!-- row -->
      

我认为也许我在 FreeMarker 配置中遗漏了一些东西,但我没有找到任何东西。我的 FreeMarker 配置类如下所示:

@Configuration
@EnableWebMvc
@ComponentScan({"cognitodemo.freemarker"})
public class AppConfig implements WebMvcConfigurer,         
ApplicationContextAware {
   private ApplicationContext applicationContext = null;


   @Override
   public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
      this.applicationContext = applicationContext;
  }


@Bean
@Description("FreeMarker View Resolver")
public FreeMarkerViewResolver viewResolver(){
    FreeMarkerViewResolver viewResolver = new FreeMarkerViewResolver();
    viewResolver.setCache(false);
    viewResolver.setPrefix("");
    viewResolver.setSuffix(".html");
    return viewResolver;
}

@Bean
public FreeMarkerConfigurer freemarkerConfig() {
    FreeMarkerConfigurer freeMarkerConfigurer = new 
FreeMarkerConfigurer();
    freeMarkerConfigurer.setTemplateLoaderPath("/WEB-INF/views/");
    return freeMarkerConfigurer;
}

}

当我使用 Spring Boot 运行应用程序时,我收到以下警告:

WARN[0;39m [35m13617[0;39m [2m---[0;39m [2m[restartedMain][0;39m [36mo.sbafFreeMarkerAutoConfiguration [0;39m [2m:[0;39m 找不到模板位置:[classpath:/templates/](请添加一些模板,检查您的 FreeMarker 配置,或设置 spring.freemarker.checkTemplateLocation=false)

但是,应用程序页面可以正常工作。只是图片加载不出来。

任何帮助将不胜感激。非常感谢。

【问题讨论】:

    标签: java spring-boot freemarker


    【解决方案1】:

    经过多次修改后,我终于可以加载图像了。不同之处在于向配置类 AppConfig 添加了一个 addResourceHandler() 方法。该方法如下图所示:

    public void addResourceHandlers(ResourceHandlerRegistry registry) {  
        registry.addResourceHandler("/img/**")
                .addResourceLocations("/img/")
                .addResourceLocations("classpath:/img/"); 
     }
    

    我还移动了图像目录,使其位于 webapp 下。如下所示:

    我也加了一行

    spring.freemarker.checkTemplateLocation: false
    

    到我的 application.properties 文件。

    请注意,resources 目录仍然在 views 目录下。我不认为这是理想的,因为我宁愿将它移动到与 img 目录相同的级别。我试图为此向资源处理程序添加代码,但没有成功。我有什么工作,所以我要这样做。

    我已经在 GitHub 上发布了这个应用程序。见https://github.com/IanLKaplan/CognitoDemoFreeMarker

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-13
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      相关资源
      最近更新 更多