DWR (Direct Web Remoting) 允許伺服器端 Java 代碼直接呼叫瀏覽器端 JavaScript 函數。關鍵在於建立 ScriptSession 與 HTTP Session 的綁定,透過 ScriptSessionId 實現精準推送。
@Service("remoteService")
public class RemoteService {
public void registerSession() {
ScriptSession scriptSession = WebContextFactory.get().getScriptSession();
String jsessionId = scriptSession.getHttpSessionId();
String dwrSessionId = scriptSession.getId();
// 存入全域快取:jsessionId -> dwrSessionId
ConstantCacheService.putCacheConstant(PUSH_ID + jsessionId, dwrSessionId);
}
}
@Service("dwrReverseAjaxService")
public class DwrReverseAjaxService {
private static final Logger LOGGER = LoggerFactory.getLogger(DwrReverseAjaxService.class);
public void pushToClient(HttpSession session, String jsFunctionName) {
String scriptSessionId = ConstantCacheService.getCacheConstant(PUSH_ID + session.getId());
Browser.withSession(scriptSessionId, () -> {
ScriptSessions.addFunctionCall(jsFunctionName, "");
});
}
}
<script src="/dwr/engine.js>、<script src="/dwr/interface/remoteService.js>remoteService.registerSession() 建立綁定。function serverCallback() { ... }@Autowired DwrReverseAjaxService reverseAjax;
public void notifyUser(HttpSession session) {
reverseAjax.pushToClient(session, "serverCallback");
}
ScriptSession 逾時設定需與 HTTP Session 一致。