DWR构建的简单聊天程序-供初学者学习

DWR允许客户端脚本远程调用服务器端的类方法。使用它可以很容易的构建ajax程序。在此,简要说明一下如何通过DWR构建一个简单的一对一聊天程序。

创新互联建站专业为企业提供察隅网站建设、察隅做网站、察隅网站设计、察隅网站制作等企业网站建设、网页设计与制作、察隅企业网站模板建站服务,十余年察隅做网站经验,不只是建网站,更提供有价值的思路和整体网络服务。

1.首先配置web.xml



        contextConfigLocation
        /WEB-INF/applicationContext*.xml


        org.springframework.web.context.ContextLoaderListener


DWR (Direct Web Remoting)
A Simple Demo DWR

 dwr-invoker
 org.directwebremoting.servlet.DwrServlet

      debug
      true


      activeReverseAjaxEnabled
      true


      initApplicationScopeCreatorsAtStartup
      true


      maxWaitAfterWrite
      -1
                                                 
 
   allowScriptTagRemoting
   true
 
 3


    dwr-invoker
    /dwr/*

  
  
  scriptSessionListener
  com.hb.util.InitScriptSessionListener
  8
  

2.配置dwr.xml


      
 

dwr中create元素中creator属性为spring,表示,名为“dwrMessageService”的bean由spring进行管理,javascript属性值表示如何在客户端调用该bean,即通过该属性的值调用。dwr可以自动对javascript对象和java对象进行转化。convert元素的match属性即表示哪个java bean交由dwr进行互转。

3.spring配置文件如下



 

4.(1)com.dwr.MyMessageService类部分代码如下:

import com.util.initParam;
public boolean pushMessageToSomeOne(String userId,Message msg){
         /*将消息保存到数据库*/
           try {
               messageService.saveMessage(msg);
           } catch (Exception e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }
//调用接收方客户端的showMessageFromOne(msg)函数,将msg消息传递给接收方
ScriptBuffer script = new ScriptBuffer();           script.appendScript("showMessageFromOne(").
appendData(msg).appendScript(");");
      ScriptSession s1= initParam.sc.get(userId); //获取接收方的ScriptSession
      s1.addScript(script);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
           return true;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
       }

(2)com.util.initParam类

package com.util;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.directwebremoting.ScriptSession;
import com.dwr.ScriptSessionAndUser;
public class initParam {
 public static Map sc  =newHashMap();  // 保存用户id和该用户对应的ScriptSession
    public initParam(){}
}

(3)用来监听ScriptSession的Servlet:InitScriptSessionListener

package com.util;
import java.io.IOException;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpSession;
import org.directwebremoting.Container;
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;
public class InitScriptSessionListener extends GenericServlet {
   /* 监控ScriptSessionListener状态*/
 public void init()
    {
 Container container = ServerContextFactory.get().getContainer();
 ScriptSessionManager manager =container.getBean(ScriptSessionManager.class);
ScriptSessionListener listener = new AddScriptSessionListener();
        manager.addScriptSessionListener(listener);
    }
    @Override
    public void service(ServletRequest arg0, ServletResponse arg1)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        init();
                                                                                                                                                                                                                                                                                                                                                                                                                         
    }
                                                                                                                                                                                                                                                                                                                                                                                                                     
                                                                                                                                                                                                                                                                                                                                                                                                                     
}

(4)AddScriptSessionListener类

package com.util;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
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 AddScriptSessionListener implements ScriptSessionListener{
    public void sessionCreated(ScriptSessionEvent se) {
 /*客户端刷新页面后,将用户的session信息和ScriptSession重新绑定*/       
WebContext ct = WebContextFactory.get();
HttpSession session =ct.getHttpServletRequest().getSession();
initParam.sc.put(session.getAttribute("UsersId").toString(),
se.getSession());
                                                                                                                                                                                                                                                                                                                                                                                                 
    public void sessionDestroyed(ScriptSessionEvent se) {
        System.out.println(se.getSession()+"销毁");
    }
                                                                                                                                                                                                                                                                                                                                                                                             
}

5.客户端代码