您的位置:首页 > 编程语言 > Java开发

spring整合dwr 3.0 聊天功能

2013-02-17 12:35 288 查看
此文章只是一个测试例子 过多的我就不往上贴了。仅供大家参考学习。此文章包含对scriptSession的处理。DWR文件配置

<?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>
  <convert match="com.*.*.dwr.entity.MessageDwr" converter="bean" />

spring方式创建
  <create creator="spring" javascript="ChatManager">
   <param name="beanName" value="chatManager" />
  </create>
 </allow>

</dwr>


web.xml配置

<!-- dwr反转ajax配置 -->
 <servlet>
  <display-name>DWR Sevlet</display-name>
  <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>  
            <description>调试DWR,发布系统时应将其设为false</description>  
            <param-name>debug</param-name>  
            <param-value>true</param-value>  
        </init-param>  

  <init-param>
   <description>日志级别有效值为: FATAL, ERROR, WARN (the default), INFO and DEBUG.</description>
   <param-name>logLevel</param-name>
   <param-value>DEBUG</param-value>
  </init-param>
        <init-param>  
            <description>使用服务器推技术(反转AJAX)</description>  
            <param-name>activeReverseAjaxEnabled</param-name>  
            <param-value>true</param-value>  
        </init-param>  
        <init-param>  
            <param-name>  
                initApplicationScopeCreatorsAtStartup   
            </param-name>  
            <param-value>true</param-value>  
        </init-param>  
        <init-param>  
            <param-name>maxWaitAfterWrite</param-name>  
            <param-value>100</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> 

   <!-- 如果你想在你的service中使用request 请在web.xml文件中加入  Spring中添加 request -->
 <listener>
     <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
 </listener>


配置一切就绪后 下面开始代码

//controller开始

package com.sme.web.dwr;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import com.sme.web.core.BaseController;

@Results({ @Result(name = "reload", location = "/WEB-INF/content/bim/chat.jsp") })
public class ChatMessageClientController extends BaseController {

 /**
  * 
  */
 private static final long serialVersionUID = 1L;
 private String name;
 private Long id;

 public String input() {
  name = this.getCreatorId().getName();
  id = this.getCreatorId().getId();
  return "reload";
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public Long getId() {
  return id;
 }

 public void setId(Long id) {
  this.id = id;
 }

}


关键service开始

package com.baoku.common.dwr.service;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.proxy.dwr.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baoku.common.dwr.entity.MessageDwr;
import com.baoku.tools.string.StringUtils;

@Service("chatManager")
public class ChatManager {
    @Autowired
    private HttpServletRequest request;
    /** 保存当前在线用户列表 */
    public static Set<MessageDwr> users = new HashSet<MessageDwr>();
    private static Map<String, ScriptSession> SCR_MAPS = new HashMap<String, ScriptSession>();

    /**
     * 更新当前在线用户
     * 
     * @param userid
     * @param username
     * @return
     */
    public String updateUsersList(String userid, String username) {
        MessageDwr user = new MessageDwr(userid, username);
        // 保存用户到列表
        users.add(user);
        // 将用户id和页面脚本session绑定
        this.setScriptSessionFlag(userid);
        // 获取当前最新scriptSession
        Collection<ScriptSession> sessions = SCR_MAPS.values();
        Util util = new Util(sessions);
        // 处理这些页面中的一些元素
        util.removeAllOptions("receiver");
        util.addOptions("receiver", users, "byid", "msg");

        return null;
    }

    /**
     * 将用户id和页面脚本session绑定
     * 
     * @param userid
     */
    public void setScriptSessionFlag(String userid) {
        ScriptSession session = getOnlyScriptSession(userid);
        if (null != session.getAttribute("userid")) {
            String uid = (String) session.getAttribute("userid");
            if (StringUtils.isBlank(uid)) {
                session.setAttribute("userid", userid);
            }
        } else {
            session.setAttribute("userid", userid);
        }
    }

    // 储存最新scriptSession
    public ScriptSession getOnlyScriptSession(String userid) {
        ScriptSession scriptSession = SCR_MAPS.get(userid);
        scriptSession = WebContextFactory.get().getScriptSession();
        SCR_MAPS.put(userid, scriptSession);
        return scriptSession;
    }

    /**
     * 根据用户id获得指定用户的页面脚本session
     * 
     * @param userid
     * @return
     */
    public ScriptSession getScriptSession(String userid) {
        ScriptSession scriptSessions = null;
        Collection<ScriptSession> sessions = SCR_MAPS.values();
        for (ScriptSession session : sessions) {
            String xuserid = (String) session.getAttribute("userid");
            if (xuserid != null && xuserid.equals(userid)) {
                scriptSessions = session;
            }
        }
        return scriptSessions;
    }

