一般情况:
public void addMessage(String text)
{
// Make sure we have a list of the list 10 messages
if (text != null && text.trim().length() > 0)
{
messages.addFirst(new Message(text));
while (messages.size() > 10)
{
messages.removeLast();
}
}
WebContext wctx = WebContextFactory.get();
String currentPage = wctx.getCurrentPage();
// Clear the input box in the browser that kicked off this page only
Util utilThis = new Util(wctx.getScriptSession());
utilThis.setValue("text", "");
// For all the browsers on the current page:
Collection sessions = wctx.getScriptSessionsByPage(currentPage);
Util utilAll = new Util(sessions);
// Clear the list and add in the new set of messages
utilAll.removeAllOptions("chatlog");
utilAll.addOptions("chatlog", messages, "text");
}
servlet:
public class TestServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Service service = new Service();
ServerContext wctx = ServerContextFactory.get(this.getServletContext());
for (int i = 0; i < 10; i++) {
service.update(wctx);
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
PrintWriter writer = response.getWriter();
writer.println("Done");
writer.close();
}}
public class Service {
private int count = 0;
public void update(ServerContext wctx) {
List<Data> messages = new ArrayList<Data>();
messages.add(new Data("testing" + count++));
// Collection sessions = wctx.getAllScriptSessions();
Collection sessions = wctx.getScriptSessionsByPage("/ReverseAjax/index.html");
Util utilAll = new Util(sessions);
utilAll.addOptions("updates", messages, "value");
}
}
其他情况要利用DWR通知客户端,利用Spring ServletContextAware
public class NotifyClient implements ServletContextAware {
static Logger logger = Logger.getLogger (NotifyClient.class.getName());
private ServletContext servletContext = null;
public void setServletContext( ServletContext servletContext )
{
this.servletContext = servletContext;
}
public int serviceUpdate (String str1, String str2) {
logger.info ("entered");
logger.info ("WebContext1"+servletContext);
ServerContext ctx = ServerContextFactory.get(servletContext );
// Generate JavaScript code to call client-side
// WebContext ctx = WebContextFactory.get();
logger.info ("WebContext"+ctx);
if (ctx != null) {
//String currentPage = ctx.getCurrentPage();
//logger.info ("current page:" + currentPage);
ScriptBuffer script = new ScriptBuffer();
script.appendScript("updatePoint(")
.appendData(str1)
.appendScript(",")
.appendData (str2)
.appendScript(");");
// Push script out to clients viewing the page
Collection<ScriptSession> sessions =
ctx.getScriptSessionsByPage("/ebnms/index.eb?do=dwrtest");