JAVA 将数据库中的内容转化为HTML

来源:互联网 发布:挖掘社交网络 中文版 编辑:程序博客网 时间:2024/05/15 14:46
/**
* 将数据库中的内容转化为HTML
*data 存在数据库内字段的内容
*formId是数据库内该条信息的ID
*filePath是生成的html文件所存放的位置
* @param image
* @return
*/
public void formToHtml(String data, String FormId, String filePath) {
StringBuffer buf = new StringBuffer("");
buf.append("<html>");
buf
.append("<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />");
buf.append("<title>sdsds</title>");
buf.append("<head>");
buf.append("</head>");
buf.append("<body>");
buf.append(data);
buf.append("</body>");
buf.append("</html>");
String fileName = filePath + FormId + ".html";
ObjectOutputStream objOutputStream;
try {
objOutputStream = new ObjectOutputStream(new FileOutputStream(
new File(fileName)));
objOutputStream.writeObject(buf.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}


/**
* 将数据库中的内容转化为HTML
*vmBasePath vm模板所存放的位置 例如D:\\projectPath\\attach\\html
*vmTempName vm模板的名称
*dataContext 存在数据库内字段的内容
*HtmlFilePath 生成的html所存放的路径 例如:"D:\\projectPath\\attach\\html\\test.html"
* @param image
* @return
*/
public String dataToHtml(String vmBasePath, String vmTempName,
String dataContext, String HtmlFilePath) throws Exception {
// 初始化并取得Velocity引擎
VelocityEngine ve = new VelocityEngine();
// 设置路径
Properties properties = new Properties();
String basePath = vmBasePath;
// String basePath = "D:\\projectPath\\attach\\html";
properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, basePath);
ve.init(properties);


// 取得velocity的模版
// Template t = ve.getTemplate("104.vm");
Template t = ve.getTemplate(vmTempName);
// 取得velocity的上下文context
VelocityContext context = new VelocityContext();


// 把数据填入上下文
// context.put("name", "Liang");
context.put("name", dataContext);


// 输出流
StringWriter writer = new StringWriter();


// 转换输出
t.merge(context, writer);
// PrintWriter filewriter = new PrintWriter(new
// FileOutputStream("D:\\projectPath\\attach\\html\\test.html"), true);
FileOutputStream fos = new FileOutputStream(HtmlFilePath);
PrintWriter filewriter = new PrintWriter(fos, true);
filewriter.println(writer.toString());


filewriter.flush();
filewriter.close();
fos.flush();
fos.close();
System.out.println("输出已经完成!");


return "success";
}
原创粉丝点击