DWR3使用

简介: DWR3使用

导入官方demo里面的jar包


新建DWRScriptSessionListener

package com.dwr.test;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.event.ScriptSessionEvent;
import org.directwebremoting.event.ScriptSessionListener;
public class DWRScriptSessionListener implements ScriptSessionListener {
  // 维护一个Map key为session的Id, value为ScriptSession对象
  public static final Map<String, ScriptSession> scriptSessionMap = new HashMap<String, ScriptSession>();
  /**
   * ScriptSession创建事件
   */
  @Override
  public void sessionCreated(ScriptSessionEvent event) {
    WebContext webContext = WebContextFactory.get();
    HttpSession session = webContext.getSession();
    ScriptSession scriptSession = event.getSession();
    scriptSessionMap.put(session.getId(), scriptSession); // 添加scriptSession
    System.out.println("session: " + session.getId() + " scriptSession: " + scriptSession.getId() + "is created!");
  }
  /**
   * ScriptSession销毁事件
   */
  @Override
  public void sessionDestroyed(ScriptSessionEvent event) {
    WebContext webContext = WebContextFactory.get();
    HttpSession session = webContext.getSession();
    ScriptSession scriptSession = scriptSessionMap.remove(session.getId()); // 移除scriptSession
    System.out.println("session: " + session.getId() + " scriptSession: " + scriptSession.getId() + "is destroyed!");
  }
  /**
   * 获取所有ScriptSession
   */
  public static Collection<ScriptSession> getScriptSessions() {
    return scriptSessionMap.values();
  }
}


新建DWRScriptSessionManager

package com.dwr.test;
import org.directwebremoting.impl.DefaultScriptSessionManager;
public class DWRScriptSessionManager extends DefaultScriptSessionManager {
  public DWRScriptSessionManager() {
    // 绑定一个ScriptSession增加销毁事件的监听器
    this.addScriptSessionListener(new DWRScriptSessionListener());
    System.out.println("bind DWRScriptSessionListener");
  }
}


新建主类MessagePush

package com.dwr.test;
import java.util.Collection;
import org.directwebremoting.Browser;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ScriptSessionFilter;
import org.directwebremoting.WebContextFactory;
public class MessagePush {
  public void onPageLoad(final String tag) {
    // 获取当前的ScriptSession
    ScriptSession scriptSession = WebContextFactory.get().getScriptSession();
    scriptSession.setAttribute("tag", tag);
    System.out.println("setAttribute");
  }
  public void send(String msg) {
    if(null==msg){
      msg="this is a message!";
    }
    final String content=msg;
    // 过滤器
    ScriptSessionFilter filter = new ScriptSessionFilter() {
      public boolean match(ScriptSession scriptSession) {
        String tag = (String) scriptSession.getAttribute("tag");
        System.out.println("tag="+tag);
        return "receiverTag".equals(tag);
      }
    };
    Runnable run = new Runnable() {
      private ScriptBuffer script = new ScriptBuffer();
      public void run() {
        
        // 设置要调用的 js及参数
        script.appendCall("show", content);
        // 得到所有ScriptSession
        Collection<ScriptSession> sessions = DWRScriptSessionListener.getScriptSessions();
        // 遍历每一个ScriptSession
        for (ScriptSession scriptSession : sessions) {
          scriptSession.addScript(script);
        }
      }
    };
    // 执行推送
    Browser.withAllSessionsFiltered(filter, run); // 注意这里调用了有filter功能的方法
  }
}


在web.xml同目录新建dwr.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dwr PUBLIC
    "-//GetAhead Limited//DTD Direct Web Remoting 1.0//EN"
    "http://www.getahead.ltd.uk/dwr/dwr30.dtd">
<dwr>
  <allow>
    <create creator="new" javascript="MessagePush">
      <param name="class" value="com.dwr.test.MessagePush" />
    </create>
  </allow>
</dwr>


在web.xml文件中添加一下配置

