Velocity模板路径的配置

woaini 2015-03-31

我们一般用 Velocity作为模板进行页面的配置,之所以这样做是因为很简单。可以通过ajax可以返回已打算html代码,把这些html代码放到指定的div当中,实现异步刷新。这样不必花大量时间去解析json代码。

ajax 前台页面我不写了,直接写后台的代码:

/**
 * Mainbo.com Inc.
 * Copyright (c) 2015-2017 All Rights Reserved.
 */
package com.mainbo.jy.lecturerecords.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mainbo.jy.comment.bo.CommentInfo;
import com.mainbo.jy.comment.service.CommentInfoService;
import com.mainbo.jy.common.page.PageList;
import com.mainbo.jy.common.web.controller.AbstractController;

/**
 * 听课记录控制器接口
 * <pre>
 *
 * </pre>
 *
 * @author Generate Tools
 * @version $Id: LectureRecords.java, v 1.0 2015-03-30 Generate Tools Exp $
 */
@Controller
@RequestMapping("/jy/lecturerecords")
public class LectureRecordsController extends AbstractController{
//map是装在数据的,key值可以直接在模板中使用
	public String aa(HttpServletRequest request,Map<String,Object> map) {
		Properties p = new Properties();
//第一种:文件路径的方式,注意一定是绝对路径
		String s=request.getSession().getServletContext().getRealPath("/")+File.separator+"WEB-INF";//模板都放在web-info下
		p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, s);

//第二种:通过类路径加载模板,模板都放在classpath下,也就是src下面
 p.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
			 
        VelocityEngine ve = new VelocityEngine(p);//生成模板引擎
        ve.init();
        /* next, get the Template */
        Template t = ve.getTemplate("hellosite.html");
        /* create a context and add data */
        VelocityContext context = new VelocityContext();
        context.put("name", "DingDangXiaoMa");
        context.put("site", "http://www.sun.com");
        
        Set<String> keys=map.keySet();
        for (String key : keys) {
        	context.put(key, map.get(key));
		}
        /* now render the template into a StringWriter */
        StringWriter writer = new StringWriter();
        t.merge(context, writer);
        /* show the World */
        System.out.println(writer.toString());
        
        return writer.toString();//得到模板上面所有的文本,这样就可以直接通过打印到前段页面了
	}
}

/**
	 * 返回字符串UTF-8编码
	 * @param response
	 * @param result 字符串内容。text/plain
	 * @throws Exception
	 */
	protected final void writeText(HttpServletResponse response, String result) throws Exception {
		response.setContentType("text/plain; charset=UTF-8");
		response.setCharacterEncoding("UTF-8");

		PrintWriter out = response.getWriter();
		out.write(result);
		out.close();
	}

	/**
	 * 用于导出、下载XML文件
	 * @param response
	 * @param result 字符串内容。
	 * @param fileName 下载的文件名
	 * @throws Exception
	 */
	protected final void downloadXML(HttpServletResponse response, String result, String fileName) throws Exception {
		// 避免过滤器赋值导致无法下载
		response.setHeader("Cache-Control", "");

		response.setContentType("application/x-msdownload");
		response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
		OutputStream out = response.getOutputStream();
		out.write(result.getBytes("UTF-8"));
		out.flush();
		out.close();
}

模板:
<div>
Hello $name! Welcome to $site world!
$data
#foreach($product in $data.datalist) <!--传过来的map的key值-->
<li>$product.username:$product.content</li> 
#end
</div>

相关推荐

lionelf / 0评论 2020-07-28