cn.zcltd.btg.httpsession.servlet.BTGHttpServletRequest Maven / Gradle / Ivy
package cn.zcltd.btg.httpsession.servlet;
import cn.zcltd.btg.httpsession.BTGSessionContext;
import cn.zcltd.btg.httpsession.kit.SessionKit;
import cn.zcltd.btg.sutil.EmptyUtil;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;
/**
* HttpServletRequest扩展
* 将默认session实现替换为btg-httpsession实现
*/
public class BTGHttpServletRequest extends HttpServletRequestWrapper {
public BTGHttpServletRequest(HttpServletRequest request) {
super(request);
}
@Override
public HttpSession getSession() {
return getSession(true);
}
@Override
public HttpSession getSession(boolean create) {
HttpServletRequest request = (HttpServletRequest) getRequest();
BTGSessionContext sessionContext = SessionKit.getSessionContext(request.getServletContext());//不适用sessionKit是为了初始化SessionContext的ServletContext
String sessionIdKey = sessionContext.getSessionIdKey();
String sessionId = null;
Cookie[] cookies = request.getCookies();
if (EmptyUtil.isNotEmpty(cookies) && cookies.length > 0) {
for (Cookie cookie : cookies) {
String ckey = cookie.getName();
String cvalue = cookie.getValue();
if (ckey.equals(sessionIdKey) && EmptyUtil.isNotEmpty(cvalue)) {
sessionId = cvalue;
}
}
}
HttpSession session = sessionContext.getSession(sessionId);
if (create && EmptyUtil.isEmpty(session)) {
session = SessionKit.getNewSession();
}
return session;
}
}