前言
之前做前后端不分离项目(例如SpringMVC)的时候,固化了思维,只能返回一个页面。但是项目需求是将页面作为一个参数返回,所以就有了下面的步骤。
思路
用模板引擎,比如velocity、thymeleaf等(后端模板)。
步骤
(1)pom文件中引入jar包
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
</dependency>
(2)在resource下创建一个velocity文件(里面写的就是html代码)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<meta charset="UTF-8">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<p style=";text-align:center;line-height:150%">
<strong><span style="font-family: 宋体;line-height: 150%;font-size: 19px"><span
style="font-family:宋体">《协议说明》</span></span></strong>
</p>
<p style="text-indent: 28px">
<span style="font-family:宋体">本人(姓名:$!creditCustomer)</span>
</p>
</body>
</html>
(3)创建velocity工具类,读取velocity文件和入参的内容
public class VelocityTemplateUtils {
private static final VelocityEngine VE = new VelocityEngine();
static {
//初始化参数
Properties properties=new Properties();
//设置velocity资源加载方式为class
properties.setProperty("resource.loader", "class");
//设置velocity资源加载方式为file时的处理类
properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
VE.init(properties);
}
public static String get(String filePath, Map<String, Object> data) {
//取得velocity的模版
Template t = VE.getTemplate(filePath, "UTF-8");
//取得velocity的上下文context
VelocityContext context = new VelocityContext();
if (!CollectionUtils.isEmpty(data)) {
for (String key : data.keySet()) {
context.put(key, data.get(key));
}
}
StringWriter writer = new StringWriter();
//把数据填入上下文
t.merge(context, writer);
return writer.toString();
}
}
编写方法调用
@Override
public String creditAgreement(String customerName) {
//传参
Map<String, Object> map = Maps.newHashMap();
map.put("creditCustomer", customerName);
map.put("year", LocalDate.now().getYear());
map.put("month", LocalDate.now().getMonthValue());
map.put("date", LocalDate.now().getDayOfMonth());
String result = null;
try {
//引用步骤(3)的工具类,完成传值。
result = VelocityTemplateUtils.get("/template.vm", map);
} catch (Exception e) {
e.printStackTrace();
}
//编码后返回
return Base64.getEncoder().encodeToString(result.getBytes());
}