Skip to content

Instantly share code, notes, and snippets.

@sndyuk
Created November 18, 2015 16:46
Show Gist options
  • Save sndyuk/acdb13a9e8917e45c475 to your computer and use it in GitHub Desktop.
Save sndyuk/acdb13a9e8917e45c475 to your computer and use it in GitHub Desktop.
package jp.co.aflac.util;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Cache resources on clinet while a user session is valid.
*
* @author sndyuk
*/
public class CacheWhileOnSessionFilter implements Filter {
private static final String SESSION_EXPIRATION_TIME = "session_expiration_time";
/**
* {@inheritDoc}
*/
@Override
public void init(final FilterConfig filterConfig) throws ServletException {
}
/**
* {@inheritDoc}
*/
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
chain.doFilter(request, response);
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpRes = (HttpServletResponse) response;
HttpSession session = httpReq.getSession(false);
if (session == null) {
httpRes.setHeader("Cache-Control", "no-cache");
httpRes.setHeader("Pragma", "no-cache, no-store");
httpRes.setDateHeader("Expires", System.currentTimeMillis());
return;
}
long sessionExpirationTime;
if (session.isNew()) {
sessionExpirationTime = session.getLastAccessedTime() + (session.getMaxInactiveInterval() * 1000);
session.setAttribute(SESSION_EXPIRATION_TIME, sessionExpirationTime);
} else {
sessionExpirationTime = (long) session.getAttribute(SESSION_EXPIRATION_TIME);
}
httpRes.setHeader("Cache-Control", "max-age=" + (sessionExpirationTime - System.currentTimeMillis()));
httpRes.setDateHeader("Expires", sessionExpirationTime);
}
/**
* {@inheritDoc}
*/
@Override
public void destroy() {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment