用户登录后所在登录页面中设置一个隐藏的iframe标签。该子页面会每隔10s中向报告一次在线消息。代码如下:
……
<divclass="response">
<iframesrc="response.html"></iframe>
</div>
……
response.html代码实现如下:
<!DOCTYPEhtml PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<metahttp-equiv="pragma"content="no-cache"></meta>
<metahttp-equiv="Cache-Control"content="no-cache, must-revalidate"></meta>
<metahttp-equiv="expires"content="0"></meta>
<metahttp-equiv="content-type"content="text/html; charset=utf-8"></meta>
<scripttype="text/javascript"src="js/ajax.js"></script>
<scripttype="text/javascript">
window.onload = function() {
setInterval(response, 10000);
}
function response() {
var url ="response"
ajaxGet(url);
}
</script>
</head>
<body></body>
</html>
服务器端程序每接受一次请求,在未退出的情况下将该会话的生存时间延长15S。服务器端相应代码如下:
package web.execute;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import web.standard.PlainServlet;
publicclass ResponseServletextends PlainServlet {
privatestaticfinallongserialVersionUID = 6549090l;
@Override
publicvoid service(HttpServletRequest request, HttpServletResponse response)throws IOException {
super.service(request, response);
HttpSession session = request.getSession(false);
if (session ==null || session.getAttribute("userId") == null) {
return;
}
if (System.currentTimeMillis() - session.getLastAccessedTime() < 10) {
return;
}
session.setMaxInactiveInterval(15);
System.out.println("responseServlet...");
}
}