1.在JSP页面加入展示代码:
新消息<input type="text" id="serverResponse" size="2"/>
2.新建一个JAVA类:
package com.msg; public class MsgDeal { public int getMsg(int uid){ MsgDao msgdao = new MsgDao(); return msgdao.getMsg(uid);//从数据库获取某个用户的新消息条数,这里自行实现即可 } }
3.在WEB-INF下新建一个dwr.xml文件,配置JAVA类
<?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> <create creator="new" javascript="Msgdeal"> <param name="class" value="com.msg.MsgDeal"/> </create> </allow> </dwr>
说明:1.x使用:<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 1.0//EN" "http://getahead.org/dwr/dwr10.dtd">
2.x使用:<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN" "http://getahead.org/dwr/dwr20.dtd">
3.x使用:<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN" "http://getahead.org/dwr/dwr30.dtd">
4.在web.xml中配置dwr:
<!-- dwr configuration -->
<servlet>
<display-name>DWR Servlet</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>
</servlet>
<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
说明:
如果版本是1.x,那servlet-class是用:uk.ltd.getahead.dwr.DWRServlet
2.x,3.x使用:org.directwebremoting.servlet.DwrServlet
5.在页面配置最后的脚本:
<script type="text/javascript" src="dwr/engine.js"></script>
<script type="text/javascript" src="dwr/util.js"></script>
<script type="text/javascript" src="dwr/interface/Msgdeal.js"></script> //Msgdeal的名字是dwr.xml中配置的名字
<script type="text/javascript">
function Test1(){
var _data = "";
dwr.engine.setAsync(false);//设置同步
Msgdeal.getMsg(1,function(data){_data = data;});//调用java中MsgDeal类的消息处理方法,这里的1是手动测试加入的,模拟的当前用户ID为1
dwr.engine.setAsync(true); //设置到初始状态
document.getElementById("serverResponse").value= _data; //设置获取的值
}
function init(){
Test1();//先加载一次
var time = 5000*10; //5*10秒
window.setInterval('Test1()',time); //关于setInterval的解释参见:http://zhoujingxian.iteye.com/blog/788719
}
</script>
6.加入dwr.jar包(如果是2.0以上的版本需要同时导入commons-logging-1.0.4.jar和log4j-1.2.12.jar以上版本的包)