反向Ajax技术dwr

坚持着执着 2012-03-29

反向Ajax技术是服务器向客户端主动的发关数据,很大的减少了服务的负担。

学习新的知识点就要多写些自己的Demo,在这里写一个最简单的例子,以作笔记:

sendMsg.jsp负责向表中添加数据(更新数据库),showMsg.jsp用来实时显示前者添加的信息。

dwr.xml

<!DOCTYPEdwrPUBLIC"-//GetAheadLimited//DTDDirectWebRemoting3.0//EN""http://getahead.org/dwr//dwr30.dtd"><dwr>

<allow>

<createcreator="new"javascript="SendMsg"scope="session">

<paramname="class"value="com.dwr.bean.SendMsg"/>

</create>

</allow>

</dwr>

SendMsg.java

packagecom.dwr.bean;

importjava.util.Collection;

importjava.util.LinkedList;

importorg.directwebremoting.WebContext;

importorg.directwebremoting.WebContextFactory;

importorg.directwebremoting.proxy.dwr.Util;

/**

*DWR反向Ajax示例

*@author︶ㄣ旺

*@version1.0

**/

publicclassSendMsg

{

publicstaticWebContextwctx=null;

//用一个List代表数据库来储存消息

privateLinkedListlist=newLinkedList();

//调用添加和显示方法

publicvoidsendMsg(Stringmsg)

{

list.addFirst(msg);

//最多保留10条聊天记录

if(list.size()>10){

list.removeLast();

}

wctx=WebContextFactory.get();

UtilutilThis=newUtil(wctx.getScriptSession());

//使用utilThis重置Id属性为msg的文本框的内容

utilThis.setValue("msg","请输入信息");

StringcurrentPage="/login/showMsg.jsp";//要推信息的页面地址

//获得所有已经打开此页面的会话

Collectionsessions=wctx.getScriptSessionsByPage(currentPage);

UtilutilAll=newUtil(sessions);

//将消息从LinkedList中取出来,放放到一个字符串数组中

String[]msgs=newString[list.size()];

msgs=(String[])list.toArray(msgs);

//先清空页面的消息内容,去除ul元素下所有元素

utilAll.removeAllOptions("ul");

//向页面添加消息内容

utilAll.addOptions("ul",msgs);

}

}

sendMsg.jsp

<%@pagelanguage="java"pageEncoding="UTF-8"%>

<%@pageisELIgnored="false"%>

<html>

<head>

<title>DWR反向Ajax示例</title>

<metahttp-equiv="pragma"content="no-cache">

<metahttp-equiv="cache-control"content="no-cache">

<scripttype='text/javascript'src='${pageContext.request.contextPath}/dwr/interface/SendMsg.js'></script>

<scripttype='text/javascript'src='${pageContext.request.contextPath}/dwr/engine.js'></script>

<scripttype='text/javascript'src='${pageContext.request.contextPath}/dwr/util.js'></script>

<scripttype="text/javascript">

functionsendMessage()

{

varmsg=$("msg").value;

SendMsg.sendMsg(msg);

}

</script>

</head>

<body>

DWR反向Ajax示例信息添加<br>

输入信息:<inputtype="text"id="msg"name="msg"onkeypress="dwr.util.onReturn(event,sendMessage)">

</body>

</html>

showMsg.jsp

<%@pagelanguage="java"pageEncoding="UTF-8"%>

<%@pageisELIgnored="false"%>

<html>

<head>

<title>DWR反向Ajax示例</title>

<metahttp-equiv="pragma"content="no-cache">

<metahttp-equiv="cache-control"content="no-cache">

<scripttype='text/javascript'src='${pageContext.request.contextPath}/dwr/engine.js'></script>

<scripttype='text/javascript'src='${pageContext.request.contextPath}/dwr/util.js'></script>

</head>

<bodyonload="dwr.engine.setActiveReverseAjax(true);">

DWR反向Ajax示例信息显示<br>

ul:

<ulid="ul">

</ul>

</body>

</html>

运行效果如图:

这时showMsg.jsp一直处于失去焦点状态,却能实时地显示服务器端更新的数据

相关推荐

mmywcoco / 0评论 2020-06-06