javax.servlet.http.HttpSessionEvent Java Examples

The following examples show how to use javax.servlet.http.HttpSessionEvent. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MyHttpSessionListener.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 7 votes vote down vote up
@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);
}
 
Example #2
Source File: SessionDestroyedListener.java    From boubei-tss with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #3
Source File: DefaultHttpSessionManager.java    From piranha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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;
}
 
Example #4
Source File: DefaultHttpSessionManager.java    From piranha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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;
}
 
Example #5
Source File: SessionListener.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** 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);
}
   }
 
Example #6
Source File: JsrWebSocketFilter.java    From quarkus-http with Apache License 2.0 6 votes vote down vote up
@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);
                }
            }
        }
    }
}
 
Example #7
Source File: StandardSession.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * 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);
            }
        }
    }

}
 
Example #8
Source File: CustomListener.java    From bidder with Apache License 2.0 5 votes vote down vote up
@Override
public void sessionDestroyed(HttpSessionEvent ev) {
	HttpSession session = ev.getSession();
	String id = session.getId();

	sessions.remove(session);
	//System.out.println("SESSION: " + id + " was destroyed");
	
}
 
Example #9
Source File: CustomListener.java    From bidder with Apache License 2.0 5 votes vote down vote up
@Override
public void sessionCreated(HttpSessionEvent ev) {
	HttpSession session = ev.getSession();
	String id = session.getId();

	sessions.add(session);
	//System.out.println("SESSION: " + id + " was created");
	
}
 
Example #10
Source File: HttpSessionCleanUpListener.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@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() : ""));
	}
}
 
Example #11
Source File: SessionRestoringHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example #12
Source File: SessionRestoringHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #13
Source File: WebDAVSessionListener.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void sessionDestroyed(HttpSessionEvent hse)
{
    webDAVLockService.setCurrentSession(hse.getSession());
    webDAVLockService.sessionDestroyed();

    if (logger.isDebugEnabled())
    {
        logger.debug("Session destroyed " + hse.getSession().getId());
    }
}
 
Example #14
Source File: ApplicationListeners.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #15
Source File: StandardSession.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * 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);
                }
            }
        }
    }
}
 
Example #16
Source File: SessionRestoringHandler.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #17
Source File: ApplicationListeners.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example #18
Source File: CsrfGuardHttpSessionListener.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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);
    }

}
 
Example #19
Source File: LogSearchSessionListener.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #20
Source File: LogSearchSessionListener.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #21
Source File: SesssionEventListener.java    From oslits with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void sessionCreated(HttpSessionEvent se) {
	HttpSession session = se.getSession();
	synchronized(sessionMonitor) {
		sessionMonitor.put(session.getId(), session);
		System.out.println(session.getId() + " : 세션 저장");
	}
}
 
Example #22
Source File: OnlineSessionStore.java    From rebuild with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void sessionCreated(HttpSessionEvent event) {
	if (LOG.isDebugEnabled()) {
		LOG.info("Created session - " + event);
	}
	ONLINE_SESSIONS.add(event.getSession());
}
 
Example #23
Source File: ApplicationListeners.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example #24
Source File: SessionRestoringHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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);
}
 
Example #25
Source File: MyHttpSessionListener.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@Override
public void sessionDestroyed(HttpSessionEvent se) {
	HttpSession session = se.getSession();
	// 将session从map中移除
	ApplicationConstants.SESSION_MAP.remove(session.getId());

	logger.debug("销毁了一个session: {}", session);
}
 
Example #26
Source File: MySessionListener.java    From mytwitter with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #27
Source File: ApplicationListeners.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example #28
Source File: DefaultHttpSessionManager.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 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());
}
 
Example #29
Source File: HttpSessionIdListenerTest.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 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);
}
 
Example #30
Source File: WebDAVSessionListener.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void sessionCreated(HttpSessionEvent hse)
{
    if (logger.isDebugEnabled())
    {
        logger.debug("Session created " + hse.getSession().getId());
    }
}