日期:2014-05-16 浏览次数:20732 次
<init-param> <param-name>activeReverseAjaxEnabled</param-name> <param-value>true</param-value> </init-param>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>利用反向ajax实现页面聊天</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="dwr/interface/DWRHelper.js"></script> <script type="text/javascript" src="dwr/engine.js"></script> <script type="text/javascript" src="dwr/util.js"></script> <script type="text/javascript"> function sendMessage(){ DWRHelper.addMessage(dwr.util.getValue("myText")); } </script> </head> <body onload="dwr.engine.setActiveReverseAjax(true);"> <input type="text" id="myText" /> <input type="button" value="发送" onclick="sendMessage()" /> <div style="width: 300px; height: 300px; border: 1px solid blue"> <ul id="chatlog"></ul> </div> </body> </html>
package com.lamp; import java.util.Collection; import java.util.LinkedList; import org.directwebremoting.WebContext; import org.directwebremoting.WebContextFactory; import org.directwebremoting.proxy.dwr.Util; public class DWRHelper { LinkedList<Message> messages = new LinkedList<Message>(); public void addMessage(String text) { if (text.trim().length() > 0 || text != null) { messages.addFirst(new Message(text)); while (messages.size() > 10) { messages.removeLast(); } } System.out.println(text); WebContext context = WebContextFactory.get(); // 获得容器上下问 String currentPage = context.getCurrentPage(); // 获得当前页面 Util util = new Util(context.getScriptSession()); util.setValue("myText", ""); // 清空当前编辑框 Collection sessions = context.getScriptSessionsByPage(currentPage); // 打开当前页面的所有会话集合 Util utilAll = new Util(sessions); utilAll.removeAllOptions("chatlog"); //清空原来列表的内容 utilAll.addOptions("chatlog", messages, "text"); //将消息显示在列表中 } }
package com.lamp; public class Message { private String text; public Message() { } public Message(String text) { this.text = text; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
<create javascript="DWRHelper" creator="new" scope="application"> <param name="class" value="com.lamp.DWRHelper"></param> </create> <convert match="com.lamp.Message" converter="bean"> <param name="include" value="id,text"></param> </convert>