Code Snippet

Just another Code Snippet site

[Velocity] Use Velocity programmatically


    @Autowired
    private VelocityConfigurer velocityConfig;

    @RequestMapping(value = { "test.html"}, method = RequestMethod.POST)
    @ResponseBody
    public String controllerMethod1() {
        VelocityEngine engine = velocityConfig.getVelocityEngine();

        Template template = engine.getTemplate("macro.vm");
        StringWriter writer = new StringWriter();

        VelocityContext context = new VelocityContext();

        context.put("key1", "value1");
        context.put("key2", "value2");

        template.merge(context, writer);

        return writer.toString();
    }

    @RequestMapping(value = "ajaxCall.html", method = RequestMethod.GET)
    public final String ajaxCall(final ModelMap modelMap, final HttpServletRequest request,
            final HttpServletResponse response, final Locale locale) throws Exception {

			// The output buffer
        ServletOutputStream output = response.getOutputStream();

        // The response buffer
        StringBuffer res = new StringBuffer(" ");

        // Call to the velocity template
        VelocityEngine ve = new VelocityEngine();
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        ve.init();

        /* next, get the Template */
        Template t = ve.getTemplate("TEMPLATE.vm");

        /* create a context and add data */
        VelocityContext context = new VelocityContext();
        context.put("anyService1", anyService1);
		context.put("anyService2", anyService2);
        context.put("locale", locale.getLanguage());
		context.put("data1", "DATA1");

        /* now render the template into a StringWriter */
        StringWriter writer = new StringWriter();
        t.merge(context, writer);
        res.append(writer.toString());

        output.print(res.toString());
        response.flushBuffer();
        return null;
    }


Comments are currently closed.