首先列出所依赖文件(网上下载即可):pushlet.jar(导入你的工程)、ajax-pushlet-client.js(页面需引人的JS)、pushlet.properties(放到src下即可)、sources.properties(放到src下即可),最后这两个文件我都没有改动过。这里要注意一下ajax-pushlet-client.js这个文件 其中有这么一段代码
- _getWebRoot: function() {
- /** Return directory of this relative to document URL. */
- if (PL.webRoot != null) {
- return PL.webRoot;
- }
- //derive the baseDir value by looking for the script tag that loaded this file
- var head = document.getElementsByTagName('head')[0];
- var nodes = head.childNodes;
- for (var i = 0; i < nodes.length; ++i) {
- var src = nodes.item(i).src;
- if (src) {
- var index = src.indexOf("ajax-pushlet-client.js");
- if (index >= 0) {
- <span style="color:#FF0000;">index = src.indexOf("js");</span>
- PL.webRoot = src.substring(0, index);
- break;
- }
- }
- }
- return PL.webRoot;
- }
配置pushlet的servlet
web.xml:
<servlet>
<servlet-name>pushlet</servlet-name>
<servlet-class>nl.justobjects.pushlet.servlet.Pushlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>pushlet</servlet-name>
<url-pattern>/pushlet.srv</url-pattern>
</servlet-mapping>
前台JSP:
send.jsp //就是利用这个页面触发后台一个servlet
- <%
- String path = request.getContextPath();
- %>
- <form action="<%=path%>/TestPushlet">
- <input type="submit" value ="submit"/>
- </form>
- <script type="text/javascript" src="<%=path %>/js/ajax-pushlet-client.js"></script>
- <div id="display">随机数在这里显示</div>
- <script>
- PL._init();
- PL.joinListen('/test/myevent1');//与发送字段一致
- function onData(event)
- {
- var data=event.get("key1");
- document.getElementById("display").innerHTML=data;
- }
- </script>
TestPushlet 这个servlet 配置就不说了 代码如下:(其实就是每3秒发送一个随机数)
- import java.io.IOException;
- import java.util.Random;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import nl.justobjects.pushlet.core.Dispatcher;
- import nl.justobjects.pushlet.core.Event;
- public class TestPushlet extends HttpServlet
- {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- public TestPushlet()
- {
- super();
- }
- protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
- {
- while (true)
- {
- Event event = Event.createDataEvent("/test/myevent1");//发送字段
- Random random = new Random();
- event.setField("key1", String.valueOf(random.nextInt(100)));
- Dispatcher.getInstance().multicast(event);
- try
- {
- Thread.sleep(3000);
- }
- catch (InterruptedException e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }