首页 > 编程学习 > Velocity:文本模板渲染
2015四月24

Velocity:文本模板渲染

public String getTemplateStr(String template, Map<String, String> para) {
        StringWriter writer = new StringWriter();
        try {
            RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices();
            StringReader reader = new StringReader(template);
            SimpleNode node = runtimeServices.parse(reader, "Template name");
            Template t = new Template();
            t.setRuntimeServices(runtimeServices);
            t.setData(node);
            t.initDocument();
            VelocityContext context = new VelocityContext();
            if (para.size() > 0) {
                for (String key : para.keySet()) {
                    context.put(key, para.get(key));
                }
            }
            t.merge(context, writer);
        } catch (Exception e) {
            throw new RuntimeException("Error commiting transaction! cause:"+ e.getMessage());
        }
        return writer.toString();
    }
    
    @At("/form")
    @Ok("vm:template.private.test")
    public void form(HttpServletRequest req, HttpServletResponse resp) {
        Map<String, Object> formParams = new HashMap<String, Object>();
        formParams.put("formKey", "form/waizhibiaodan/01/01.form");
        int timeout = 60 * 1000;
        String str = Http.post("http://127.0.0.1/test/getFormKey", formParams, timeout);
        NutMap map = Json.fromJson(NutMap.class, str);
        String formData = map.getString("data");
        Map<String, String> params = new HashMap<String, String>();
        params.put("startDate", "2015-04-21");
        params.put("endDate", "2015-04-25");
        req.setAttribute("formData", getTemplateStr(formData, params));
    }

Loading

本文地址:https://wizzer.cn/archives/3122 , 转载请保留.

本文目前尚无任何评论.

发表评论