Pushlet后台推送实例
工程目录如下:
1、下载jar包,下载地址 http://sourceforge.net/projects/pushlets/
2、将jar包拷到WebContent/WEB-INF/lib目录下,js文件拷贝到对应目录,pushlet.properties和sources.properties拷贝到WEB-INF目录下。
sources.properties文件中增加如下配置
source7=com.zts.pushlet.PushLetTest
3、PushLetTest.java
1 package com.zts.pushlet; 2 3 import java.io.Serializable; 4 5 import nl.justobjects.pushlet.core.Event; 6 import nl.justobjects.pushlet.core.EventPullSource; 7 8 @SuppressWarnings("serial") 9 public class PushLetTest extends EventPullSource implements Serializable 10 { 11 private int index = 0; 12 13 /** 14 * 设置休眠时间 15 */ 16 @Override 17 protected long getSleepTime() 18 { 19 return 3000; 20 } 21 22 /** 23 * 创建事件 业务部分写在pullEvent()方法中,这个方法会被定时调用。 24 */ 25 @Override 26 protected Event pullEvent() 27 { 28 Event event = Event.createDataEvent("/zts/pushlet"); 29 event.setField("result", index + "HelloWorld."); 30 index++; 31 return event; 32 } 33 34 }
4、index.jsp
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 2 <%@ page contentType="text/html;charset=UTF-8"%> 3 <html> 4 <head> 5 <title>HelloWorld</title> 6 <script type="text/javascript" src="ajax-pushlet-client.js"></script> 7 <script type="text/javascript"> 8 PL._init(); 9 PL.joinListen('/zts/pushlet'); 10 function onData(event) { 11 //console.log(event.get("result")); 12 var obj = document.getElementById("content"); 13 obj.innerHTML = obj.innerHTML + event.get("result") + "<br/>"; 14 } 15 </script> 16 </head> 17 18 <body> 19 <div id="content" style="border:1px solid #000; 200px;">推送内容如下:</div> 20 </body> 21 </html>
5、web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> 3 <!-- 缺省js文件通过"pushlet.srv"名字触发servlet的。不需要修改<url-pattern>/pushlet.srv</url-pattern>, 4 如果修改,需要在对应的js文件中也要修改对应的名字。 5 PL.pushletURL = PL._getWebRoot() + 'pushlet.srv'; 6 --> 7 <servlet> 8 <servlet-name>pushlet</servlet-name> 9 <servlet-class>nl.justobjects.pushlet.servlet.Pushlet</servlet-class> 10 <load-on-startup>1</load-on-startup> 11 </servlet> 12 <servlet-mapping> 13 <servlet-name>pushlet</servlet-name> 14 <url-pattern>/pushlet.srv</url-pattern> 15 </servlet-mapping> 16 17 18 <welcome-file-list> 19 <welcome-file>index.jsp</welcome-file> 20 </welcome-file-list> 21 </web-app>
浏览器打开后的输出结果如下:
如果多个推送,js文件多次拷贝修改名字,区别即可。