<servlet>
    <servlet-name>dwr-invoker</servlet-name>
    <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
    <init-param>
      <param-name>org.directwebremoting.extend.ScriptSessionManager</param-name>
      <param-value>com.dwr.test.DWRScriptSessionManager </param-value>
    </init-param>
    <init-param>
      <param-name>debug</param-name>
      <param-value>true</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>pollAndCometEnabled</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>
      <!-- dwr配置文件路径 -->
      <param-name>config</param-name>
      <param-value>/WEB-INF/dwr.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dwr-invoker</servlet-name>
    <url-pattern>/dwr/*</url-pattern>
  </servlet-mapping>


jsp页面

<%@ 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 HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
  <meta http-equiv="pragma" content="no-cache">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="expires" content="0">    
  <!--
  <link rel="stylesheet" type="text/css" href="styles.css">
  -->
  <script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
  <script type= "text/javascript" src ="dwr/util.js"></script>     
     <script type="text/javascript" src= "dwr/engine.js"></script >   
     <script type="text/javascript" src= "dwr/interface/MessagePush.js" ></script>  
  
  <script>
        dwr.engine.setActiveReverseAjax(true);
    dwr.engine.setNotifyServerOnPageUnload(true,true);
    var tag = "receiverTag";    //自定义一个标签
        MessagePush.onPageLoad(tag);
    dwr.engine.setErrorHandler(function(){});
    
    function show(content){ 
            alert(content);
        }
        
        function sendMessage(){
          var message = dwr.util.getValue("msg");
          MessagePush.send(message);
        }
  </script>
  </head>
  
  <body>
    <div align="center">
       <p>
           Your Message:
           <input id="msg"  />
           <input type="button" value="Send" οnclick="sendMessage()" />
       </p>
    </div>
  </body>
</html>

注意需要引用一下几个js

jquery-1.8.3.min.js--页面上使用到了jquery

dwr/util.js-----与下面的js都是dwr内置的,固定写法

dwr/engine.js

dwr/interface/MessagePush.js---这个是我们在dwr.xml中配置的 javascript="MessagePush",名字对应



效果

在文本框中输入一句话,然后点击send按钮,后台接收到消息后推送到前台页面


相关文章
|
人工智能 自然语言处理 搜索推荐
AI在医疗领域的应用有哪些?
【5月更文挑战第7天】AI在医疗领域的应用有哪些?
777 6
|
1天前
|
云安全 人工智能 算法
以“AI对抗AI”,阿里云验证码进入2.0时代
三层立体防护,用大模型打赢人机攻防战
1278 1
|
9天前
|
编解码 人工智能 自然语言处理
⚽阿里云百炼通义万相 2.6 视频生成玩法手册
通义万相Wan 2.6是全球首个支持角色扮演的AI视频生成模型,可基于参考视频形象与音色生成多角色合拍、多镜头叙事的15秒长视频,实现声画同步、智能分镜,适用于影视创作、营销展示等场景。
678 4
|
1天前
|
机器学习/深度学习 安全 API
MAI-UI 开源:通用 GUI 智能体基座登顶 SOTA!
MAI-UI是通义实验室推出的全尺寸GUI智能体基座模型,原生集成用户交互、MCP工具调用与端云协同能力。支持跨App操作、模糊语义理解与主动提问澄清,通过大规模在线强化学习实现复杂任务自动化,在出行、办公等高频场景中表现卓越,已登顶ScreenSpot-Pro、MobileWorld等多项SOTA评测。
459 2
|
2天前
|
人工智能 Rust 运维
这个神器让你白嫖ClaudeOpus 4.5,Gemini 3!还能接Claude Code等任意平台
加我进AI讨论学习群,公众号右下角“联系方式”文末有老金的 开源知识库地址·全免费
|
1天前
|
存储 弹性计算 安全
阿里云服务器4核8G收费标准和活动价格参考:u2a实例898.20元起,计算型c9a3459.05元起
现在租用阿里云服务器4核8G价格是多少?具体价格及配置详情如下:云服务器ECS通用算力型u2a实例,配备4核8G配置、1M带宽及40G ESSD云盘(作为系统盘),其活动价格为898.20元/1年起;此外,ECS计算型c9a实例4核8G配置搭配20G ESSD云盘,活动价格为3459.05元/1年起。在阿里云的当前活动中,4核8G云服务器提供了多种实例规格供用户选择,不同实例规格及带宽的组合将带来不同的优惠价格。本文为大家解析阿里云服务器4核8G配置的实例规格收费标准与最新活动价格情况,以供参考。
222 150