    /**
     * 发送消息
     * 
     * @param sender
     *            发送者
     * @param receiverid
     *            接受者id
     * @param msg
     *            消息
     */
    public void send(String sender, String receiverid, String msg) {
        ScriptSession session = this.getScriptSession(receiverid);
        ScriptBuffer sb = new ScriptBuffer();
        sb.appendScript("showMessage({msg: ")
                .appendData(msg)
                .appendScript(", time: '")
                .appendScript(
                        new SimpleDateFormat("HH:mm:ss").format(new Date()))
                .appendScript("',sender:'").appendScript(sender)
                .appendScript("'})");
        session.addScript(sb);
    }

}


//实体开始

@Entity
@Table(name = "COMMON_MESSAGE")
public class MessageDwr implements Serializable {
 /**
  * 
  */
 private static final long serialVersionUID = 1L;
 private Long id;
 private String msg;
 private String time;

 @Id
 @SequenceGenerator(name = "SME_SEQ", sequenceName = "COMMON_MESSAGE_SEQ", allocationSize = 1)
 @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SME_SEQ")
 public Long getId() {
  return id;
 }

 public void setId(Long id) {
  this.id = id;
 }

 @Column(length = 100)
 public String getMsg() {
  return msg;
 }

 public void setMsg(String msg) {
  this.msg = msg;
 }

 @Column(length = 20)
 public String getTime() {
  return time;
 }

 public void setTime(String time) {
  this.time = time;
 }

 private String byid;

 @Transactional
 public String getByid() {
  return byid;
 }

 public void setByid(String byid) {
  this.byid = byid;
 }

 public MessageDwr(String userid, String username) {
  super();
  this.byid = userid;
  this.msg = username;
 }

//在Set中添加相同实体会重 把hashCode重写

 @Override
 public int hashCode() {
  return byid.hashCode() * 7 + msg.hashCode() * 11;
 }

 @Override
 public boolean equals(Object obj) {
  if (obj.getClass() != this.getClass()) {
   return false;
  }
  MessageDwr meDwr = (MessageDwr) obj;
  if (null != this.getByid() && this.getByid().equals(meDwr.getByid())
    && this.getMsg() != null
    && this.getMsg().equals(meDwr.getMsg())) {
   return true;
  }
  return false;
 }


//JSP开始

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ include file="http://www.cnblogs.com/../common/taglibs.jsp"%>
<html>  
    <head>  
        <title>chat</title>  
        <!-- jQuery -->
        <script type='text/javascript' src="${ctx}/plugin/jquery.js"></script>
        <!-- 通用JS -->
        <script type='text/javascript' src="${ctx}/plugin/common.js" ></script>
        <script type='text/javascript' src='${ctx}/dwr/interface/ChatManager.js'></script>  
        <script type='text/javascript' src='${ctx}/dwr/engine.js'></script>  
        <script type='text/javascript' src='${ctx}/dwr/util.js'></script>  
        <script type="text/javascript">
        dwr.engine.setNotifyServerOnPageUnload(true);
        /**  
         * 页面初始化  
         */  
        function init() {   
            ChatManager.updateUsersList($('userid').value,$('username').value); // 当你打开界面的时候,先获得在线用户列表.   
        }   

        /**  
         * 发送消息  
         */  
        function send() {   
            var sender = dwr.util.getValue('username'); // 获得发送者名字   
        var receiver = dwr.util.getValu('receiver'); // 获得接受者id 
            var msg = dwr.util.getValue('message'); // 获得消息内容   
            ChatManager.send(sender, receiver, msg); // 发送消息   
        }   
          
        function showMessage(data) {
            var message = decodeURIComponent(decodeURIComponent(data.msg));
            var text = dwr.util.getValue("info");
            if (!!text) {  
                dwr.util.setValue("info", text+"\n" +data.sender+ " " + data.time + "\n" + message);
            } else {
                dwr.util.setValue("info", data.sender+" "+data.time + "\n" + message);
            }
        }

        window.onload = init;//页面加载完毕后执行初始化方法init  
        
        </script>
    </head>  
    <body>  
        <input type="hidden" name="userid" value="${id}"/>  
        <table class="tablemodule">
 <thead>
  <tr>
   <td>昵称: ${name}<input type="hidden" name="username" value="${name}"/> </td>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>
    <textarea rows="20" cols="60" id="info" readonly="readonly"></textarea>
   <textarea  rows="3" cols="50" name="message" id="message"></textarea>
   <input type="button" value="发送" id="send" name="send" onclick="send();" />  
   </td>
   <td style="vertical-align: top;">
    <select name="receiver" id="receiver"  style="width:300px; height:200px;" multiple="multiple">  
            </select> 
          </td>
  </tr>
 </tbody>
</table>
    </body>  
</html>


//以上就是我的介绍 关于更多的DWR问题 请google/以下是我运行效果
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: