SpringBoot读取并传参到resource下的html页面,并将html页面作为一个参数返回

前言

之前做前后端不分离项目(例如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());
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值