public class SessionWraper extends HttpServletRequestWrapper {
private static final Log log = LogFactory.getLog(SessionWraper.class);
private HttpServletResponse response = null;
public SessionWraper(HttpServletRequest request) {
super(request);
}
public void setResponse(HttpServletResponse response) {
this.response = response;
}
public HttpSession getSession() {
HttpSession session = super.getSession();
processSessionCookie(session);
return session;
}
public HttpSession getSession(boolean create) {
HttpSession session = super.getSession(create);
processSessionCookie(session);
return session;
}
private void processSessionCookie(HttpSession session) {
log.fatal("processSessionCookie>>"+session.getId());
if (null == response || null == session) {
return;
}
// cookieOverWritten - Flag to filter multiple "Set-Cookie" headers
Object cookieOverWritten = getAttribute("COOKIE_OVERWRITTEN_FLAG");
log.fatal((null == cookieOverWritten) +"||"+ isSecure()
+"||"+ isRequestedSessionIdFromCookie() +"||"+ session.isNew());
if (null == cookieOverWritten && isSecure()
&& isRequestedSessionIdFromCookie() && session.isNew()) {
Cookie cookie = createCookie(session);
// Adding an "Set-Cookie" header to the response
response.addCookie(cookie);
// To avoid multiple "Set-Cookie" header
setAttribute("COOKIE_OVERWRITTEN_FLAG", "true");
}
}
/**
* Might have created the cookie in SSL protocol and tomcat will loose the
* session if there is change in protocol from HTTPS to HTTP. To avoid this,
* trick the browser using the HTTP and HTTPS session cookie.
*
* @param session
*
* @return the cookie
*/
private Cookie createCookie(HttpSession session) {
log.fatal("createCookie>>"+session.getId());
Cookie cookie = new Cookie("JSESSIONID", session.getId());
cookie.setMaxAge(-1); // Life of the browser or timeout
cookie.setSecure(false);
String contextPath = getContextPath();
if ((contextPath != null) && (contextPath.length() > 0)) {
cookie.setPath(contextPath);
} else {
cookie.setPath("/");
}
return cookie;
}
}