1. 程式人生 > >Dwr java伺服器反推技術(伺服器推送到頁面)

Dwr java伺服器反推技術(伺服器推送到頁面)

原始碼及展示

Gitee: https://gitee.com/liaotuo/DwrTest

  • 展示
    這裡寫圖片描述

  • 簡介
    簡略的實現了伺服器反向通知到前臺頁面, 在輸入框輸入文字,點擊發送按鈕,訊息會被通知到所有線上的使用者。

實現

依賴

  • dwr.jar
  • commons-logging-1.0.4.jar
  • jquery-3.2.1.min.js

jar包可以直接在我gitee下載

目錄結構

這裡寫圖片描述

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>DwrTest</display-name> <welcome-file-list> <welcome-file
>
index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file
>
</welcome-file-list> <!-- 配置dwrServelet --> <servlet> <servlet-name>dwr</servlet-name> <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class> <!-- 開啟debug模式 --> <init-param> <param-name>debug</param-name> <param-value>true</param-value> </init-param> <!-- 使用伺服器反推技術(逆Ajax) --> <init-param> <param-name>activeReverseAjaxEnabled</param-name> <param-value>true</param-value> </init-param> <!-- 能夠從其他域進行請求 --> <init-param> <param-name>crossDomainSessoionSecurity</param-name> <param-value>false</param-value> </init-param> <!-- 允許遠端js --> <init-param> <param-name>allowScriptTagRemoting</param-name> <param-value>true</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dwr</servlet-name> <!-- 此路徑決定dwr engin.js util.js的路徑 --> <url-pattern>/js/dwr/*</url-pattern> </servlet-mapping> </web-app>

dwr.xml

<!DOCTYPE dwr PUBLIC
    "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN"
    "http://getahead.org/dwr/dwr30.dtd">

<dwr>
    <allow>
        <!-- javascript="Java類名" -->
        <create creator="new" javascript="DwrPush">
            <param name="class">util.DwrPush</param>
        </create>
    </allow>
</dwr>

index.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    // 用於獲取專案根目錄
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- 需要引入的dwr的三個重要js 路徑要和web.xml server-mapping內配置的路徑一致-->
<script type="text/javascript" src="<%=path%>/js/dwr/util.js"></script>
<script type="text/javascript" src="<%=path%>/js/dwr/engine.js"></script>
<script type="text/javascript"
    src="<%=path%>/js/dwr/interface/DwrPush.js"></script>

<script type="text/javascript" src="<%=path%>/js/jquery-3.2.1.min.js"></script>

<title>Clannad聊天室</title>
</head>
<body>
    <ul id="ul" style="color: red; font-size: 15px;"></ul>
    <input type="text" name="msg" id="msg" size="30">
    <input type="button" name="button" id="send" value="傳送">
</body>
<script type="text/javascript">
    /* 開啟ajax反推技術 並給按鈕繫結推送方法 */
    $(document).ready(function() {
        dwr.engine.setActiveReverseAjax(true);
        $('#send').click(function() {
            DwrPush.push($('#msg').val());
        });
    });
    // 回撥方法
    function callback(msg) {
        $('#ul').html($('#ul').html() + "</br>" + msg);
    }
</script>
</html>

DwrPush.java

package util;

import java.util.ArrayList;
import java.util.List;

import org.directwebremoting.Container;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ServerContextFactory;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.event.ScriptSessionEvent;
import org.directwebremoting.event.ScriptSessionListener;
import org.directwebremoting.extend.ScriptSessionManager;;
/***
 * Dwr反向推送類
 * @author liaot
 * @time 2017/12/09
 */
public class DwrPush {
    // 記錄所有線上的ScriptSession
    private final static List<ScriptSession> SESSIONS = new ArrayList<ScriptSession>();
    static {
        // 得到DWR容器
        Container container = ServerContextFactory.get().getContainer();
        // 從DWR中得到會話管理器
        ScriptSessionManager manager = container.getBean(ScriptSessionManager.class);
        // 建立一個會話監聽器
        ScriptSessionListener ssl = new ScriptSessionListener() {

            @Override
            public void sessionCreated(ScriptSessionEvent e) {
                SESSIONS.add(e.getSession());
                System.out.println("user login " + SESSIONS.size());
            }

            @Override
            public void sessionDestroyed(ScriptSessionEvent e) {
                SESSIONS.remove(e.getSession());
                System.out.println("user exit " + SESSIONS.size());
            }
        };
        // 給管理器新增監聽器
        manager.addScriptSessionListener(ssl);
    }

    public void push(String msg) {
        // 得到當前使用者的ScriptSession
        ScriptSession seft = WebContextFactory.get().getScriptSession();
        System.out.println(seft);
        for (ScriptSession session : SESSIONS) {
            // 建立指令碼 快取 執行指定function 傳遞msg引數
            ScriptBuffer sb = new ScriptBuffer();
            //呼叫 jsp頁面上 callback 方法
            sb.appendCall("callback", seft.getCreationTime() + " : " + msg);
            //將指令碼新增到回話中
            session.addScript(sb);
        }
    }
}

參考資料