`

使用Spring计时器和velocity模板定时生成静态html/jsp文件

阅读更多
当一个页面不是经常需要更新的话,就需要为它定时生成一个静态文件,这样可以减轻服务器压力,相应的也减少了用户等待时间。

首先看一下一个主jsp文件:
<%@ page contentType="text/html; charset=UTF-8"%>
 <?xml version="1.0"?>  
 <!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html>
<head>
	<title>新闻快讯</title>
	<link rel="stylesheet" type="text/css" href="CSS/styles.css">
</head>
<body>
	。。。。。。
	<!--这是个需要生成的文件,当然你也可以生成html文件,但是需要注意乱码-->
	<jsp:include page="baseInfoMiddle.jsp"></jsp:include>
	
	。。。。。。
</body>
</html>


配置Spring文件:
<!-- velocityEngine生成模板文件 -->
  <bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
        <property name="velocityProperties">   
            <props>   
                <prop key="resource.loader">class</prop>   
                <prop key="class.resource.loader.class">   
                    org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader   
                </prop>   
                <prop key="velocimacro.library"></prop>   
            </props>   
        </property>   
   </bean>
  <!-- 定时器 -->
<!-- 要调用的工作类 --> 
 <bean id ="quartzJob" class ="com.tlt.app.util.QuartzJob">
 	<property name="velocityEngine" ref="velocityEngine" />
 </bean>
 <!-- 定义调用对象和调用对象的方法 --> 
 <bean id ="jobtask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> 
	 <!-- 调用的类 --> 
	 <property name="targetObject"> 
	 	<ref bean="quartzJob" /> 
	 </property> 
	 <!-- 调用类中的方法 --> 
	 <property name="targetMethod"> 
	 	<value>work</value> 
	 </property> 
 </bean>
 <!-- 定义触发时间 --> 
 <bean id ="doTime" class="org.springframework.scheduling.quartz.CronTriggerBean"> 
	 <property name="jobDetail"> 
	 	<ref bean="jobtask" /> 
	 </property> 
	 <!-- cron表达式 --> 
	 <property name="cronExpression">
	 	<!-- 每天凌晨4点触发
	 	<value>0 0 4 * * ?</value> 
	 	 -->
	 	 <!-- 每隔1分钟执行1次,为了测试 -->
	 	<value>0 0/1 * * * ?</value> 
	 </property> 
 </bean>
 <!-- 总管理类 如果将lazy-init='false'那么容器启动就会执行调度程序 --> 
 <bean id="startQuertz" lazy-init="false" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> 
	 <property name="triggers" > 
		 <list> 
		 	<ref bean="doTime" /> 
		 </list> 
	 </property> 
 </bean>


编写要调用的工作类QuartzJob:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.VelocityException;
import org.springframework.ui.velocity.VelocityEngineUtils;

public class QuartzJob {
	VelocityEngine velocityEngine;
	private int count;
	public void work(){
////////////////////////////////////////////////////////////////////////////
//这里每个人的写法不同,但不管怎么样,目的只有一个:获得想要的数据。我这里是通过post请求返回数据后解析,最后把想要的数据填入下面的HashMap<String, String>中就ok了;当然你也可以从数据库中获取数据。
//		System.out.println("----------开始HTTP连接----------");
//		String url="http://XXX.XXX.XXX.XXX";
//		WebClient client=new WebClient();
//		String content="";
//		try {
//			content = client.getWebContentByPost(url,"action=login&loginname=13761083826&password=111111");
//			content = new String(content.getBytes("iso-8859-1"),"UTF-8");
//			System.out.println(content);
//			client=null;
//		} catch (IOException e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		}
//		System.out.println("----------结束HTTP连接----------");
//		System.out.println("----------解析xml开始----------");
//		parse(content);
//		System.out.println("----------解析xml结束----------");
////////////////////////////////////////////////////////////////////////////		
		Map<String, String> model=new HashMap<String, String>();
		model.put("填入需要的key1", "填入需要的值1");
		model.put("填入需要的key2", "填入需要的值2");
		String result = null;
		try {
			result=VelocityEngineUtils.mergeTemplateIntoString(this.getVelocityEngine(), "vm/baseInfoMiddle.vm", "UTF-8",model);
		} catch (VelocityException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
//		System.out.println("result="+result);//打印看看,如果乱码,将baseInfoMiddle.vm文件保存成UTF-8格式
		try {
//通常情况下,静态文件都需要生成在tomcat\webapps\yourProject下
//			String toPath="D:\\Program Files\\Apache Software Foundation\\Tomcat 5.5\\webapps\\yourProject\\baseInfoMiddle.jsp";
//如果下面的写法,文件将生成在tomcat\bin下
//String toPath="baseInfoMiddle.jsp";
//文件最终的生成地址,可以像下面那样。这样不管tomcat装在哪里!
			String toPath="..\\webapps\\yourProject\\baseInfoMiddle.jsp";
			PrintWriter writer = new PrintWriter(toPath,"UTF-8");
			writer.println(result);
			writer.flush();
			writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println( "[Quartz任务调度生成文件]:"+count++ );
	}
	
	public VelocityEngine getVelocityEngine() {
		return velocityEngine;
	}
	public void setVelocityEngine(VelocityEngine velocityEngine) {
		this.velocityEngine = velocityEngine;
	}
}


同时奉送WebClient.java类,该类用于网络连接,应该一看就能明白
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class WebClient {
	
	public WebClient(){
		
	}

	public String getWebContentByGet(String urlString, final String charset,
			int timeout) throws IOException {
		if (urlString == null || urlString.length() == 0) {
			return null;
		}
		urlString = (urlString.startsWith("http://") || urlString
				.startsWith("https://")) ? urlString : ("http://" + urlString)
				.intern();
		URL url = new URL(urlString);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		// 增加报头,模拟浏览器,防止屏蔽
		conn.setRequestProperty(
						"User-Agent",
						"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
		// 只接受text/html类型,当然也可以接受图片,pdf,*/*任意,就是tomcat/conf/web里面定义那些
		conn.setRequestProperty("Accept", "text/html");
		conn.setConnectTimeout(timeout);
		try {
			if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
				return null;
			}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		InputStream input = conn.getInputStream();
		BufferedReader reader = new BufferedReader(new InputStreamReader(input,charset));
		String line = null;
		StringBuffer sb = new StringBuffer();
		while ((line = reader.readLine()) != null) {
			sb.append(line).append("\r\n");
		}
		if (reader != null) {
			reader.close();
		}
		if (conn != null) {
			conn.disconnect();
		}
		return sb.toString();

	}

	public String getWebContentByGet(String urlString) throws IOException {
		return getWebContentByGet(urlString, "iso-8859-1", 5000);
	}

	public String getWebContentByPost(String urlString,String data, final String charset,
			int timeout)throws IOException{
		if (urlString == null || urlString.length() == 0) {
			return null;
		}
		urlString = (urlString.startsWith("http://") || urlString
				.startsWith("https://")) ? urlString : ("http://" + urlString).intern();
		URL url = new URL(urlString);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		 // 设置是否向connection输出,因为这个是post请求,参数要放在  http正文内,因此需要设为true
        connection.setDoOutput(true);   
        connection.setDoInput(true); 
        connection.setRequestMethod("POST");
        // Post 请求不能使用缓存   
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
        // 增加报头,模拟浏览器,防止屏蔽
        connection.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows vista)");
        // 只接受text/html类型,当然也可以接受图片,pdf,*/*任意
        connection.setRequestProperty("Accept", "text/xml");
        connection.setConnectTimeout(timeout);
        connection.connect();
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        String content = URLEncoder.encode(data, "utf-8");//+URLEncoder.encode("中文 ", "utf-8");
        out.writeBytes(content);
        out.flush();   
        out.close();
        
		try {
			//必须写在发送数据的后面
			if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
				return null;
			}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),charset));
        String line;
        StringBuffer sb=new StringBuffer();
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\r\n");
        }
        if (reader != null) {
			reader.close();
		}
		if (connection != null) {
			connection.disconnect();
		}
		return sb.toString();
	}
	public String getWebContentByPost(String urlString,String data) throws IOException {
		return getWebContentByPost(urlString, data,"iso-8859-1", 5000);
	}
	
	public static void main(String[] args) throws IOException {
		WebClient client=new WebClient();
//		String s = client.getWebContentByGet("http://www.baidu.com");
//		s = new String(s.getBytes("iso-8859-1"), "gb2312");
		
		String s = client.getWebContentByPost("http://localhost:8080/Lottery/login.portal","action=login&loginname=13761083826&password=111111");
		s = new String(s.getBytes("iso-8859-1"), "UTF-8");
		System.out.println(s);
	}
	

}


模板类自己设计,比如我的baseInfoMiddle.vm:
<%@ page contentType="text/html; charset=UTF-8" %>
<?xml version="1.0"?>
<!DOCTYPE HTML PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0 //EN" "http://www.wapforun.org/DTD/xhtml-mobile10.dtd">
<html>
	<head>
	<title></title>
	</head>
	<body>
		<p>$key1</p>
		<p>$key2</p>
		
	</body>
</html>


如有看不明白,请先看这里:
http://ben-sin.iteye.com/blog/426435
分享到:
评论
2 楼 joewalker 2011-11-21  
楼上要求太多啦,能够有这样的demo已经很好了
xiechao240 写道
最好上传一份代码,让我们下载后附加就可以运行,这样学习起来效率高一些。

1 楼 xiechao240 2010-08-12  
最好上传一份代码,让我们下载后附加就可以运行,这样学习起来效率高一些。

相关推荐

Global site tag (gtag.js) - Google Analytics