1.环境搭建
创建maven工程并导入Freemarker的maven坐标
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
<!-- 导入配置文件处理器,配置文件进行绑定就会有提示,需要重启 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
2.创建模板文件(分为properties、xml配置文件和yml配置两种选择其一就可)
Freemarker的模板文件后缀可一般建议为ftl
(1)properties、xml配置文件
(1)在工程中resource下创建属性文件freemarker.properties。
通过配置可以指定将静态HTML页面生成的目录位置
out_put_path=D:/ideaProjects/health_parent/health_mobile/src/main/webapp/pages
2)在工程的Spring配置文件中配置.。freeMarkerConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="freeMarkerConfig"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<!--指定模板文件所在目录-->
<property name="templateLoaderPath" value="/templates/"/>
<!--指定字符集-->
<property name="defaultEncoding" value="UTF-8"/>
</bean>
<context:property-placeholder location="classpath:freemarker.properties"/>
</beans>
(2)yml配置文件
创建配置类,定义生成的静态文件的保存路径
package com.itheima.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Data
@Component
@Configuration
@ConfigurationProperties(prefix = "spring.freemarker")
public class FreemarkerProperties {
//生成的静态文件的保存路径
private String out_put_path;
}
yml内的配置
spring:
freemarker:
charset: UTF-8
check-template-location: false
template-loader-path: classpath:/templates/
out-put-path: "E:/LZHJAVA4_projects/bxg-health-parent/bxg-health-mobile/src/main/resources/mobile/pages"
3.生成静态页面
@PropertySource(value = "classpath:freemarker.properties")
@Service
public class SetmealServiceImpl implements SetmealService {
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
@Value("${out_put_path}")//从属性文件读取输出目录的路径
private String outPutPath;
/**
* 新增体检套餐
*
* @param setmeal
* @param checkgroupIds
*/
@Transactional
@Override
public void add(Setmeal setmeal, List<Integer> checkgroupIds) {
//1.新增setmeal表
setmealDao.add(setmeal);
String fileName = setmeal.getImg();
redisTemplate.opsForSet().add(RedisConstant.SETMEAL_PIC_DB_RESOURCES, fileName);
//2.新增setmeal_group关系表
Integer setmealId = setmeal.getId();
if (checkgroupIds != null && checkgroupIds.size() > 0) {
for (Integer checkgroupId : checkgroupIds) {
setmealGroupDao.add(setmealId, checkgroupId);
}
}
//调用方法
generateMobileStaticHtml();
}
}
生成静态页面
//生成静态页面
public void generateMobileStaticHtml() {
//准备模板文件中所需的数据
List<Setmeal> setmealList = setmealDao.getSetmeal();
//生成套餐列表静态页面
generateMobileSetmealListHtml(setmealList);
//生成套餐详情静态页面(多个)
generateMobileSetmealDetailHtml(setmealList);
}
静态页面生成通用方法
/**
* 用于生成静态页面
*
* @param templateName
* @param htmlPageName
* @param dataMap
*/
public void generateHtml(String templateName, String htmlPageName, Map<String, Object> dataMap) {
// 第一步:创建一个Configuration对象,直接new一个对象。构造方法的参数就是FreeMarker对于的版本号。
Configuration configuration = freeMarkerConfigurer.getConfiguration();
Writer out = null;
try {
// 加载模版文件
Template template = configuration.getTemplate(templateName);
// 生成数据
File docFile = new File(outPutPath + "/" + htmlPageName);
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
// 输出文件
template.process(dataMap,out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != out) {
out.flush();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
//生成套餐列表静态页面
public void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
Map<String, Object> dataMap = new HashMap<String, Object>();
dataMap.put("setmealList", setmealList);
this.generateHtml("mobile_setmeal.ftl", "m_setmeal.html", dataMap);
}
//生成套餐详情静态页面(多个)
//生成套餐详情静态页面(多个)
public void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
for (Setmeal setmeal : setmealList) {
Map<String, Object> dataMap = new HashMap<String, Object>();
dataMap.put("setmeal", setmealDao.findByIdB(setmeal.getId()));
this.generateHtml("mobile_setmeal_detail.ftl",
"setmeal_detail_"+setmeal.getId()+".html",
dataMap);
}
}
参考配置详情
注意:
spring.mvc.static-path-pattern=/** 不要写成 classpath:/**\
## Freemarker 配置
## 文件配置路径
spring.freemarker.template-loader-path=classpath:/templates/
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true
spring.freemarker.request-context-attribute=request
spring.freemarker.suffix=.ftl
spring.mvc.static-path-pattern=/**
yaml:
spring:
## Freemarker 配置
freemarker:
cache: false
charset: UTF-8
check-template-location: true
content-type: text/html
expose-request-attributes: true
expose-session-attributes: true
request-context-attribute: request
suffix: .ftl
template-loader-path: classpath:/templates/
mvc:
static-path-pattern: /**
#配置freemarker详解
#spring.freemarker.allow-request-override=false
# Set whether HttpServletRequest attributes are allowed to override (hide) controller generated model attributes of the same name.
#设置是否允许HttpServletRequest属性覆盖(隐藏)控制器生成的同名模型属性。
#spring.freemarker.allow-session-override=false
# Set whether HttpSession attributes are allowed to override (hide) controller generated model attributes of the same name.
#设置是否允许HttpSession属性覆盖(隐藏)控制器生成的同名模型属性。
#spring.freemarker.cache=false
# Enable template caching.
#启用模板缓存。
#spring.freemarker.charset=UTF-8
# Template encoding.
#设置编码格式
#spring.freemarker.check-template-location=true
# Check that the templates location exists.
#检查模板位置是否存在。
#spring.freemarker.content-type=text/html
# Content-Type value.
#内容类型值
#spring.freemarker.enabled=true
# Enable MVC view resolution for this technology.
#为这种技术启用MVC视图解决方案。
#spring.freemarker.expose-request-attributes=false
# Set whether all request attributes should be added to the model prior to merging with the template.
#设置是否应该在与模板合并之前将所有请求属性添加到模型中。
#spring.freemarker.expose-session-attributes=false
# Set whether all HttpSession attributes should be added to the model prior to merging with the template.
#设置是否在与模板合并之前将所有HttpSession属性添加到模型中。
#spring.freemarker.expose-spring-macro-helpers=true
# Set whether to expose a RequestContext for use by Spring's macro library, under the name "springMacroRequestContext".
#设置是否公开RequestContext供Spring宏库使用,名称为“SpringMacroRequestContext”。
#spring.freemarker.prefer-file-system-access=true
# Prefer file system access for template loading. File system access enables hot detection of template changes.
#更喜欢文件系统访问模板加载。文件系统访问允许对模板更改进行热检测。
#spring.freemarker.prefix=
# Prefix that gets prepended to view names when building a URL.
#前缀,用于在构建URL时查看名称
#spring.freemarker.request-context-attribute=
# Name of the RequestContext attribute for all views.
#所有视图的RequestContext属性的名称。
#spring.freemarker.settings.*=
# Well-known FreeMarker keys which will be passed to FreeMarker's Configuration.
#众所周知的FreeMarker密钥将传递给FreeMarker的配置。
#spring.freemarker.suffix=
# Suffix that gets appended to view names when building a URL.
#后缀,该后缀用于在构建URL时查看名称。
#spring.freemarker.template-loader-path=classpath:/templates/
# Comma-separated list of template paths.
#以逗号分隔的模板路径列表。
#spring.freemarker.view-names=
# White list of view names that can be resolved.
#可以解析的视图名称的白列表。