下面列出了怎么用javax.servlet.http.HttpSessionEvent的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void sessionDestroyed(HttpSessionEvent se) {
HttpSessionImpl session = (HttpSessionImpl) se.getSession();
final Session underlying;
if (System.getSecurityManager() == null) {
underlying = session.getSession();
} else {
underlying = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(session));
}
List<UndertowSession> connections = (List<UndertowSession>) underlying.getAttribute(SESSION_ATTRIBUTE);
if (connections != null) {
synchronized (underlying) {
for (UndertowSession c : connections) {
try {
c.close(new CloseReason(CloseReason.CloseCodes.VIOLATED_POLICY, ""));
} catch (IOException e) {
UndertowLogger.REQUEST_IO_LOGGER.ioException(e);
}
}
}
}
}
@Override
public void sessionCreated(HttpSessionEvent se) {
HttpSession session = se.getSession();
// 将 session 放入 map
ApplicationConstants.SESSION_MAP.put(session.getId(), session);
// 总访问人数++
ApplicationConstants.TOTAL_HISTORY_COUNT++;
// 如果当前在线人数超过历史记录,则更新最大在线人数,并记录时间
if (ApplicationConstants.SESSION_MAP.size() > ApplicationConstants.MAX_ONLINE_COUNT) {
ApplicationConstants.MAX_ONLINE_COUNT = ApplicationConstants.SESSION_MAP.size();
ApplicationConstants.MAX_ONLINE_COUNT_DATE = new Date();
}
logger.debug("创建了一个session: {}", session);
}
/** HttpSessionListener interface */
@Override
public void sessionCreated(HttpSessionEvent sessionEvent) {
if (sessionEvent == null) {
return;
}
HttpSession session = sessionEvent.getSession();
session.setMaxInactiveInterval(Configuration.getAsInt(ConfigurationKeys.INACTIVE_TIME));
//set server default locale for STURTS and JSTL. This value should be overwrite
//LocaleFilter class. But this part code can cope with login.jsp Locale.
if (session != null) {
String defaults[] = LanguageUtil.getDefaultLangCountry();
Locale preferredLocale = new Locale(defaults[0] == null ? "" : defaults[0],
defaults[1] == null ? "" : defaults[1]);
session.setAttribute(LocaleFilter.PREFERRED_LOCALE_KEY, preferredLocale);
Config.set(session, Config.FMT_LOCALE, preferredLocale);
}
}
/**
* Create the session.
*
* @param webApplication the web application.
* @param request the request.
* @return the session.
*/
@Override
public synchronized HttpSession createSession(WebApplication webApplication, HttpServletRequest request) {
String sessionId = UUID.randomUUID().toString();
DefaultHttpSession session = new DefaultHttpSession(webApplication, sessionId, true);
session.setSessionManager(this);
sessions.put(sessionId, session);
HttpServletResponse response = (HttpServletResponse) webApplication.getResponse(request);
Cookie cookie = new Cookie(name, sessionId);
if (path != null) {
cookie.setPath(path);
} else {
cookie.setPath("".equals(webApplication.getContextPath())? "/" : webApplication.getContextPath());
}
response.addCookie(cookie);
sessionListeners.stream().forEach((sessionListener) -> {
sessionListener.sessionCreated(new HttpSessionEvent(session));
});
return session;
}
/**
* Change the session id.
*
* @param request the request.
* @return the session id.
*/
@Override
public String changeSessionId(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
throw new IllegalStateException("No session active");
}
String oldSessionId = session.getId();
sessions.remove(oldSessionId);
String sessionId = UUID.randomUUID().toString();
DefaultHttpSession newSession = (DefaultHttpSession) session;
newSession.setId(sessionId);
sessions.put(sessionId, session);
idListeners.stream().forEach((idListener) -> {
idListener.sessionIdChanged(new HttpSessionEvent(session), oldSessionId);
});
return sessionId;
}
public void sessionCreated(HttpSessionEvent event) {
HttpSession session = event.getSession();
// 设置 session 的过期时间
if(session.isNew()){
String configValue = ParamConfig.getAttribute(PX.SESSION_CYCLELIFE_CONFIG);
try {
int cycleLife = Integer.parseInt(configValue);
session.setMaxInactiveInterval(cycleLife); // 以秒为单位
}
catch(Exception e) { }
}
String sessionId = session.getId();
String appCode = Context.getApplicationContext().getCurrentAppCode();
log.debug("应用【" + appCode + "】里 sessionId为:" + sessionId
+ " 的session创建完成,有效期为:" + session.getMaxInactiveInterval() + " 秒 ");
Context.sessionMap.put(sessionId, session);
}
/**
* Inform the listeners about the new session.
*
*/
public void tellNew() {
// Notify interested session event listeners
fireSessionEvent(Session.SESSION_CREATED_EVENT, null);
// Notify interested application event listeners
Context context = manager.getContext();
Object listeners[] = context.getApplicationLifecycleListeners();
if (listeners != null && listeners.length > 0) {
HttpSessionEvent event =
new HttpSessionEvent(getSession());
for (int i = 0; i < listeners.length; i++) {
if (!(listeners[i] instanceof HttpSessionListener))
continue;
HttpSessionListener listener =
(HttpSessionListener) listeners[i];
try {
context.fireContainerEvent("beforeSessionCreated",
listener);
listener.sessionCreated(event);
context.fireContainerEvent("afterSessionCreated", listener);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
try {
context.fireContainerEvent("afterSessionCreated",
listener);
} catch (Exception e) {
// Ignore
}
manager.getContext().getLogger().error
(sm.getString("standardSession.sessionEvent"), t);
}
}
}
}
/**
* Inform the listeners about the change session ID.
*
* @param newId new session ID
* @param oldId old session ID
* @param notifySessionListeners Should any associated sessionListeners be
* notified that session ID has been changed?
* @param notifyContainerListeners Should any associated ContainerListeners
* be notified that session ID has been changed?
*/
@Override
public void tellChangedSessionId(String newId, String oldId,
boolean notifySessionListeners, boolean notifyContainerListeners) {
Context context = manager.getContext();
// notify ContainerListeners
if (notifyContainerListeners) {
context.fireContainerEvent(Context.CHANGE_SESSION_ID_EVENT,
new String[] {oldId, newId});
}
// notify HttpSessionIdListener
if (notifySessionListeners) {
Object listeners[] = context.getApplicationEventListeners();
if (listeners != null && listeners.length > 0) {
HttpSessionEvent event =
new HttpSessionEvent(getSession());
for(Object listener : listeners) {
if (!(listener instanceof HttpSessionIdListener))
continue;
HttpSessionIdListener idListener =
(HttpSessionIdListener)listener;
try {
idListener.sessionIdChanged(event, oldId);
} catch (Throwable t) {
manager.getContext().getLogger().error
(sm.getString("standardSession.sessionEvent"), t);
}
}
}
}
}
public void stop() {
ClassLoader old = getTccl();
try {
setTccl(servletContext.getClassLoader());
this.started = false;
final Map<String, SessionPersistenceManager.PersistentSession> objectData = new HashMap<>();
for (String sessionId : sessionManager.getTransientSessions()) {
Session session = sessionManager.getSession(sessionId);
if (session != null) {
final HttpSessionEvent event = new HttpSessionEvent(SecurityActions.forSession(session, servletContext, false));
final Map<String, Object> sessionData = new HashMap<>();
for (String attr : session.getAttributeNames()) {
final Object attribute = session.getAttribute(attr);
sessionData.put(attr, attribute);
if (attribute instanceof HttpSessionActivationListener) {
((HttpSessionActivationListener) attribute).sessionWillPassivate(event);
}
}
objectData.put(sessionId, new PersistentSession(new Date(session.getLastAccessedTime() + (session.getMaxInactiveInterval() * 1000)), sessionData));
}
}
sessionPersistenceManager.persistSessions(deploymentName, objectData);
this.data.clear();
} finally {
setTccl(old);
}
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
final String incomingSessionId = servletContext.getSessionConfig().findSessionId(exchange);
if (incomingSessionId == null || !data.containsKey(incomingSessionId)) {
next.handleRequest(exchange);
return;
}
//we have some old data
PersistentSession result = data.remove(incomingSessionId);
if (result != null) {
long time = System.currentTimeMillis();
if (time < result.getExpiration().getTime()) {
final HttpSessionImpl session = servletContext.getSession(exchange, true);
final HttpSessionEvent event = new HttpSessionEvent(session);
for (Map.Entry<String, Object> entry : result.getSessionData().entrySet()) {
if (entry.getValue() instanceof HttpSessionActivationListener) {
((HttpSessionActivationListener) entry.getValue()).sessionDidActivate(event);
}
if(entry.getKey().startsWith(HttpSessionImpl.IO_UNDERTOW)) {
session.getSession().setAttribute(entry.getKey(), entry.getValue());
} else {
session.setAttribute(entry.getKey(), entry.getValue());
}
}
}
}
next.handleRequest(exchange);
}
public void sessionCreated(final HttpSession session) {
if(!started) {
return;
}
final HttpSessionEvent sre = new HttpSessionEvent(session);
for (int i = 0; i < httpSessionListeners.length; ++i) {
this.<HttpSessionListener>get(httpSessionListeners[i]).sessionCreated(sre);
}
}
public void sessionDestroyed(final HttpSession session) {
if(!started) {
return;
}
final HttpSessionEvent sre = new HttpSessionEvent(session);
for (int i = httpSessionListeners.length - 1; i >= 0; --i) {
ManagedListener listener = httpSessionListeners[i];
this.<HttpSessionListener>get(listener).sessionDestroyed(sre);
}
}
@Override
public void sessionCreated(HttpSessionEvent event) {
HttpSession session = event.getSession();
CsrfGuard csrfGuard = CsrfGuard.getInstance();
csrfGuard.updateToken(session);
// Check if should generate tokens for protected resources on current session
if (csrfGuard.isTokenPerPageEnabled() && csrfGuard.isTokenPerPagePrecreate()
&& !SessionUtils.tokensGenerated(session)) {
csrfGuard.generatePageTokensForSession(session);
}
}
public void stop() {
ClassLoader old = getTccl();
try {
setTccl(servletContext.getClassLoader());
this.started = false;
final Map<String, SessionPersistenceManager.PersistentSession> objectData = new HashMap<>();
for (String sessionId : sessionManager.getTransientSessions()) {
Session session = sessionManager.getSession(sessionId);
if (session != null) {
final HttpSessionEvent event = new HttpSessionEvent(SecurityActions.forSession(session, servletContext, false));
final Map<String, Object> sessionData = new HashMap<>();
for (String attr : session.getAttributeNames()) {
final Object attribute = session.getAttribute(attr);
sessionData.put(attr, attribute);
if (attribute instanceof HttpSessionActivationListener) {
((HttpSessionActivationListener) attribute).sessionWillPassivate(event);
}
}
objectData.put(sessionId, new PersistentSession(new Date(session.getLastAccessedTime() + (session.getMaxInactiveInterval() * 1000)), sessionData));
}
}
sessionPersistenceManager.persistSessions(deploymentName, objectData);
this.data.clear();
} finally {
setTccl(old);
}
}
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
HttpSession session = httpSessionEvent.getSession();
String sessionID = session.getId();
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(session.getServletContext());
// Cleanup FutureHolder
FutureHolderMap futureHolder = (FutureHolderMap) applicationContext.getBean("futureHolder");
List<String> keysToRemove = new ArrayList<>();
for (String key : futureHolder.keySet()) {
if (key.endsWith("@" + sessionID) ) {
keysToRemove.add(key);
}
}
for (String removeMe : keysToRemove) {
futureHolder.remove(removeMe);
}
// Remove all download data and associated files
DownloadService downloadService = (DownloadService) applicationContext.getBean("DownloadService");
downloadService.removeAllDownloadData(session);
// Cleanup grid recycle bin
ComAdmin admin = (ComAdmin) session.getAttribute(AgnUtils.SESSION_CONTEXT_KEYNAME_ADMIN);
if (admin != null) {
ComGridTemplateService gridTemplateService = applicationContext.getBean("GridTemplateService", ComGridTemplateService.class);
gridTemplateService.deleteRecycledChildren(admin.getCompanyID());
}
// Cleanup waiting interactive imports
ProfileImportWorker profileImportWorker = (ProfileImportWorker) session.getAttribute(ProfileImportAction.PROFILEIMPORTWORKER_SESSIONKEY);
if (profileImportWorker != null && profileImportWorker.isWaitingForInteraction()) {
profileImportWorker.cleanUp();
session.removeAttribute(ProfileImportAction.PROFILEIMPORTWORKER_SESSIONKEY);
logger.info("Canceled interactively waiting ProfileImport for session: " + sessionID + " " + (admin != null ? "admin: " + admin.getUsername() : ""));
}
}
@Override
public void sessionCreated(HttpSessionEvent ev) {
HttpSession session = ev.getSession();
String id = session.getId();
sessions.add(session);
//System.out.println("SESSION: " + id + " was created");
}
@Override
public void sessionDestroyed(HttpSessionEvent ev) {
HttpSession session = ev.getSession();
String id = session.getId();
sessions.remove(session);
//System.out.println("SESSION: " + id + " was destroyed");
}
@SuppressWarnings("unchecked")
public void sessionCreated(HttpSessionEvent se) {
HttpSession session = se.getSession();
synchronized(sessionMonitor) {
sessionMonitor.put(session.getId(), session);
System.out.println(session.getId() + " : 세션 저장");
}
}
@Override
public void sessionCreated(HttpSessionEvent event) {
synchronized (this) {
numberOfSessions++;
}
logger.info(String.format("New session is created (Id: %s). Number of sessions: %d", event.getSession().getId(), numberOfSessions));
}
@Override
public void sessionDestroyed(HttpSessionEvent event) {
synchronized (this) {
numberOfSessions--;
}
logger.info(String.format("Session destroyed (Id: %s). Number of sessions: %d", event.getSession().getId(), numberOfSessions));
}
@SuppressWarnings("unchecked")
@Override
public void sessionDestroyed(HttpSessionEvent hse)
{
webDAVLockService.setCurrentSession(hse.getSession());
webDAVLockService.sessionDestroyed();
if (logger.isDebugEnabled())
{
logger.debug("Session destroyed " + hse.getSession().getId());
}
}
@Override
public void sessionCreated(HttpSessionEvent event) {
if (LOG.isDebugEnabled()) {
LOG.info("Created session - " + event);
}
ONLINE_SESSIONS.add(event.getSession());
}
public void httpSessionIdChanged(final HttpSession session, final String oldSessionId) {
if(!started) {
return;
}
final HttpSessionEvent sre = new HttpSessionEvent(session);
for (int i = 0; i < httpSessionIdListeners.length; ++i) {
this.<HttpSessionIdListener>get(httpSessionIdListeners[i]).sessionIdChanged(sre, oldSessionId);
}
}
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
final String incomingSessionId = servletContext.getSessionConfig().findSessionId(exchange);
if (incomingSessionId == null || !data.containsKey(incomingSessionId)) {
next.handleRequest(exchange);
return;
}
//we have some old data
PersistentSession result = data.remove(incomingSessionId);
if (result != null) {
long time = System.currentTimeMillis();
if (time < result.getExpiration().getTime()) {
final HttpSessionImpl session = servletContext.getSession(exchange, true);
final HttpSessionEvent event = new HttpSessionEvent(session);
for (Map.Entry<String, Object> entry : result.getSessionData().entrySet()) {
if (entry.getValue() instanceof HttpSessionActivationListener) {
((HttpSessionActivationListener) entry.getValue()).sessionDidActivate(event);
}
if(entry.getKey().startsWith(HttpSessionImpl.IO_UNDERTOW)) {
session.getSession().setAttribute(entry.getKey(), entry.getValue());
} else {
session.setAttribute(entry.getKey(), entry.getValue());
}
}
}
}
next.handleRequest(exchange);
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
HttpSession session = se.getSession();
// 将session从map中移除
ApplicationConstants.SESSION_MAP.remove(session.getId());
logger.debug("销毁了一个session: {}", session);
}
@Override
public void sessionDestroyed(HttpSessionEvent event) {
HttpSession session = event.getSession();
Users user = (Users) session.getAttribute("user");
if (user == null) {
return;
}
ServletContext servletContext = event.getSession().getServletContext();
servletContext.removeAttribute(((Users) session.getAttribute("user")).getUname());
Integer onlineNum = (Integer) servletContext.getAttribute("onlineNum");
if (onlineNum > 0) {
servletContext.setAttribute("onlineNum", onlineNum - 1);
}
Object signinid = session.getAttribute("signinid");
if (user == null || signinid == null) {
return;
}
int uid = user.getUid();
Timestamp sdtime = Times.getSystemTime();
usersDao.updateOnline(0, uid);
signinDao.updateSignin((Integer) signinid, sdtime);
Object adid = session.getAttribute("adid");
Admins admin = (Admins) session.getAttribute("admin");
if (admin == null || adid == null) {
return;
}
int aid = admin.getAid();
adminsDao.updateOnline(0, aid);
adloginDao.updateSignin((Integer) adid, sdtime);
}
public void sessionCreated(final HttpSession session) {
if(!started) {
return;
}
final HttpSessionEvent sre = new HttpSessionEvent(session);
for (int i = 0; i < httpSessionListeners.length; ++i) {
this.<HttpSessionListener>get(httpSessionListeners[i]).sessionCreated(sre);
}
}
/**
* Destroy the session.
*
* @param session the session.
*/
@Override
public synchronized void destroySession(HttpSession session) {
sessionListeners.stream().forEach((sessionListener) -> {
sessionListener.sessionDestroyed(new HttpSessionEvent(session));
});
sessions.remove(session.getId());
}
/**
* Handle the session id changed event.
*
* @param event the event.
* @param oldSessionId the old session id.
*/
@Override
public void sessionIdChanged(HttpSessionEvent event, String oldSessionId) {
HttpSession session = event.getSession();
session.getServletContext().setAttribute("newSessionId", session.getId());
session.getServletContext().setAttribute("oldSessionId", oldSessionId);
}
@Override
public void sessionCreated(HttpSessionEvent hse)
{
if (logger.isDebugEnabled())
{
logger.debug("Session created " + hse.getSession().getId());
}
}