第一、在项目中引入dwr.jar,然后在web.xml中进行配置,配置如下:
- <servlet>
- <servlet-name>dwr-invoker</servlet-name>
- <servlet-class>
- org.directwebremoting.servlet.DwrServlet
- </servlet-class>
- <init-param>
- <param-name>crossDomainSessionSecurity</param-name>
- <param-value>false</param-value>
- </init-param>
- <init-param>
- <param-name>allowScriptTagRemoting</param-name>
- <param-value>true</param-value>
- </init-param>
- <init-param>
- <param-name>classes</param-name>
- <param-value>java.lang.Object</param-value>
- </init-param>
- <init-param>
- <param-name>activeReverseAjaxEnabled</param-name>
- <param-value>true</param-value>
- </init-param>
- <init-param>
- <param-name>initApplicationScopeCreatorsAtStartup</param-name>
- <param-value>true</param-value>
- </init-param>
- <init-param>
- <param-name>maxWaitAfterWrite</param-name>
- <param-value>3000</param-value>
- </init-param>
- <init-param>
- <param-name>debug</param-name>
- <param-value>true</param-value>
- </init-param>
- <init-param>
- <param-name>logLevel</param-name>
- <param-value>WARN</param-value>
- </init-param>
- </servlet>
第二:在web.xml的同级目录下新建dwr.xml文件,内容如下
- <!DOCTYPEdwrPUBLIC
- "-//GetAheadLimited//DTDDirectWebRemoting3.0//EN"
- "http://getahead.org/dwr/dwr30.dtd">
- <dwr>
- <alow>
- <createcreator="new"javascript="MessagePush">
- <paramname="class"value="com.huatech.messageremind.service.MessagePush"/>
- </create>
- <createcreator="new"javascript="TestPush">
- <paramname="class"value="com.huatech.messageremind.service.Test"/>
- </create>
- </alow>
- </dwr>
这个是dwr的基本配置,MessagePush在页面的javascript中使用,这个是对被推送页面开放的java类,Test是对推送页面开放的java类。场景:管理员后台登陆,发布一条消息,通过Test推送到后台,后台通过MessagePush推送给指定的用户,当然,至于怎么找到指定的用户,下面会说。
第三,被推送的页面代码
- <%@pagelanguage="java"import="java.util.*"pageEncoding="utf-8"%>
- <%
- Stringpath=request.getContextPath();
- StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
- <html>
- <head>
- <basehref="<%=basePath%>">
- <title>DWRDEMO</title>
- <metahttp-equiv="pragma"content="no-cache">
- <metahttp-equiv="cache-control"content="no-cache">
- <metahttp-equiv="expires"content="0">
- <metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">
- <metahttp-equiv="description"content="Thisismypage">
- </head>
- <scripttype='text/javascript'src='dwr/engine.js'></script>
- <scripttype='text/javascript'src='dwr/util.js'></script>
- <scripttype="text/javascript"src="dwr/interface/MessagePush.js"></script>
- <scripttype="text/javascript">
- //通过该方法与后台交互,确保推送时能找到指定用户
- functiononPageLoad(){
- varuserId='${userinfo.humanid}';
- MessagePush.onPageLoad(userId);
- }
- //推送信息
- functionshowMessage(autoMessage){
- alert(autoMessage);
- }
- </script>
- <bodyonload="onPageLoad();dwr.engine.setActiveReverseAjax(true);dwr.engine.setNotifyServerOnPageUnload(true);;">
- ThisismyDWRDEOMpage.<hr>
- <br>
- <divid="DemoDiv">demo</div>
- </body>
- </html>
以上代码的简单解释:
页面页面onload的3个函数都是必须的,后两个是dwr的,第一个是将登录用户的userid与对应 的scriptSession进行处理,以便精确推送的时候能找到推送对象
第四 MessagePush类中实现的方法如下:
- publicvoidonPageLoad(StringuserId){
- ScriptSessionscriptSession=WebContextFactory.get().getScriptSession();
- scriptSession.setAttribute(userId,userId);
- DwrScriptSessionManagerUtildwrScriptSessionManagerUtil=newDwrScriptSessionManagerUtil();
- try{
- dwrScriptSessionManagerUtil.init();
- System.out.println("cacaca");
- }catch(ServletExceptione){
- e.printStackTrace();
- }
- }
里面对应的DwrScriptSessionManagerUtil 对应如下:
- importjavax.servlet.ServletException;
- importjavax.servlet.http.HttpSession;
- importorg.directwebremoting.Container;
- importorg.directwebremoting.ServerContextFactory;
- importorg.directwebremoting.WebContextFactory;
- importorg.directwebremoting.event.ScriptSessionEvent;
- importorg.directwebremoting.event.ScriptSessionListener;
- importorg.directwebremoting.extend.ScriptSessionManager;
- importorg.directwebremoting.servlet.DwrServlet;
- publicclassDwrScriptSessionManagerUtilextendsDwrServlet{
- privatestaticfinallongserialVersionUID=-7504612622407420071L;
- publicvoidinit()throwsServletException{
- Containercontainer=ServerContextFactory.get().getContainer();
- ScriptSessionManagermanager=container.getBean(ScriptSessionManager.class);
- ScriptSessionListenerlistener=newScriptSessionListener(){
- publicvoidsessionCreated(ScriptSessionEventev){
- HttpSessionsession=WebContextFactory.get().getSession();
- StringuserId=((User)session.getAttribute("userinfo")).getHumanid()+"";
- System.out.println("aScriptSessioniscreated!");
- ev.getSession().setAttribute("userId",userId);
- }
- publicvoidsessionDestroyed(ScriptSessionEventev){
- System.out.println("aScriptSessionisdistroyed");
- }
- };
- manager.addScriptSessionListener(listener);
- }
- }
第五 推送页面代码:
- <%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>
- <%
- Stringpath=request.getContextPath();
- StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
- <html>
- <head>
- <basehref="<%=basePath%>">
- <title>MyJSP'MyJsp.jsp'startingpage</title>
- <metahttp-equiv="pragma"content="no-cache">
- <metahttp-equiv="cache-control"content="no-cache">
- <metahttp-equiv="expires"content="0">
- <metahttp-equiv="keywords"content="keyword1,keyword3">
- <metahttp-equiv="description"content="Thisismypage">
- <scripttype="text/javascript"src="<%=request.getContextPath()%>/js/jquery-1.5.1.js"></script>
- <scripttype='text/javascript'src='dwr/engine.js'></script>
- <scripttype='text/javascript'src='dwr/util.js'></script>
- <scripttype='text/javascript'src='dwr/interface/TestPush.js'></script>
- <scripttype="text/javascript">
- functiontest(){
- varmsg=document.getElementById("msgId").value;
- //msg={msgId:'1',context:$("#msgContext").val()};
- TestPush.sendMessageAuto(msg,"哈哈哈");
- }
- </script>
- </head>
- <body>
- id :<inputtype="text"name="msgId"id="msgId"/><br/>
- <inputtype="button"value="Send"onclick="test()"/>
- </body>
- </html>
第六:精确推送要实现的代码:
- publicclassTest{
- publicvoidsendMessageAuto(Stringuserid,Stringmessage){
- finalStringuserId=userid;
- finalStringautoMessage=message;
- Browser.withAllSessionsFiltered(newScriptSessionFilter(){
- publicbooleanmatch(ScriptSessionsession){
- if(session.getAttribute("userId")==null)
- returnfalse;
- else
- return(session.getAttribute("userId")).equals(userId);
- }
- },newRunnable(){
- privateScriptBufferscript=newScriptBuffer();
- publicvoidrun(){
- script.appendCall("showMessage",autoMessage);
- Collection<ScriptSession>sessions=Browser
- .getTargetSessions();
- for(ScriptSessionscriptSession:sessions){
- scriptSession.addScript(script);
- }
- }
- });
- }
- }
至此 这个例子的代码都已经贴出来了,应该是可以跑通的,有问题的话可以给我留言。当然,要自己写个登录,然后把userId放到session里面,这个比较简单,就不贴代码了,有问题可以在http://download.csdn.net/detail/luojia_wang/5275588上下载原项目。我只是简单的做了一个能实现功能的例子,还有很多地方要研究,比如跟spring整合,还可能有很多优化,等我继续学习一下再说.