springboot采用FreeMarker模板集成应用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/songhaifengshuaige/article/details/54136984
本案例继续在之前的章节的工程集成上进行,再次 添加Freemarker作为视图模板。

1、第一步仍然是在POM文件中加入对应的依赖:
<!-- freemarker 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

2、采用默认的路径存放模板视图(默认参数可直接查看源码FreeMarkerProperties、FreeMarkerTemplateAvailabilityProvider):

<!DOCTYPE>
<html>
<head>
<title>
freemark
</title>
</head>
<body>
<h1>Hello ${name} from resource freemark!</h1>
</body>
3、修改处理home请求的方法:
@RequestMapping(value = "/{type}/home", method = RequestMethod.GET)
public ModelAndView showJspHome(@PathVariable(value="type") String type) {
ModelAndView model = new ModelAndView();
model.addObject("name", "帅帅");
if("jsp".equals(type)){
//加入类型路径,从而可以通过viewNames来判断选择视图对应的解析器
model.setViewName("jsp/home");
}else if("thymeleaf".equals(type)){
model.setViewName("thymeleaf/home");
}else if("ftl".equals(type)){
model.setViewName("ftl/home");
}else{
model.setViewName("error");
}
return model;
}
仅仅添加ftl的处理

4、请求验证:

验证成功,且此时之前定义的jsp&thymeleaf视图同样可以兼容同时使用。

5、同样,我们如果需要自定义模板路径呢,特别是部署在自定义容器中时,如何实现呢。通过验证有多种实现方式,下面一一罗列:

<!DOCTYPE>
<html>
<head>
<title>
freemark
</title>
</head>
<body>
<h1>Hello ${name} from WEB-INF freemark!</h1>
</body>

5.1、首先最简单的方式,直接修改application.properties配置文件,添加
#freemark
spring.freemarker.template-loader-path=/WEB-INF/
启动服务验证:


5.2、通过xml方式,在applicationContext.xml中添加如下配置:
<!-- 设置freeMarker的配置文件路径 -->
<bean id="freemarkerConfiguration"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:freemarker.properties"/>
</bean>
<!-- 配置freeMarker的模板路径 -->
<bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="freemarkerSettings" ref="freemarkerConfiguration"/>
<property name="templateLoaderPath" value="/WEB-INF/" />
<property name="defaultEncoding" value="UTF-8" />
<property name="freemarkerVariables">
<map>
<entry key="xml_escape" value-ref="fmXmlEscape" />
</map>
</property>
</bean>
<bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape" />

其中对应的freemarker.properties:
template_update_delay=3600
tag_syntax=auto_detect
default_encoding=UTF-8
output_encoding=UTF-8
locale=zh_CN
date_format=yyyy-MM-dd
time_format=HH:mm:ss
datetime_format=yyyy-MM-dd HH:mm:ss
number_format=#,###.##
classic_compatible=true
#ignore,debug,html_debug,rethrow
template_exception_handler=html_debug

此方式,其实来源于springmvc中之前采用的xml配置方式,此时通过@ImportResource注解加载xml配置。

5.3、后面的几种方式均是修改之前定义的视图解析器JAVA配置类,第一种:
/**
* 主要配置多视图实现的视图解析器相关bean实例
* @author song
*
*/
@Configuration
public class ViewResolverConfiguration {
@Bean
public InternalResourceViewResolver getJspViewResolver(){
InternalResourceViewResolver jspViewResolver=new InternalResourceViewResolver();
jspViewResolver.setPrefix("/WEB-INF/");
jspViewResolver.setSuffix(".jsp");
jspViewResolver.setViewClass(JstlView.class);
//通过ViewNames属性来实现,通过请求中返回的视图名称匹配其采用哪个对应的视图解析器处理,从而找到对应prefix下的页面
jspViewResolver.setViewNames("jsp/*");
jspViewResolver.setOrder(10);
//开发时不启用缓存,改动即可生效
jspViewResolver.setCache(false);
return jspViewResolver;
}
@Bean
public TemplateResolver templateResolver(){
TemplateResolver templateResolver=new ServletContextTemplateResolver();
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML5");
templateResolver.setOrder(0);
templateResolver.setCacheable(false);
templateResolver.setCharacterEncoding("UTF-8");
return templateResolver;
}
@Bean
public SpringTemplateEngine templateEngine(){
SpringTemplateEngine templateEngine=new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
return templateEngine;
}
@Bean
public ThymeleafViewResolver thymeleafViewResolver(){
ThymeleafViewResolver thymeleafViewResolver=new ThymeleafViewResolver();
thymeleafViewResolver.setTemplateEngine(templateEngine());
thymeleafViewResolver.setViewClass(ThymeleafView.class);
thymeleafViewResolver.setViewNames(new String[]{"thymeleaf/*"});
thymeleafViewResolver.setCharacterEncoding("UTF-8");
//开发时不启用缓存,改动即可生效
thymeleafViewResolver.setCache(false);
return thymeleafViewResolver;
}
@Bean
public FreeMarkerConfigurer freemarkerConfig() throws IOException, TemplateException {
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
configurer.setTemplateLoaderPath("/WEB-INF/");
return configurer;
}

@Bean
@ConditionalOnProperty(name = "spring.freemarker.enabled", matchIfMissing = true)
public FreeMarkerViewResolver getFreemarkViewResolver() {
FreeMarkerViewResolver freeMarkerViewResolver = new FreeMarkerViewResolver();
freeMarkerViewResolver.setCache(false);
freeMarkerViewResolver.setSuffix(".ftl");
freeMarkerViewResolver.setContentType("text/html; charset=UTF-8");
freeMarkerViewResolver.setOrder(1);
freeMarkerViewResolver.setViewNames("ftl/*");
freeMarkerViewResolver.setViewClass(FreeMarkerView.class);
return freeMarkerViewResolver;
}

}
其中getFreemarkViewResolver()方法在后续的两种方式中同样需要配置,差异主要体现在 freemarkerConfig() 。

5.4、将上述的freemarkerConfig()方法替换配置如下:
@Autowired
protected FreeMarkerProperties properties;

@Bean
@ConditionalOnMissingBean({ FreeMarkerConfig.class })
public FreeMarkerConfigurer freemarkerConfig() {
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
applyProperties(configurer);
return configurer;
}
protected void applyProperties(FreeMarkerConfigurationFactory factory) {
properties.setTemplateLoaderPath("/WEB-INF/");
factory.setTemplateLoaderPaths(this.properties.getTemplateLoaderPath());
factory.setPreferFileSystemAccess(this.properties.isPreferFileSystemAccess());
factory.setDefaultEncoding(this.properties.getCharsetName());
Properties settings = new Properties();
settings.putAll(this.properties.getSettings());
factory.setFreemarkerSettings(settings);
}
此方式主要参考源码FreeMarkerAutoConfiguration实现。通过此方式能够结合系统默认的属性以及自定义属性。此方式同样能够看到一些xml中<property name="freemarkerSettings" ref="freemarkerConfiguration"/>的对应JAVA实现。

6、在XML中还有一个XmlEscape的bean实例,在JAVA配置中通过如下即可实现:
@Bean(name ="freemarkerConfig")
public FreeMarkerConfigurer freemarkerConfig() {
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
configurer.setTemplateLoaderPath("/WEB-INF/");
Map<String, Object> map = new HashMap<>();
map.put("xml_escape", new XmlEscape());
configurer.setFreemarkerVariables(map);
return configurer;
}

以上第5步采用4中方式实现,其实原理基本一致。均能够得到如下期望结果(并且打包成war部署常规容器同样验证可行)

阅读更多
换一批

没有更多推荐了,返回首页