在web应用中使用velocity

<%@  page language="java" contentType= "text/html; charset=GB18030" pageEncoding="gb18030" %>
<%@  page import="java.util.*" %>
<%@  page import="java.io.*" %>
<%@  page import="java.lang.*" %>
<%@  page import="org.apache.velocity.*" %>
<%@  page import="org.apache.velocity.app.*" %>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
out.println(path + " " + basePath);
String realPath = request.getRealPath("");
out.println(" realPath=" + realPath);
%>

<%
    //---------初始化Velocity----此块可以单独放在一个Initiator.java类中进行--------
    System.out.print("Step 1 : Initializing Velocity...");
//String fileDir = "D:/workspace_MyEclipse/test_sm/WebRoot/";
    String fileDir = realPath + "/";
    Properties p = new Properties();
    p.setProperty("file.resource.loader.path", fileDir);
    p.setProperty("input.encoding","GB18030");
    p.setProperty("output.encoding","GB18030");
try {
Velocity.init(p);
} catch (Exception e) {
e.printStackTrace();
}
%>

<% 
    //可抽象在一个adminhead.jsp文件中
    VelocityContext context = new VelocityContext();
    //定义输出流
    StringWriter w = new StringWriter();
    //定义VM文件所在的相对路径
    String vmPath = "template/";
    //设置VM文件中的相对路径
    context.put("vmPath",vmPath);
%>

<% 
    //jsp文件用于将model数据view显示出来
// 把数据填入上下文
    context.put("name", "Liang李安");
    context.put("date", (new Date()).toString());
    Client c = new Client();
    List<Animal> aList = c.animalManager.findAllAnimal();
    context.put("aList", aList);

    Template tm;
    tm = Velocity.getTemplate(vmPath + "hellovelocity2.html");
%>

<%
    //可抽象在一个admintail.jsp文件中
    try{
        //模板替换
        tm.merge( context, w );
        //向客户端输出
        out.println(w);
    }catch(Exception ex) {
      ex.printStackTrace();
    }
%>    

你可能感兴趣的:(java,Web,jsp,MyEclipse,velocity)