文章标签 ‘velocity’
20154 月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));
    }
20134 月11

Velocity遍历hashtable输出key和value

#foreach($key in $yygldwlx.keySet())

key:$!key —>$!yygldwlx.get(“$!key”)

#end