我需要在后台使用JavaScript定期创建HTTP服务。
每次通话都不得影响会话超时(会话时钟功能)。
有可能吗?应该如何以可靠的方式完成?
答案 0 :(得分:0)
好的,我是在Filter的帮助下完成的。 会话到期截止日期存储在会话中并由http请求更新。具有无状态参数的用户不会更新到期超时。 这是我的代码:
public class SessionTimeoutFilter implements Filter {
private static final Logger log = LoggerFactory.getLogger(SessionTimeoutFilter.class);
/** The http stateless request parameter name. */
private final static String PAR_HTTP_STATELESS_REQUEST = "stateless";
/** The session expiry time argument name. */
private final static String ARG_SESSION_EXPIRY_TIME = "sessionExpiryTime";
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
try {
HttpServletRequest httpReq = (HttpServletRequest) request;
if (httpReq.getParameterMap().containsKey(PAR_HTTP_STATELESS_REQUEST)) {
// do nothing
} else {
HttpSession session = httpReq.getSession(false);
if (session != null) {
Object expirationTime = session.getAttribute(ARG_SESSION_EXPIRY_TIME);
if (expirationTime != null && expirationTime instanceof Long) {
Long expirationDate = (Long) expirationTime;
if (expirationDate < System.currentTimeMillis()) {
// manual expiration
session.invalidate();
session = null;
}
}
// session still active
if (session != null) {
long currTime = System.currentTimeMillis();
long expiryTime = currTime + session.getMaxInactiveInterval() * 1000;
// new expiration deadline
session.setAttribute(ARG_SESSION_EXPIRY_TIME, new Long(expiryTime));
}
}
}
} catch (Exception e) {
log.error("Unable set session timeout cookies due to: " + e, e);
}
filterChain.doFilter(request, response);
}
@Override
public void destroy() {}
}