dwr进行消息推送示例

Posted java一生

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了dwr进行消息推送示例相关的知识,希望对你有一定的参考价值。

<?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="PushMessage">
    <param name="class" value="com.manhui.push.controller.PushMessage"/>
    </create>          
  </allow>
</dwr>

  

关于dwr的介绍可自行度娘,这里主要做一个dwr进行消息推送的demo

第一步:这里使用maven项目,先引入jar的仓库地址:

1 <dependency>
2             <groupId>org.directwebremoting</groupId>
3             <artifactId>dwr</artifactId>
4             <version>3.0.0-RELEASE</version>
5         </dependency>
View Code

第二步:web.xml配置

	<!-- dwr相关配置 -->
	<servlet>
		<servlet-name>dwr-invoker</servlet-name>
		<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
		<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>
		<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>6000</param-value>
		</init-param>
		<load-on-startup>2</load-on-startup>  
	</servlet>
      <servlet-mapping>    
     <servlet-name>dwr-invoker</servlet-name>    
     <url-pattern>/dwr/*</url-pattern>    
  </servlet-mapping> 

  第三步:后台编码

package com.manhui.push.controller;

import java.util.Collection;

import org.apache.log4j.Logger;
import org.directwebremoting.Browser;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ScriptSessionFilter;
import org.directwebremoting.WebContextFactory;

/**
 * 推送消息控制层,这里主要是进行消息的精确推送,当然如果要进行所有推送,则不需要进行过滤处理即可
 * @author hq
 *
 */
public class PushMessage {
	
	private Logger log = Logger.getLogger(PushMessage.class);
	
	 // 载入页面时调用,传入name值作为推送的标识
    public void onPageLoad(String name) {
        ScriptSession session = WebContextFactory.get().getScriptSession();
        session.setAttribute("name", name);
    }
    public void addMessage(String userid, String message) {
        final String userId = userid;
        final String autoMessage = message;
        ScriptSession session = WebContextFactory.get().getScriptSession();
        String from =(String) session.getAttribute("name");
        
        // 获取所有scriptsession并通过ScriptSessionFilter筛选符合条件的ScriptSession
        Browser.withAllSessionsFiltered(new ScriptSessionFilter() {
            // 实现match方法,条件为真为筛选出来的session
            public boolean match(ScriptSession session) {
                String name = session.getAttribute("name").toString();
               return name == null ? false : userId.equals(name);
            }
        }, new Runnable() {
            private ScriptBuffer script = new ScriptBuffer();
            public void run() {
                // 设定前台接受消息的方法和参数
                script.appendCall("receiveMessages", autoMessage);
                Collection<ScriptSession> sessions = Browser
                        .getTargetSessions();//获取有效的scriptsession
                // 向所有符合条件的页面推送消息
                for (ScriptSession scriptSession : sessions) {
                    if (scriptSession.getAttribute("name").equals(userId)) {
                        scriptSession.addScript(script);
                    }
                }
            }
        });
    }
	
	

}

  第四步:在web.xml同级目录下创建dwr.xml文件

 

<?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="PushMessage">
    <param name="class" value="com.manhui.push.controller.PushMessage"/>
    </create>          
  </allow>
</dwr>

  

第五步:在需要推送消息的页面引入相关js,并在页面初始化之前加载相关方法

   <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/PushMessage.js"></script>

     <script type="text/javascript" src="dwr/interface/PushMessage.js"></script>该js文件是根据dwr.xml自行生成的,前面的是dwr.jar里面的

页面初始化加载调用:

  dwr.engine.setActiveReverseAjax(true);// 开启逆向Ajax,也可写在body标签的onload方法中
  dwr.engine.setNotifyServerOnPageUnload(true);
  dwr.engine.setErrorHandler(function(){});//"   这个方法 防止项目已经关闭,客户页面还未关闭,页面会谈Error的问题
  onPageLoad();

  

var chatlog = "";
var name = \'${name}\';
function sendMessage() {
    var message = $("#message").val();
    var user = $("#user").val();
    // 通过代理调用后台的addMessage方法发送消息
    PushMessage.addMessage(user, message);
}

// 前台接受消息的方法,由后台调用 
function receiveMessages(messages) {
    var lastMessage =  messages;
    chatlog = "<p>" + lastMessage + "</p>" + chatlog;
    $("#list").html(chatlog);
}

//读取name值作为推送的唯一标示
function onPageLoad(){
    // 获取URL中的name属性为唯一标识符
    var userId = name;
    $("#myName").html(userId);
    // 通过代理,传入区别本页面的唯一标识符
    PushMessage.onPageLoad(userId);
 }

  第六步:效果如下

 

以上是关于dwr进行消息推送示例的主要内容,如果未能解决你的问题,请参考以下文章

DWR实现服务器向客户端推送消息

DWR服务器推送技术

dwr 后台服务器推送技术

dwr 后台服务器推送技术

DWR系列02-DWR逆向Ajax即服务器推送

DWR 3.0 入门示例教程(简单实例)