dwr+maven实现java和js方法互相调用,实现推送, 完整切超简单例子

来源:互联网 发布:假面骑士空我 知乎 编辑:程序博客网 时间:2024/05/21 05:43


本文算是完全转载的,只是本人使用的是maven工具:

参考原文:

dwr入门:http://blog.csdn.net/Marksinoberg/article/details/55505423

精准推送:http://blog.csdn.net/pangliang_csdn/article/details/68945872

推送对象:http://blog.csdn.net/rongyongfeikai2/article/details/7778082

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  <modelVersion>4.0.0</modelVersion>  <groupId>com.jzy</groupId>  <artifactId>dwr</artifactId>  <packaging>war</packaging>  <version>0.0.1-SNAPSHOT</version>  <name>dwr Maven Webapp</name>  <url>http://maven.apache.org</url>  <dependencies>    <dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <version>3.8.1</version>      <scope>test</scope>    </dependency>    <!-- dwr推送 -->    <dependency>    <groupId>org.directwebremoting</groupId>    <artifactId>dwr</artifactId>    <version>3.0.0-RELEASE</version></dependency><!-- https://mvnrepository.com/artifact/commons-logging/commons-logging --><dependency>    <groupId>commons-logging</groupId>    <artifactId>commons-logging</artifactId>    <version>1.1.1</version></dependency>  </dependencies>  <build>    <finalName>dwr</finalName>  </build></project>

test.jsp

注意:里面引入的


/util.js,
engine.js,
DwrPush.js
可以根据以下地址中列出的地址进行引入:

http://localhost:8080/项目名/dwr/  点击页面上的DwrPush,里面又引入地址

