springboot FreeMarker 与 Velocity 对比

本文详细介绍了Freemarker和Velocity两种模板引擎在实际项目中的应用案例,包括配置环境、加载模板、数据传递及渲染过程。通过具体代码展示了如何根据业务需求选择合适的模板引擎进行消息通知的生成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Freemarker

    public void message(String mark, String type, Orderform orderform, String userId, String shouhouleixing) {
        if (shouhouleixing.equals("0")) {
            shouhouleixing = "仅退款";
        } else if (shouhouleixing.equals("1")) {
            shouhouleixing = "退货退款";
        } else if (shouhouleixing.equals("2")) {
            shouhouleixing = "退货退款";
        }
        Map<String, Object> map = new HashMap<>();
        StringWriter writer = new StringWriter();
        try {
   			Template templates = this.templateService.getByMark(mark);
            // File file=new File("./src/main/resources/templates/freemarker/index.ftl");
            String path1 = this.getClass().getClassLoader().getResource("").getPath() + "templates/freemarker/index.ftl";
            System.out.println(path1);
            PrintWriter pwrite = new PrintWriter(new OutputStreamWriter(new FileOutputStream(path1)));
            pwrite.print(templates.getContent());
            pwrite.flush();
            pwrite.close();
            FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
            Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
            //加载模板
            ClassTemplateLoader ctl = new ClassTemplateLoader(getClass(), "/templates/freemarker");
            //cfg.setDirectoryForTemplateLoading(new File("./src/main/resources/templates/freemarker"));
            TemplateLoader[] loaders = new TemplateLoader[]{ctl};
            MultiTemplateLoader mtl = new MultiTemplateLoader(loaders);
            cfg.setTemplateLoader(mtl);
            cfg.setDateFormat("yyyy-MM-dd HH:mm:ss");
            cfg.setEncoding(Locale.CHINA, "utf-8");
            cfg.setDefaultEncoding("utf-8");
            freeMarkerConfigurer.setConfiguration(cfg);
            Map<String, Object> context = new HashMap<>();
            context.put("send_time", new Date());
            context.put("shouhouleixing", shouhouleixing);
            context.put("orderForm", orderform);
            //获取模板
            Template template = cfg.getTemplate("index.ftl", "utf-8");
            template.process(context, writer);
            String content = writer.toString();

            String userName = "admin";
            IUser admin = this.userService.getUserByUserName(userName);
            Message msg = new Message();
            msg.setAddTime(new Date());
            msg.setContent(content);
            msg.setFromUserId(admin.getId());
            msg.setTitle(templates.getTitle());
            msg.setToUserId(Long.parseLong(userId));
            msg.setDeleteStatus(false);
            msg.setActivityType(0);
            msg.setStatus(0);
            msg.setReplyStatus(0);
            msg.setImportantStatus(false);
            if (type.equals("4")) {
                msg.setType(4);
            } else if (type.equals("5")) {
                msg.setType(5);
            }
            msg.setAuditStatus(1);
            msg.setActId(0);
            Integer save = this.messageService.save(msg);
            if (save > 0) {
                map.clear();
                map.put("message", "发送成功");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }

2.Velocity

private void launchedAfterSale_template(String mark,TuiKuanShouHou tuiKuanShouHou,String type) throws Exception {
       Template template = this.templateService.getObjByProperty("mark", mark);
        if (template.isOpen()){
            String path = System.getProperty("********") + "vm" + File.separator;
            PrintWriter pwrite = new PrintWriter(
                    new OutputStreamWriter(new FileOutputStream(path + "msg.vm", false), "UTF-8"));
            pwrite.print(template.getContent());
            pwrite.flush();
            pwrite.close();

            Properties p = new Properties();
            p.setProperty("file.resource.loader.path", System.getProperty("****") + "vm" + File.separator);
            p.setProperty("input.encoding", "UTF-8");
            p.setProperty("output.encoding", "UTF-8");
            Velocity.init(p);
            org.apache.velocity.Template blank = Velocity.getTemplate("msg.vm", "UTF-8");
            VelocityContext context = new VelocityContext();
            context.put("tuiKuanShouHou", tuiKuanShouHou);
            context.put("config", this.configService.getSysConfig());
            context.put("send_time", CommUtil.formatLongDate(new Date()));
            context.put("webPath", this.configService.getSysConfig().getAddress());
            StringWriter writer = new StringWriter();
            blank.merge(context, writer);

            String content = writer.toString();

            User admin = this.userService.getObjByProperty("userName", "admin");
            Message msg = new Message();
            msg.setAddTime(new Date());
            msg.setContent(content);
            msg.setFromUser(admin);
            msg.setTitle(template.getTitle());
            msg.setToUser(tuiKuanShouHou.getOrderForm().getStore().getUser());
            if (type.equals("4")){
                msg.setType(4);
            }else if (type.equals("5")){
                msg.setType(5);
            }
            msg.setAuditStatus(1);
            this.messageService.save(msg);
            CommUtil.deleteFile(path + "msg.vm");
            writer.flush();
            writer.close();
        }
    }

orderForm
    ${(send_time?string("yyyy-MM-dd HH:mm:ss"))!}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值