js监听关闭页面,关闭页面时执行操作
程序员文章站
2022-07-12 18:55:20
...
功能要求:关闭页面时,后台执行自定义操作。
具体要求:用户关闭网页时,自动在后台清除其登录信息。
长话短说,show code!
前端javascript代码,具体onbeforeunload和onunload区别不再赘述:
window.onbeforeunload = onbeforeunload_handler;
function onbeforeunload_handler() {
$.post(contentPath + "Login/CloseWindow");
}
后台相应代码:
@ResponseBody
@RequestMapping(value = "/CloseWindow", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public void closeWindow(HttpServletRequest request){
String username = SystemInfo.getCurrentUserId();
BaseUser userEntity = baseUserBLL.CheckLogin(username);
ServletContext application = request.getSession().getServletContext();
Map<String, String> loginMap = (Map<String, String>) application.getAttribute("loginMap");
loginMap.remove(userEntity.getAccount());
}