Dwr java服务器反推技术(服务器推送到页面)

源码及展示

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

  • 展示
    Dwr java服务器反推技术(服务器推送到页面)_第1张图片

  • 简介
    简略的实现了服务器反向通知到前台页面, 在输入框输入文字,点击发送按钮,消息会被通知到所有在线的用户。

实现

依赖

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

jar包可以直接在我gitee下载

目录结构

Dwr java服务器反推技术(服务器推送到页面)_第2张图片

web.xml


<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>DwrTestdisplay-name>
  <welcome-file-list>
    <welcome-file>index.htmlwelcome-file>
    <welcome-file>index.htmwelcome-file>
    <welcome-file>index.jspwelcome-file>
    <welcome-file>default.htmlwelcome-file>
    <welcome-file>default.htmwelcome-file>
    <welcome-file>default.jspwelcome-file>
  welcome-file-list>

  
  <servlet>
    <servlet-name>dwrservlet-name>
    <servlet-class>org.directwebremoting.servlet.DwrServletservlet-class>
    
    <init-param>
      <param-name>debugparam-name>
      <param-value>trueparam-value>
    init-param>
    
    <init-param>
        <param-name>activeReverseAjaxEnabledparam-name>
        <param-value>trueparam-value>
    init-param>
    
    <init-param>
        <param-name>crossDomainSessoionSecurityparam-name>
        <param-value>falseparam-value>
    init-param>
    
    <init-param>
        <param-name>allowScriptTagRemotingparam-name>
        <param-value>trueparam-value>
    init-param>
  servlet>

  <servlet-mapping>
    <servlet-name>dwrservlet-name>
    
    <url-pattern>/js/dwr/*url-pattern>
  servlet-mapping>
web-app>

dwr.xml



<dwr>
    <allow>
        
        <create creator="new" javascript="DwrPush">
            <param name="class">util.DwrPushparam>
        create>
    allow>
dwr>

index.jsp


<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">

<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() + "
"
+ 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 SESSIONS = new ArrayList();
    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);
        }
    }
}

参考资料

  • dwr 官网: http://directwebremoting.org/dwr/
  • imooc: https://www.imooc.com/learn/784

你可能感兴趣的:(Java)