Pushler初级Demo2 - 服务器端主动推送消息


参考文章:http://blog.sina.com.cn/s/blog_58b9cb3a01014l71.html


1.> 添加基础文件


 jar : pushlet.jar
 src : source.properties | pushlet.properties

 js : ajax-pushlet-client.js | js-pushlet-client.js


该DEMO下载地址


2.> web.xml
两个Servlet,一个是pushlet 并且要提前初始化,另一个我们自己的Servlet
<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>  

<servlet>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>zy.pushlet.web.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/myServlet.do</url-pattern>
</servlet-mapping>



3.> 不需要再去修改 source.properties 再去注册事件源了.

4.> MyServlet
public class MyServlet extends HttpServlet {
private String meg;
protected void service(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

       //获取内容并转码
       meg = request.getParameter("meg");
       meg = new String(meg.getBytes("UTF-8"),"ISO-8859-1");  
       
       //初始化事件实例,并发送
       Event event = Event.createDataEvent("/Pointer");
       event.setField("data", meg);
       Dispatcher.getInstance().multicast(event);
       
      response.sendRedirect(request.getContextPath()+"/input.jsp");
}
}



5.> 发送端和接收端


input.jsp
<% request.setAttribute("ctx", request.getContextPath()); %>
<form action="${ctx}/myServlet.do">
    消息内容 : <input type="text" name="meg" />
    <input type="submit" value="发送" />
</form>



receive.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="ajax-pushlet-client.js"></script>
</head>
<body>
  <div>
     接收到的内容 :
     <div id="receive">    
     </div>
  </div>
  <script type="text/javascript">
       PL._init();
       PL.joinListen('/Pointer');
 
       var receive = document.getElementById("receive");
       function onData(event) {
            receive.innerHTML = receive.innerHTML + event.get("data") +"<br/>";
       }
  </script>
</body>
</html>




6.> Test

分别打开两个页面,input.jsp 和 receive.jsp



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值