在前兩篇中咱們已經介紹了Dwr零配置文化化和前端調用後端的方法,想必你們應該已經會熟練掌握了,下來咱們主要探討一下後端怎麼反向調用前端的js方法;html
就如前兩篇說到了用Dwr註冊了兩個Service組件,一個是remote,另一個是頁面使用到的controller,這個remote是在頁面一加載進來就會被調用的,這樣就使得會話和頁面ScriptSession創建了綁定的關係,方便咱們後面使用它的scriptSessionId進行頁面定向推送;前端
下面是創建會話和頁面ScriptSession的方法(頁面剛加載進來的時候就會被調用的):java
ScriptSession scriptSession = WebContextFactory.get().getScriptSession(); String jsessionId = scriptSession.getHttpSessionId(); String dwrSessionId = scriptSession.getId(); LOGGER.info(String.format("set jsessionId = [%s],dwrsession = [%s] push enabled",jsessionId,dwrSessionId)); ConstantCacheService.putCacheConstant(Constants.PUSH_ID+jsessionId, dwrSessionId);
下面是用來反向調用前端的Service方法:
後端
@Service("dwrReverseAjaxService") public class DwrReverseAjaxService { private static final Logger LOGGER = LoggerFactory.getLogger(DwrReverseAjaxService.class); public void directWebRemotingWithSession(HttpSession session, final String functionName) { Assert.notNull(session, "[Dwr Reverse Ajax] Session can not be null!"); final String scriptSessionId = ConstantCacheService.getCacheConstantValue(Constants.PUSH_ID + session.getId()); LOGGER.info("[DWR Session ID] = " + scriptSessionId + " [Script Function Name] = " + functionName); Browser.withSession(scriptSessionId, new Runnable() { public void run() { ScriptSessions.addFunctionCall(functionName, ""); } }); } }ConstantCacheService就是這個對這個Map進行操做的靜態類,DWR反向Ajax 是利用了scriptSessionId來進行反向定位推送的,而這個scriptSessionId是利用咱們以前頁面剛加載進來就創建好保存到的一個全局的Map對裏面();
下來只要在你想要何時調用的時候使用註冊的這個Service bean就能夠了,傳進去的參數爲HttpSession和你想調用的前端Js funciton name,同時注意一下當前頁面存在這個Js function,並且通常是主頁面的Js裏面的方法才能被訪問到,不然前端會提示該方法未定義的錯誤;同時在Js function所在的頁面的*.html剛進來時就調用一下dwr.engine.setActiveReverseAjax(true);通常放在body裏面,形如session
<body onload="dwr.engine.setActiveReverseAjax(true);"></body>
這個是比較關鍵的,還有一個dwr.engine.setErrorHandler(function(){});也可加在上面那句的後面,用來處理報告異常的,這個是可選的;spa
以上就是關於Dwr的簡單應用,純屬第一次用,有什麼不對的地方,請你們指正出來,感激涕零啊!大神請飄過~~~~~;code