Reverse Ajax with Spring and DWR

Ajax is used heavily for web 2.0 applications to provide enhance user experience, which allows a web page to be updated without the need of full refresh. Normally this updated information is pulled from client side.
Javascript call is used to make an Ajax call to the server and received information is updated.
But there are scenarios when server decides to update information on client side e.g. Chat applications, server side processing status, user presence etc.

In these situations server side "PUSH" is required instead of Client side "PULL". There are three techniques used for this purpose:
  • Polling (the browser sends requests at regular interval)
  • Comet (long lived HTTP connection connection is kept open and server keeps replying)
  • Piggyback (server waits for client to make request and sends update with that request data)
1. Enable Reverse Ajax in DWR configuration
There are two ways of going this:

You can enable in DWR.xml

or if you are using DWR name spaces then you can provide entry in [Servlet Name]-servelt.xml
<dwr:controller id="dwrController" debug="true">
<dwr:config-param name="activeReverseAjaxEnabled" value="true" />

2. Enable Reverse Ajax in JSP

3. Now we need to get Browser sessions from server side and push content there:

WebContext wctx = WebContextFactory.get();
String currentPage = wctx.getCurrentPage();

Get current page from webContext

Collection sessions = wctx.getScriptSessionsByPage(currentPage);
Get all other clients session

After getting these sessions you can push data from here using proxy interface
Util utilAll = new Util(sessions);
utilAll.addOptions("chatlog", messages, "text");

Above lines will add messages collection to all the browsers under "chatlog" element

Similarly you can execute scripts on browsers from server side.

ScriptBuffer script = new ScriptBuffer();

Above snippet will execute receiveMessages() javascript function on client side.

This way you can have full control on client side from server side. Chat application, Stock Ticker control applications, mail client can use this feature effectively.