除了利用Pushlet实现信息推送外,DWR反转同样可以实现推送。
DWR的简单配置方法已经在以前的博客中写过。所以这里直接贴代码:
新建web工程,这里命名为DwrEg,包结构如下:
web.xml代码如下:
- <?xmlversion="1.0"encoding="UTF-8"?>
- <web-appversion="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">
- servletservlet-name>dwr-invoke</servlet-class>uk.ltd.getahead.dwr.DWRServletinit-paramparam-name>debugparam-value>true>activeReverseAjaxEnabled <!--
- >classes>java.lang.Object>--
- servlet-mappingurl-pattern>/dwr/*welcome-file-listwelcome-file>client.htmlweb-app>
dwr.xml代码如下:
<!DOCTYPEdwrPUBLIC"-//GetAheadLimited//DTDDirectWebRemoting2.0//EN""http://getahead.org/dwr//dwr20.dtd"dwrallowcreatejavascript="myrevsrse"creator="new"paramname="class"value="com.src.MyReverse"/>
create>
MyReverse.java代码如下:
- packagecom.src;
- importjava.util.Collection;
- importorg.directwebremoting.ScriptBuffer;
- importorg.directwebremoting.ScriptSession;
- importorg.directwebremoting.ServerContext;
- importorg.directwebremoting.ServerContextFactory;
- importorg.directwebremoting.WebContext;
- importorg.directwebremoting.WebContextFactory;
- importorg.directwebremoting.proxy.dwr.Util;
- publicclassMyReverse{
- voidsendMes(Stringmes){
- System.out.println("kaoshisibestllll...");
- send("系统消息:"+mes);
- }
- voidsend(finalStringoutput){
- org.directwebremoting.WebContextweb=WebContextFactory.get();
- Stringpage=web.getServletContext().getContextPath()+"/client.html";
- Collectionsessions=web.getScriptSessionsByPage(page);
- System.out.println("size=="+sessions.size());
- UtilutilAll=newUtil(sessions);
- utilAll.addFunctionCall("callBack",output);//callBack是client.jsp里面的javascript函数,output是传递过去的参数
- //utilAll.setValue("news_id",output,false);
- //这种方法也可以,直接将client.html里id为news_id的textarea的值设置为output的值
- voidnoticeNewOrder(intid){
- WebContextwctx=WebContextFactory.get();
- ScriptBufferscript=newScriptBuffer();
- script.appendScript("receiveMessages(")
- .appendData(id)
- .appendScript(");");
- ServerContextsctx=ServerContextFactory.get(wctx.getServletContext());
- Collection<ScriptSession>pages=sctx.getScriptSessionsByPage("/DwrEg/client.html");
- for(ScriptSessionsession:pages){
- session.addScript(script);
- }
client.HTML代码如下: