使用DWR实现消息推送功能

参考:http://blog.csdn.net/carefree31441/article/details/17225851

添加Maven依赖:

<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.directwebremoting/dwr -->
        <dependency>
            <groupId>org.directwebremoting</groupId>
            <artifactId>dwr</artifactId>
            <version>3.0.0-RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>

    </dependencies>

新建一个ScriptSessionListener:监听ScriptSession的创建和销毁

public class DWRScriptSessionListener implements ScriptSessionListener {
    // 维护一个Map key为session的Id, value为ScriptSession对象
    public static final Map<String, ScriptSession> scriptSessionMap = new HashMap<String, ScriptSession>();

    public void sessionCreated(ScriptSessionEvent event) {
        WebContext webContext = WebContextFactory.get();
        HttpSession session = webContext.getSession();
        ScriptSession scriptSession = event.getSession();
        scriptSession.setAttribute("userid", session.getId());//这里使用sesssion,使用时可存储为用户id后使用
        scriptSessionMap.put(session.getId(), scriptSession); // 添加scriptSession
        System.out.println("session-created"+session.getId());
    }

    public void sessionDestroyed(ScriptSessionEvent event) {
        WebContext webContext = WebContextFactory.get();
        HttpSession session = webContext.getSession();
        scriptSessionMap.remove(session.getId()); // 移除scriptSession
    }
}

继承DefaultScriptSessionManager,添加ScriptSession监听器

public class DWRScriptSessionManager extends DefaultScriptSessionManager {
    public DWRScriptSessionManager(){  
        //绑定一个ScriptSession增加销毁事件的监听器  
        this.addScriptSessionListener( new DWRScriptSessionListener());  
 }
}

Web全局配置:web.xml

<web-app>
    <display-name>DWR-START</display-name>
    <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>activeReverseAjaxEnabled</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>org.directwebremoting.extend.ScriptSessionManager </param-name>
            <param-value>gdou.laiminghai.dwr.DWRScriptSessionManager </param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>dwr-invoker</servlet-name>
        <url-pattern>/dwr/*</url-pattern>
    </servlet-mapping>
</web-app>

消息推送功能类

public class MessagePush {
    //改善给特定用户
    public void sendToOne(final String userId, final String 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", message);
                Collection<ScriptSession> sessions = Browser.getTargetSessions();
                for (ScriptSession scriptSession : sessions) {
                    scriptSession.addScript(script);
                }
            }
        });
    }

    //发送给所有用户
    public void sendToAll(final String message) {
        Browser.withAllSessions(new Runnable() {
            public void run() {
                ScriptSessions.addFunctionCall("showMessage", message);
            }
        });
    }
}

DWR配置:在web.xml同一目录下新建dwr.xml

<dwr>
    <allow><!--定义了DWR能够创建和转换的类,以供 javascript 访问-->
        <create creator="new" javascript="MessagePush">
            <param name="class" value="gdou.laiminghai.dwr.MessagePush" />
        </create>
    </allow>
</dwr>

页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
<body>
    <div>sessionid:<input id="sessionid" type="text">message:<input id="msg" type="text">
    <input type="button" onclick="sendToOne();" value="发送"></div>
    <div>message:<input id="msg2" type="text">
    <input type="button" onclick="sendToAll();" value="发送给所有人"></div>
    <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">
        dwr.engine.setActiveReverseAjax(true);
        dwr.engine.setNotifyServerOnPageUnload(true);

        //回调函数
        function showMessage(message) {
            alert(message);
        }

        function sendToOne(){
            var sessionid = document.getElementById("sessionid").value;
            var msg = document.getElementById("msg").value;
            MessagePush.sendToOne(sessionid,msg);
        }

        function sendToAll(){
            var msg2 = document.getElementById("msg2").value;
            MessagePush.sendToAll(msg2);
        }
    </script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/crazylai1996/article/details/79403977