如何在action中直接调用dwr的反向ajax类

我现在要用dwr来做反向ajax,有一个功能需要在action中直接调用dwr的反向ajax类,现在我直接调用的话,系统会报空指针异常
我看了一下应该是Collection sessions=context.getScriptSessionsByPage(currentPage);这句话报的。
我觉得应该是WebContext context=WebContextFactory.get();时,因为没有从jsp页面发出请求,所以context得到了一个null。
请问老师,如果我要想直接在action类中通过new的方法直接调用dwr的反向ajax类,应该如何做呢?

dwr类代码如下:

[code="java"]

public class SendMessage {
@SuppressWarnings("unchecked")
public void addMessage(String message)
{

    messages.add(message);
     ScriptBuffer script = new ScriptBuffer();
        script.appendScript("receiveMessages(")
              .appendData(messages)
              .appendScript(");");
              //应该是此处的WebContextFactory.get(),如果我不从jsp页面执行改类,得到一个null
    WebContext context=WebContextFactory.get();
    String currentPage="/index.jsp";
    Collection<ScriptSession> sessions=context.getScriptSessionsByPage(currentPage);
    for(ScriptSession session:sessions)
    {
        session.addScript(script);
    }               
}
private List<String> messages=new LinkedList<String>();

}[/code]

DWR 2.0存在这个问题,我也遇到过,在JavaEye找到了解决方案,不过并不满意。该方案的大致思路是改写一个DWR类,强制get返回非空的WebContext,但又带来新问题。

最佳方案:使用DWR 3.0。

这个问题已经被新的API修正了,同时还增加Browser类,便于处理客户端页面。

String page = ServerContextFactory.get().getContextPath() + "xxx.jsp";
Browser.withPage(page,new Runnable() {
public void run() {
ScriptSessions.addScript("alert(1)");
}
});

请参考我的博客 [url]http://yourgame.iteye.com/blog/199079[/url]