在前兩篇中我們已經介紹了Dwr零配置文化化和前端調用后端的方法,想必大家應該已經會熟練掌握了,下來我們主要探討一下后端怎么反向調用前端的js方法;
就如前兩篇說到了用Dwr注冊了兩個Service組件,一個是remote,另外一個是頁面使用到的controller,這個remote是在頁面一加載進來就會被調用的,這樣就使得會話和頁面ScriptSession建立了綁定的關系,方便我們后面使用它的scriptSessionId進行頁面定向推送;
下面是建立會話和頁面ScriptSession的方法(頁面剛加載進來的時候就會被調用的):
1
2
3
4
5
|
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); |
1
|
下面是用來反向調用前端的Service方法:<br> |
1
2
3
4
5
6
7
8
9
|
@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, "" ); }});}} |
這個Service是利用了scriptSessionId來進行反向定位推送的,而這個scriptSessionId是利用我們之前頁面剛加載進來就建立好保存到的一個全局的Map對里面;
下來只要在你想要什么時候調用的時候使用注冊的這個Service bean就可以了,傳進去的參數為HttpSession和你想調用的前端Js funciton name,同時注意一下當前頁面存在這個Js function,而且一般是主頁面的Js里面的方法才能被訪問到,否則前端會提示該方法未定義的錯誤;
以上就是關于Dwr的簡單應用,純屬第一次用,有什么不對的地方,請大家指正出來,感激不盡啊!大神請飄過~~~~~;