JAVAEE Velocity配置例子

看了红薯的OSChina简单架构,也想学习一下Velocity。网上例子也不少,有很多都用到Veloctiy 配置文件,我觉得比较麻烦,最后找了只用代码的,这样结构比较清晰。

0.开发环境:MyEclipse10.7,jdk1.6,JAVAEE 6.0

1.相关jar包下载:地址

Engine,velocity-1.7和Tools,velocity-2.0都下载,包很多,我这个例子用到下面的包就可以跑起来:

JAVAEE Velocity配置例子_第1张图片

2.配置,code

新建WebProject-->VelocityTest,创建完成后结构如下:

JAVAEE Velocity配置例子_第2张图片

先在web.xml配置IndexServlet(EncodeFilter是处理字符编码的,我都是UTF-8的),然后在IndexServlet里用velocity来处理页面。VelocityHelper.java是配置Velocity的。VelocityTest.java是测试的。下面我把代码一一贴出,这里是代码工程下载地址:

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name></display-name>	
    
      <filter>
  	<filter-name>EncodeFilter</filter-name>
  	<filter-class>com.suchok.filter.EncodeFilter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>EncodeFilter</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
    
      <servlet>
     <servlet-name>velocity</servlet-name>
     <servlet-class>org.apache.velocity.tools.view.VelocityViewServlet</servlet-class>
   </servlet>
   <servlet-mapping>
     <servlet-name>velocity</servlet-name>
     <url-pattern>*.html</url-pattern>
   </servlet-mapping>
    
    
    
    <servlet>
  	<servlet-name>IndexServlet</servlet-name>
    <servlet-class>com.suchok.IndexServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>IndexServlet</servlet-name>
  	<url-pattern>/*</url-pattern>
  </servlet-mapping>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
IndexServlet.java


package com.suchok;

import java.io.IOException;
import java.io.PrintWriter;

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

import com.suchok.velocity.VelocityTest;

public class IndexServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		process(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		process(req,resp);
	}
	
	private void process(HttpServletRequest req, HttpServletResponse resp){
		 PrintWriter out;
		try {
			resp.setContentType("text/html;charset=UTF-8");
			out = resp.getWriter();
			out.println(VelocityTest.HelloWorld());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
EncodeFilter.java


package com.suchok.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;



public class EncodeFilter implements Filter{

	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		arg0.setCharacterEncoding("utf-8");
		arg2.doFilter(arg0, arg1);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
	}


}
VelocityHelper.java


package com.suchok.velocity;

import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;

public class VelocityHelper {

	private static final String TMP_PATH="com/suchok/velocity/tmp";
    public static Logger logger = Logger.getLogger(VelocityHelper.class);
    static {
   
    	//***find tmp file under class path
    	Velocity.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); 
        try {
            Velocity.init();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    public static Template getTemplate(String fileName) throws Exception {
        return Velocity.getTemplate(TMP_PATH+"/"+fileName, "UTF-8");
    }
}
VelocityTest.java


package com.suchok.velocity;

import java.io.StringWriter;

import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;

public class VelocityTest {
	private static Logger logger = Logger.getLogger(VelocityTest.class);

	public static String HelloWorld() {
		StringWriter write = null;
		try {
			Template template = VelocityHelper.getTemplate("hello.html");
			VelocityContext vc = new VelocityContext();
			vc.put("title", "hello");
			write = new StringWriter();
			template.merge(vc, write);
			write.flush();
			write.close();

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			e.printStackTrace();
		}
		return write == null ? "null" : write.toString();
	}
}
hello.html


<html>
<head>
<meta content="text/html" charset="utf-8"/>
</head>
<body>
内容:$title
</html>

3.运行结果


JAVAEE Velocity配置例子_第3张图片

4.感受

才开始学JAVAEE开发,用jsp感觉页面元素比较复杂,有时候要写java code,比较混乱,而velocity页面简单全是html和velocity标签即可,和以前用过php的smarty引擎一样,前端和后端分离了,更好维护了;jsp页面第一次要编译,然后再装载class文件,而velocity直接装载模板,暴露一些细节,但我觉得结构也清晰了。



你可能感兴趣的:(javaee,velocity,例子)