我一直在研究一个演示应用程序,以了解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)
但是,应用程序页面正常工作。只是图像无法加载。
任何帮助将不胜感激。预先非常感谢。
答案 0 :(得分:0)
经过多次黑客攻击,我终于可以加载图像了。有所不同的是在配置类AppConfig中添加了addResourceHandler()方法。此方法如下所示:
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/img/**")
.addResourceLocations("/img/")
.addResourceLocations("classpath:/img/");
}
我还移动了图像目录,使其位于webapp下。如下所示:
我还添加了一行
spring.freemarker.checkTemplateLocation: false
到我的application.properties文件。
请注意,资源目录仍位于views目录下。我认为这并不理想,因为我希望将其移至与img目录相同的级别。我试图为此添加代码到资源处理程序,但没有成功。我所拥有的有效,所以我将继续进行下去。
我已经在GitHub上发布了此应用程序。参见https://github.com/IanLKaplan/CognitoDemoFreeMarker