<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Insert title here</title><script type='text/javascript' src='/dwr/dwr/util.js'></script> <script type='text/javascript' src='/dwr/dwr/engine.js'></script>  <script type='text/javascript' src='/dwr/dwr/interface/DwrPush.js'></script>      <script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script><script type="text/javascript"> $(document).ready(function(){alert("开始");//dwr.engine.setActiveReverseAjax(true); dwr.engine.setActiveReverseAjax(true) ;$("#send").click(function(){var data = $("#msg").val();DwrPush.Send(data);}); });function callback(msg){$("#ul").html(msg); }</script></head><body><!-- <h1>test</h1> --><ul id="ul" style="color:red;font-size:60px;"></ul><input type="text" name="msg" id="msg" size="30" style="height: 60px;font-size:35px;" /><input type="button"  value="发布信息" id="send"/></body></html>


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="DwrPush">            <param name="class" value="com.dwr.test.HelloDwr"></param>            <!-- 这个标签可以写也可以不写,无所谓的-->            <include method="Send"/>        </create>        <!-- 可以传递对象参数 ,match 为对应的java对象,value对应的是包含的字段-->        <!-- <convert converter="bean" match="com.dwr.UserBean">              <param name="include" value="id,userName,psw"></param>          </convert>   -->    </allow></dwr>


HwlloDwr.java

package com.dwr.test;import java.util.Collection;import org.directwebremoting.ScriptBuffer;import org.directwebremoting.ScriptSession;import org.directwebremoting.WebContext;import org.directwebremoting.WebContextFactory; import org.directwebremoting.proxy.dwr.Util;public class HelloDwr {   @SuppressWarnings("deprecation")    public static void Send(String msg){        WebContext webContext = WebContextFactory.get();        @SuppressWarnings("deprecation")        Collection<ScriptSession> sessions = webContext.getAllScriptSessions();        // 构建发送所需的JS脚本        ScriptBuffer scriptBuffer = new ScriptBuffer();        // 调用客户端的js脚本函数        scriptBuffer.appendScript("callback(");        // 这个msg可以被过滤处理一下,或者做其他的处理操作。这视需求而定。        scriptBuffer.appendData(msg);        scriptBuffer.appendScript(")");        // 为所有的用户服务        @SuppressWarnings("deprecation")        Util util = new Util(sessions);        util.addScript(scriptBuffer);    }}

web.xml

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" ><web-app>  <display-name>Archetype Created Web Application</display-name>            <listener>      <listener-class>org.directwebremoting.servlet.DwrListener</listener-class>    </listener>   <servlet>      <servlet-name>dwr</servlet-name>      <!-- version 2 * -->      <!-- <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class> -->      <!-- 2.x 和3.x版本的都可以 -->      <!-- <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class> -->      <!-- 3.x版本的还可以使用下面这个 -->       <servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>      <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>      <!-- 是能够从其他域请求true:开启; false:关闭 -->      <init-param>          <param-name>crossDomainSessionSecurity</param-name>          <param-value>false</param-value>      </init-param>      <!-- 允许远程调用js -->      <init-param>          <param-name>allowScriptTagRemoting</param-name>          <param-value>true</param-value>      </init-param>      <load-on-startup>1</load-on-startup>    </servlet>  <servlet-mapping>      <servlet-name>dwr</servlet-name>      <url-pattern>/dwr/*</url-pattern>  </servlet-mapping>      </web-app>
以上实现的是推送简单的字符串,还可以实现推送对象。
/********************************   推送对象  ,配置文件增加以下红色部分,其他同上简单对象 ********************************************************/
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="DwrPush">            <param name="class" value="com.dwr.test.HelloDwr"></param>            <!-- 这个标签可以写也可以不写,无所谓的-->            <include method="Send"/>            <include method="bindUser"/>            <include method="sendOne"/>            <include method="sendMany"/>        </create>                <!-- 可以传递对象参数 ,match 为对应的java对象,value对应的是包含的字段 -->        <convert converter="bean" match="com.dwr.pojo.Message">              <param name="include" value="username,age,height"></param>          </convert>              </allow></dwr>
//添加pojo类
public class Message {private String title;private String content;private String url;public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}public String getUrl() {return url;}public void setUrl(String url) {this.url = url;} }
//发送的java方法
public static void Send(String msg){    Message newMessage = new Message();        newMessage.setTitle("下雪了");        newMessage.setContent("雪地里来了一群小画家");        newMessage.setUrl("baidu.com");                WebContext webContext = WebContextFactory.get();//        @SuppressWarnings("deprecation")        Collection<ScriptSession> sessions = webContext.getAllScriptSessions();        // 构建发送所需的JS脚本        ScriptBuffer scriptBuffer = new ScriptBuffer();        // 调用客户端的js脚本函数        scriptBuffer.appendScript("callback(");        // 这个msg可以被过滤处理一下,或者做其他的处理操作。这视需求而定。        scriptBuffer.appendData(newMessage);        scriptBuffer.appendScript(")");        // 为所有的用户服务//        @SuppressWarnings("deprecation")        Util util = new Util(sessions);        util.addScript(scriptBuffer);    }
//js 接收函数
function callback(msg){console.log(msg);$("#ul").html(msg.url); 
/****************************************************     精准推送到客户端      ********************************************/
原理:一般与登陆联系。
1、客户端执行方法,在自己的scriptsession中放入标识
2、服务端有特定方法过滤出你要推送的客户端scriptsession集合,然后逐个客户端推送消息
实现代码:配置文件都不用动,如果要推送对象消息,以上新加的dwr.xml配置部分必须加上
首先有个scriptsession管理类:
import javax.servlet.ServletException;  import javax.servlet.http.HttpSession;    import org.directwebremoting.Container;  import org.directwebremoting.ServerContextFactory;  import org.directwebremoting.WebContextFactory;  import org.directwebremoting.event.ScriptSessionEvent;  import org.directwebremoting.event.ScriptSessionListener;  import org.directwebremoting.extend.ScriptSessionManager;  import org.directwebremoting.servlet.DwrServlet;  public class DwrScriptSessionManagerUtil extends DwrServlet {public void init() throws ServletException {            //获取scriptsession 的上下文        Container container = ServerContextFactory.get().getContainer();        //获取当前scriptsession        ScriptSessionManager manager = container.getBean(ScriptSessionManager.class);                    //scripsession监听器        ScriptSessionListener listener = new ScriptSessionListener() {                //有scriptsession创建            public void sessionCreated(ScriptSessionEvent ev) {                        HttpSession session = WebContextFactory.get().getSession();                        String userId = (String) session.getAttribute("userId");                        System.out.println(">>>>>>>>>a ScriptSession is created!");                                    ev.getSession().setAttribute("userId", userId);                    }                //有scriptsession销毁            public void sessionDestroyed(ScriptSessionEvent ev) {                        System.out.println(">>>>>>>>a ScriptSession is distroyed");                    }                };                manager.addScriptSessionListener(listener);            }    }
js:
//绑定账号
$("#bindusernm").click(function(){var data = $("#username").val();console.log(data);DwrPush.bindUser(data);});
//接受java推送的对象数据
function showMessage(autoMessage){       console.log(autoMessage);    } 
 
/**  *保存账号名**/ public void bindUser(String userName) {
        ScriptSession scriptSession = WebContextFactory.get().getScriptSession();        System.out.println("绑定的账号是:"+userName);        scriptSession.setAttribute("userId", userName); //把前台传入的id保存        DwrScriptSessionManagerUtil dwrScriptSessionManagerUtil = new DwrScriptSessionManagerUtil();        try {                 dwrScriptSessionManagerUtil.init();        } catch (ServletException e) {            e.printStackTrace();            }        } 
 
//java后台推送方法
public void sendMany(String recievStr){//修改成功给张三,李四发消息 final String[] recieverArr = recievStr.split(","); //排除重复的账号final Set<String> receiverSet = new HashSet<String>();for(String recieve : recieverArr){receiverSet.add(recieve);}            final Message newMessage = new Message();        newMessage.setTitle("下雪了");        newMessage.setContent("雪地里来了一群小画家");        newMessage.setUrl("baidu.com");        Browser.withAllSessionsFiltered(new ScriptSessionFilter(){              public boolean match(ScriptSession session){                   if (session.getAttribute("userId") == null){                     return false;                }else{                 String attribute = (String) session.getAttribute("userId");                 for(String reciever : receiverSet){                 if(attribute.equals(reciever)){                 return true;                }                }                 return false;                }            }          }, new Runnable(){              private ScriptBuffer script = new ScriptBuffer();             public void run(){                  script.appendCall("showMessage", newMessage);                 Collection<ScriptSession> sessions = Browser.getTargetSessions();                  for (ScriptSession scriptSession : sessions){                    scriptSession.addScript(script);                  }              }          });   }