最近网上看的代码 敲下来试试 行得通 于是拿到这里和大家分享下。
首先 下载DWR的JAR包 下载地址http://directwebremoting.org/dwr/downloads/index.html
接下来 在web工程中加入相应的jar包,因为用到了spring的消息驱动机制 如下:
Message.java
import java.util.Date; /** * 作为信息传递的基础类 * @author frank59 * */ public class Message { private int id; private String msg; private Date time; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } }ChatMessageEvent.java
import org.springframework.context.ApplicationEvent; /** * 自定义事件类 * @author frank59 * */ public class ChatMessageEvent extends ApplicationEvent{ public ChatMessageEvent(Object source) { super(source); } private static final long serialVersionUID = -6626763488290315190L; }
import java.util.Collection; import java.util.Date; import javax.servlet.ServletContext; import org.directwebremoting.ScriptBuffer; import org.directwebremoting.ScriptSession; import org.directwebremoting.ServerContext; import org.directwebremoting.ServerContextFactory; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.web.context.ServletContextAware; import entity.Message; /** * MessageEvent事件的监听类 * 需要spring的支持 利用spring的消息驱动机制 * @author frank59 * */ @SuppressWarnings("unchecked") public class ChatMessageClient implements ApplicationListener, ServletContextAware { private ServletContext ctx; @SuppressWarnings("deprecation") public void onApplicationEvent(ApplicationEvent event) { // 如果事件类型是ChatMessageEvent就执行下面操作 if (event instanceof ChatMessageEvent) { Message msg = (Message) event.getSource(); ServerContext context = ServerContextFactory.get(); // 获得客户端所有chat页面script session连接数 Collection<ScriptSession> sessions = context .getScriptSessionsByPage(ctx.getContextPath() + "/chat.jsp"); for (ScriptSession session : sessions) { ScriptBuffer sb = new ScriptBuffer(); Date time = msg.getTime(); String s = time.getYear() + "-" + (time.getMonth() + 1) + "-" + time.getDate() + " " + time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds(); System.out.println(s);/////////////////s // 执行setMessage方法 sb.appendScript("showMessage({msg: '").appendScript( msg.getMsg()).appendScript("', time: '") .appendScript(s).appendScript("'})"); System.out.println(sb.toString());/////////////////sb //执行客户端script session方法,相当于浏览器执行JavaScript代码 //上面就会执行客户端浏览器中的showMessage方法,并且传递一个对象过去 session.addScript(sb); } } } public void setServletContext(ServletContext arg0) { this.ctx = arg0; } }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean id="chatService" class="chat.ChatService"/> <bean id="chatMessageClient" class="chat.ChatMessageClient"/> </beans>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> <convert match="entity.Message" converter="bean"> <param name="include" value="msg,time" /> </convert> <create creator="spring" javascript="ChatService"> <param name="beanName" value="chatService" /> </create> </allow> </dwr>
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- 加载Spring容器配置 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 设置Spring容器加载配置文件路径 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:applicationContext-*.xml</param-value> </context-param> <listener> <listener-class>org.directwebremoting.servlet.DwrListener</listener-class> </listener> <servlet> <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> <!-- dwr的comet控制 --> <init-param> <param-name>pollAndCometEnabled</param-name> <param-value>true</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dwr-invoker</servlet-name> <url-pattern>/dwr/*</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
<%@ 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 'chat.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"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script type="text/javascript" src="${pageContext.request.contextPath }/dwr/engine.js"></script> <script type="text/javascript" src="${pageContext.request.contextPath }/dwr/util.js"></script> <script type="text/javascript" src="${pageContext.request.contextPath }/dwr/interface/ChatService.js"></script> <script type="text/javascript"> function send() { var time = new Date(); var content = dwr.util.getValue("content"); var name = dwr.util.getValue("userName"); var info = encodeURI(encodeURI(name + " say:\n" + content)); var msg = {"msg": info, "time": time}; dwr.util.setValue("content", ""); if (!!content) { ChatService.sendMessage(msg); } else { alert("发送的内容不能为空!"); } } function showMessage(data) { var message = decodeURI(decodeURI(data.msg)); var text = dwr.util.getValue("info"); if (!!text) { dwr.util.setValue("info", text + "\n" + data.time + " " + message); } else { dwr.util.setValue("info", data.time + " " + message); } } </script> </head> <body onload="dwr.engine.setActiveReverseAjax(true);"> <textarea rows="20" cols="60" id="info" readonly="readonly"></textarea> <hr /> 昵称:<input type="text" id="userName" /> <br /> 消息:<textarea rows="5" cols="30" id="content"></textarea> <input type="button" value=" Send " onclick="send()" style="height: 85px; width: 85px;" /> </body> </html>