动态内容生成HTML.好处大家应该在网上都略微了解了些.下面我向大家介绍一下,如何使用Velocity生成HTML.
关于中文问题,我已经在另一篇里介绍过了,该如何设置Velocity的编码,这里就不再重复了.
代码见下:
- String path = request.getSession().getServletContext().getRealPath("/");
- Properties p = new Properties();
- p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, "");
- p.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
- p.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
- p.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
- try {
- Velocity.init(p);
- Template template = Velocity.getTemplate(path
- + "WEB-INF\\velocity\\模版文件名");
- VelocityContext context = new VelocityContext();
- context.put("insurance", insurance);
- FileOutputStream fos = new FileOutputStream(path + "aaa" + ".html");
- BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
- fos, "UTF-8"));//设置写入的文件编码,解决中文问题
- template.merge(context, writer);
- writer.close();
- } catch (Exception e) {
- e.printStackTrace();
- }