DWR进行后台消息推送

前端之家收集整理的这篇文章主要介绍了DWR进行后台消息推送前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package com.push.method;
import javax.servlet.ServletException;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.WebContextFactory;

import com.push.util.DwrScriptSessionManagerUtil;

public class MessagePush {

    public void pageOnLoad(String userId) {
        ScriptSession scriptSession = WebContextFactory.get().getScriptSession();
        scriptSession.setAttribute(userId,userId);
        DwrScriptSessionManagerUtil dwrScriptSessionManagerUtil = new DwrScriptSessionManagerUtil();
        try {
               dwrScriptSessionManagerUtil.init();
        } catch (ServletException e) {
               e.printStackTrace();
        }
    }

}

MessagePush.java

package com.push.services;
import java.util.Collection;
import org.directwebremoting.Browser;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ScriptSessionFilter;

public class SendMessage {

	
    public void sendMessageAuto(String userid,String message) {
    	final String userId = userid ;
        final String autoMessage = message; 
        Browser.withAllSessionsFiltered(new ScriptSessionFilter(){
	        public boolean match(ScriptSession session) {
	                  if (session.getAttribute("userId") == null)
	                         return false;
	                  else
	                         return (session.getAttribute("userId")).equals(userId);
	        }
        },new Runnable(){
               private ScriptBuffer script = new ScriptBuffer();
               public void run() {
                      script.appendCall("showMessage",autoMessage);
                      Collection<ScriptSession> sessions = Browser.getTargetSessions();
                      for (ScriptSession scriptSession : sessions) {
                             scriptSession.addScript(script);
                      }
               		}
        		});
    		}
}

SendMessage.java
package com.push.util;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import org.directwebremoting.Container;
import org.directwebremoting.ServerContextFactory;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.event.ScriptSessionEvent;
import org.directwebremoting.event.ScriptSessionListener;
import org.directwebremoting.extend.ScriptSessionManager;
import org.directwebremoting.servlet.DwrServlet;

public class DwrScriptSessionManagerUtil extends DwrServlet{
	
	/**
	 * SerialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	public void init() throws ServletException {
	 
	  Container container = ServerContextFactory.get().getContainer();
     
	  ScriptSessionManager manager = container.getBean(ScriptSessionManager.class);
     
      ScriptSessionListener listener = new ScriptSessionListener() {
    	  	public void sessionCreated(ScriptSessionEvent ev) {
                    HttpSession session = WebContextFactory.get().getSession();
                  String userId = (String)session.getAttribute("userinfo");
                    System.out.println("已经创建一个ScriptSession(脚本会话)");
                    ev.getSession().setAttribute("userId",userId);
             }
             public void sessionDestroyed(ScriptSessionEvent ev) {
                    System.out.println("a脚本会话已经销毁..");
             }
      };
      
      manager.addScriptSessionListener(listener);
  }

}

DwrScriptSessionManagerUtil.java
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <base href="<%=basePath%>" /> 
    <title>Demo|消息即时推送 </title>
   	<script type="text/javascript" src="dwr/engine.js"></script>
    <script type="text/javascript" src="dwr/util.js"></script>
    <script type="text/javascript" src="dwr/interface/MessagePush.js"></script>
    <script type="text/javascript">
   	  function onLoad(){
            var userId = '${userinfo}';
            MessagePush.pageOnLoad(userId);
       }
       
       function showMessage(val){
       	alert(val);
       }
    </script>
	<style type="text/css">
	<!-- 
		*{ font-size:12px; color:#666}
		input { border:#CCC solid 1px;}
	-->
	</style>
</head>
<body onload="dwr.engine.setActiveReverseAjax(true);dwr.engine.setNotifyServerOnPageUnload(true);onLoad();">
  <form id="form1" name="form1" method="post" action="user!send.action">
    <table width="400" height="120" border="0" align="center" cellpadding="0" cellspacing="0">
      <tr>
        <td width="106" height="100" align="right" valign="bottom">当前登录用户:</td>
        <td width="294" height="100" valign="bottom">${userinfo}</td>
      </tr>
      <tr>
        <td height="35" align="right" valign="bottom">发送至:</td>
        <td height="35" valign="bottom"><input name="username" type="text" id="username" size="27" maxlength="20" /></td>
      </tr>
      <tr>
        <td height="35" align="right">内容:</td>
        <td height="80" valign="bottom">
          <textarea name="context" cols="25" rows="5" id="context">要推送的内容..</textarea></td>
      </tr>
      <tr>
        <td height="35" colspan="2" align="center" valign="middle">
        <input type="submit" name="Submit" value="提交" /></td>
      </tr>
    </table>
</form>
</body>
</html>

main.jsp
<?xml version="1.0" encoding="UTF-8"?>
     <!DOCTYPE dwr PUBLIC
          "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN"
          "http://getahead.org/dwr/dwr30.dtd">
  <dwr>
       <allow>
			<create creator="new" javascript="MessagePush">
				<param name="class" value="com.push.method.MessagePush" />
				<include method="pageOnLoad" />
			</create>
      </allow>
  </dwr>

dwr.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	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_2_5.xsd">
  
<servlet>
    <servlet-name>dwr-invoker</servlet-name>
    <servlet-class> org.directwebremoting.servlet.DwrServlet</servlet-class>
    <init-param>
        <param-name>crossDomainSessionSecurity</param-name>
           <param-value>false</param-value>
        </init-param>
    <init-param>
      <param-name>allowScriptTagRemoting</param-name>
      <param-value>true</param-value>
    </init-param>
    <init-param>
      <param-name>classes</param-name>
      <param-value>java.lang.Object</param-value>
    </init-param>
    <init-param>
        <param-name>activeReverseAjaxEnabled</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
       <param-name>initApplicationScopeCreatorsAtStartup</param-name>
       <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>maxWaitAfterWrite</param-name>
        <param-value>3000</param-value>
    </init-param>
    <init-param>
        <param-name>debug</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>logLevel</param-name>
        <param-value>WARN</param-value>
    </init-param>
</servlet>
<servlet-mapping>
	<servlet-name>dwr-invoker</servlet-name>
	<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
  
  <filter>
  	<filter-name>struts</filter-name>
  	<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
 </filter>
 <filter-mapping>
 	<filter-name>struts</filter-name>
 	<url-pattern>*.action</url-pattern>
 </filter-mapping>
 
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
</web-app>
web.xml

猜你在找的Ajax相关文章