下面列出了javax.servlet.http.HttpSessionAttributeListener#javax.servlet.http.HttpSessionListener 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Add the listener.
*
* @param <T> the type.
* @param listener the listener
*/
@Override
public <T extends EventListener> void addListener(T listener) {
if (listener instanceof ServletContextListener) {
contextListeners.add((ServletContextListener) listener);
}
if (listener instanceof ServletContextAttributeListener) {
contextAttributeListeners.add((ServletContextAttributeListener) listener);
}
if (listener instanceof ServletRequestListener) {
requestListeners.add((ServletRequestListener) listener);
}
if (listener instanceof ServletRequestAttributeListener) {
httpRequestManager.addListener((ServletRequestAttributeListener) listener);
}
if (listener instanceof HttpSessionAttributeListener) {
httpSessionManager.addListener(listener);
}
if (listener instanceof HttpSessionIdListener) {
httpSessionManager.addListener(listener);
}
if (listener instanceof HttpSessionListener) {
httpSessionManager.addListener(listener);
}
}
/**
* Create the listener.
*
* @param <T> the type.
* @param clazz the class of the listener to create.
* @return the listener.
* @throws ServletException when it fails to create the listener.
*/
@Override
public <T extends EventListener> T createListener(Class<T> clazz) throws ServletException {
T result = objectInstanceManager.createListener(clazz);
boolean ok = false;
if (result instanceof ServletContextListener || result instanceof ServletContextAttributeListener || result instanceof ServletRequestListener
|| result instanceof ServletRequestAttributeListener || result instanceof HttpSessionAttributeListener
|| result instanceof HttpSessionIdListener || result instanceof HttpSessionListener) {
ok = true;
}
if (!ok) {
LOGGER.log(WARNING, "Unable to create listener: {0}", clazz);
throw new IllegalArgumentException("Invalid type");
}
return result;
}
/**
* This method is used by injected code to register listeners for {@link ServletContext}. If object argument is a
* {@link ServletContext} and listener argument contains {@link HttpSessionListener} or
* {@link HttpSessionAttributeListener}, the method will add them to list of known listeners associated to
* {@link ServletContext}
*
* @param servletContext
* the active servlet context
* @param listener
* the listener to use
*/
public void onAddListener(ServletContext servletContext, Object listener) {
String contextPath = servletContext.getContextPath();
ServletContextDescriptor scd = getDescriptor(servletContext);
logger.debug("Registering listener {} for context {}", listener, contextPath);
// As theoretically one class can implement many listener interfaces we
// check if it implements each of supported ones
if (listener instanceof HttpSessionListener) {
scd.addHttpSessionListener((HttpSessionListener)listener);
}
if (listener instanceof HttpSessionAttributeListener) {
scd.addHttpSessionAttributeListener((HttpSessionAttributeListener)listener);
}
if (ServletLevel.isServlet31) {
// Guard the code inside block to avoid use of classes
// that are not available in versions before Servlet 3.1
if (listener instanceof HttpSessionIdListener) { // NOSONAR
scd.addHttpSessionIdListener((HttpSessionIdListener)listener);
}
}
}
@Test
public void testSessionDestroyed() {
HttpSessionBindingListener bindingListener = mock(HttpSessionBindingListener.class);
String dummy = "dummy";
when(session.getAttribute("binding")).thenReturn(bindingListener);
when(session.getAttribute("attribute")).thenReturn(dummy);
when(session.getAttributeNamesWithValues()).thenReturn(Arrays.asList("binding", "attribute"));
HttpSessionListener listener = mock(HttpSessionListener.class);
descriptor.addHttpSessionListener(listener);
notifier.sessionDestroyed(session, false);
verify(bindingListener).valueUnbound(any(HttpSessionBindingEvent.class));
verify(listener).sessionDestroyed(any(HttpSessionEvent.class));
HttpSessionListener listener2 = mock(HttpSessionListener.class);
HttpSessionBindingListener bindingListener2 = mock(HttpSessionBindingListener.class);
when(session.getAttribute("binding2")).thenReturn(bindingListener2);
when(session.getAttributeNamesWithValues()).thenReturn(Arrays.asList("binding", "attribute", "binding2"));
descriptor.addHttpSessionListener(listener2);
notifier.sessionDestroyed(session, false);
verify(listener, times(2)).sessionDestroyed(any(HttpSessionEvent.class));
verify(bindingListener, times(2)).valueUnbound(any(HttpSessionBindingEvent.class));
verify(bindingListener2).valueUnbound(any(HttpSessionBindingEvent.class));
verify(listener2).sessionDestroyed(any(HttpSessionEvent.class));
}
@Override
public final void removeSession(final AbstractSession session, boolean invalidate) {
final String clusterId = getClusterId(session);
final boolean removed = removeSession(clusterId);
if (removed) {
_sessionsStats.decrement();
_sessionTimeStats.set(Math.round((System.currentTimeMillis() - session.getCreationTime()) / 1000.0));
_sessionIdManager.removeSession(session);
if (invalidate) {
_sessionIdManager.invalidateAll(session.getClusterId());
}
if (invalidate && _sessionListeners != null) {
final HttpSessionEvent event = new HttpSessionEvent(session);
for (int i = LazyList.size(_sessionListeners); i-- > 0;) {
((HttpSessionListener) LazyList.get(_sessionListeners, i)).sessionDestroyed(event);
}
}
if (!invalidate) {
session.willPassivate();
}
}
}
@Override
public void onApplicationEvent(AbstractSessionEvent event) {
if (this.listeners.isEmpty()) {
return;
}
HttpSessionEvent httpSessionEvent = createHttpSessionEvent(event);
for (HttpSessionListener listener : this.listeners) {
if (event instanceof SessionDestroyedEvent) {
listener.sessionDestroyed(httpSessionEvent);
}
else if (event instanceof SessionCreatedEvent) {
listener.sessionCreated(httpSessionEvent);
}
}
}
/**
* Registers a listener.
*
* @param entry
* the entry
*/
public static void registerListener( HttpSessionListenerEntry entry )
{
String strListenerClass = entry.getListenerClass( );
try
{
HttpSessionListener listener = (HttpSessionListener) Class.forName( strListenerClass ).newInstance( );
LIST_LISTENERS.add( listener );
AppLogService.info( "New Listener registered : " + strListenerClass );
}
catch( InstantiationException | IllegalAccessException | ClassNotFoundException e )
{
AppLogService.error( "Error registering the listener " + strListenerClass + " : " + e.getMessage( ), e );
}
}
private void addListener(String name, String classname) {
LOG.debug("Adding listener: " + name + "=" + classname);
Object listenerObject = GlobalResourceLoader.getResourceLoader().getObject(new ObjectDefinition(classname));
if (listenerObject == null) {
LOG.error("Listener '" + name + "' class not found: " + classname);
return;
}
if (!(listenerObject instanceof HttpSessionListener)) {
LOG.error("Class '" + listenerObject.getClass() + "' does not implement servlet javax.servlet.http.HttpSessionListener");
return;
}
HttpSessionListener listener = (HttpSessionListener) listenerObject;
listeners.put(name, listener);
}
private static boolean isWeb(final Class<?> beanClass) {
if (Servlet.class.isAssignableFrom(beanClass)
|| Filter.class.isAssignableFrom(beanClass)) {
return true;
}
if (EventListener.class.isAssignableFrom(beanClass)) {
return HttpSessionAttributeListener.class.isAssignableFrom(beanClass)
|| ServletContextListener.class.isAssignableFrom(beanClass)
|| ServletRequestListener.class.isAssignableFrom(beanClass)
|| ServletContextAttributeListener.class.isAssignableFrom(beanClass)
|| HttpSessionListener.class.isAssignableFrom(beanClass)
|| HttpSessionBindingListener.class.isAssignableFrom(beanClass)
|| HttpSessionActivationListener.class.isAssignableFrom(beanClass)
|| HttpSessionIdListener.class.isAssignableFrom(beanClass)
|| ServletRequestAttributeListener.class.isAssignableFrom(beanClass);
}
return false;
}
/**
* 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);
}
}
}
}
@Override
public <T extends EventListener> void addListener(T t) {
if (!context.getState().equals(LifecycleState.STARTING_PREP)) {
throw new IllegalStateException(
sm.getString("applicationContext.addListener.ise",
getContextPath()));
}
boolean match = false;
if (t instanceof ServletContextAttributeListener ||
t instanceof ServletRequestListener ||
t instanceof ServletRequestAttributeListener ||
t instanceof HttpSessionIdListener ||
t instanceof HttpSessionAttributeListener) {
context.addApplicationEventListener(t);
match = true;
}
if (t instanceof HttpSessionListener ||
(t instanceof ServletContextListener && newServletContextListenerAllowed)) {
// Add listener directly to the list of instances rather than to
// the list of class names.
context.addApplicationLifecycleListener(t);
match = true;
}
if (match) return;
if (t instanceof ServletContextListener) {
throw new IllegalArgumentException(sm.getString(
"applicationContext.addListener.iae.sclNotAllowed",
t.getClass().getName()));
} else {
throw new IllegalArgumentException(sm.getString(
"applicationContext.addListener.iae.wrongType",
t.getClass().getName()));
}
}
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);
}
}
public JettyFactory(boolean httpOnly, int maxHttpPostSize, int maxFormKeys,
HttpSessionListener httpSessionEventListener) {
this.httpOnly = httpOnly;
this.maxHttpPostSize = maxHttpPostSize;
this.maxFormKeys = maxFormKeys;
this.httpSessionEventListener = httpSessionEventListener;
}
@Override
public <T extends EventListener> void addListener(T listener) {
Objects.requireNonNull(listener);
boolean addFlag = false;
ServletEventListenerManager listenerManager = getServletEventListenerManager();
if(listener instanceof ServletContextAttributeListener){
listenerManager.addServletContextAttributeListener((ServletContextAttributeListener) listener);
addFlag = true;
}
if(listener instanceof ServletRequestListener){
listenerManager.addServletRequestListener((ServletRequestListener) listener);
addFlag = true;
}
if(listener instanceof ServletRequestAttributeListener){
listenerManager.addServletRequestAttributeListener((ServletRequestAttributeListener) listener);
addFlag = true;
}
if(listener instanceof HttpSessionIdListener){
listenerManager.addHttpSessionIdListenerListener((HttpSessionIdListener) listener);
addFlag = true;
}
if(listener instanceof HttpSessionAttributeListener){
listenerManager.addHttpSessionAttributeListener((HttpSessionAttributeListener) listener);
addFlag = true;
}
if(listener instanceof HttpSessionListener){
listenerManager.addHttpSessionListener((HttpSessionListener) listener);
addFlag = true;
}
if(listener instanceof ServletContextListener){
listenerManager.addServletContextListener((ServletContextListener) listener);
addFlag = true;
}
if(!addFlag){
throw new IllegalArgumentException("applicationContext.addListener.iae.wrongType"+
listener.getClass().getName());
}
}
/**
* Add a listener.
*
* @param <T> the type.
* @param listener the listener.
*/
@Override
public <T extends EventListener> void addListener(T listener) {
if (listener instanceof HttpSessionAttributeListener) {
attributeListeners.add((HttpSessionAttributeListener) listener);
}
if (listener instanceof HttpSessionIdListener) {
idListeners.add((HttpSessionIdListener) listener);
}
if (listener instanceof HttpSessionListener) {
sessionListeners.add((HttpSessionListener) listener);
}
}
/**
* 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 = (Context) manager.getContainer();
Object listeners[] = context.getApplicationLifecycleListeners();
if (listeners != null) {
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.getContainer().getLogger().error
(sm.getString("standardSession.sessionEvent"), t);
}
}
}
}
@Override
public <T extends EventListener> void addListener(T t) {
if (!context.getState().equals(LifecycleState.STARTING_PREP)) {
throw new IllegalStateException(
sm.getString("applicationContext.addListener.ise",
getContextPath()));
}
boolean match = false;
if (t instanceof ServletContextAttributeListener ||
t instanceof ServletRequestListener ||
t instanceof ServletRequestAttributeListener ||
t instanceof HttpSessionAttributeListener) {
context.addApplicationEventListener(t);
match = true;
}
if (t instanceof HttpSessionListener
|| (t instanceof ServletContextListener &&
newServletContextListenerAllowed)) {
// Add listener directly to the list of instances rather than to
// the list of class names.
context.addApplicationLifecycleListener(t);
match = true;
}
if (match) return;
if (t instanceof ServletContextListener) {
throw new IllegalArgumentException(sm.getString(
"applicationContext.addListener.iae.sclNotAllowed",
t.getClass().getName()));
} else {
throw new IllegalArgumentException(sm.getString(
"applicationContext.addListener.iae.wrongType",
t.getClass().getName()));
}
}
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(RepositoryBackedSession session) {
if (session instanceof HttpSession) {
HttpSessionEvent event = new HttpSessionEvent((HttpSession)session);
for (HttpSessionListener listener : descriptor.getHttpSessionListeners()) {
listener.sessionCreated(event);
}
}
}
@Test
public void testOnAddListener() {
ServletContextDescriptor scd = new ServletContextDescriptor(servletContext);
when(servletContext.getAttribute(Attributes.SERVLET_CONTEXT_DESCRIPTOR)).thenReturn(scd);
sessionHelpers.onAddListener(servletContext, "Dummy");
assertTrue(scd.getHttpSessionListeners().isEmpty());
assertTrue(scd.getHttpSessionIdListeners().isEmpty());
assertTrue(scd.getHttpSessionAttributeListeners().isEmpty());
HttpSessionListener listener = mock(HttpSessionListener.class);
HttpSessionIdListener idListener = mock(HttpSessionIdListener.class);
HttpSessionAttributeListener attributeListener = mock(HttpSessionAttributeListener.class);
HttpSessionListener multiListener = mock(HttpSessionListener.class,
withSettings().extraInterfaces(HttpSessionAttributeListener.class));
HttpSessionAttributeListener attributeMultiListener = (HttpSessionAttributeListener)multiListener;
sessionHelpers.onAddListener(servletContext, listener);
assertThat(scd.getHttpSessionListeners(), hasItem(listener));
assertTrue(scd.getHttpSessionIdListeners().isEmpty());
assertTrue(scd.getHttpSessionAttributeListeners().isEmpty());
sessionHelpers.onAddListener(servletContext, idListener);
assertThat(scd.getHttpSessionListeners(), hasItem(listener));
assertThat(scd.getHttpSessionIdListeners(), hasItem(idListener));
assertTrue(scd.getHttpSessionAttributeListeners().isEmpty());
sessionHelpers.onAddListener(servletContext, attributeListener);
assertThat(scd.getHttpSessionListeners(), hasItem(listener));
assertThat(scd.getHttpSessionIdListeners(), hasItem(idListener));
assertThat(scd.getHttpSessionAttributeListeners(), hasItem(attributeListener));
sessionHelpers.onAddListener(servletContext, multiListener);
assertThat(scd.getHttpSessionListeners(), hasItem(listener));
assertThat(scd.getHttpSessionListeners(), hasItem(multiListener));
assertThat(scd.getHttpSessionIdListeners(), hasItem(idListener));
assertThat(scd.getHttpSessionAttributeListeners(), hasItem(attributeListener));
assertThat(scd.getHttpSessionAttributeListeners(), hasItem(attributeMultiListener));
}
@Test
public void testSessionCreated() {
HttpSessionListener listener = mock(HttpSessionListener.class);
descriptor.addHttpSessionListener(listener);
notifier.sessionCreated(session);
verify(listener).sessionCreated(any(HttpSessionEvent.class));
HttpSessionListener listener2 = mock(HttpSessionListener.class);
descriptor.addHttpSessionListener(listener2);
notifier.sessionCreated(session);
verify(listener, times(2)).sessionCreated(any(HttpSessionEvent.class));
verify(listener2).sessionCreated(any(HttpSessionEvent.class));
}
@Test
public void testShutdown() {
HttpSessionListener listener = mock(HttpSessionListener.class);
descriptor.addHttpSessionListener(listener);
notifier.sessionDestroyed(session, true);
verify(listener).sessionDestroyed(any(HttpSessionEvent.class));
HttpSessionListener listener2 = mock(HttpSessionListener.class);
descriptor.addHttpSessionListener(listener2);
notifier.sessionDestroyed(session, true);
verify(listener, times(2)).sessionDestroyed(any(HttpSessionEvent.class));
verify(listener2).sessionDestroyed(any(HttpSessionEvent.class));
}
/**
* 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 = (Context) manager.getContainer();
Object listeners[] = context.getApplicationLifecycleListeners();
if (listeners != null) {
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.getContainer().getLogger().error
(sm.getString("standardSession.sessionEvent"), t);
}
}
}
}
@Override
public <T extends EventListener> void addListener(T t) {
if (!context.getState().equals(LifecycleState.STARTING_PREP)) {
throw new IllegalStateException(
sm.getString("applicationContext.addListener.ise",
getContextPath()));
}
boolean match = false;
if (t instanceof ServletContextAttributeListener ||
t instanceof ServletRequestListener ||
t instanceof ServletRequestAttributeListener ||
t instanceof HttpSessionAttributeListener) {
context.addApplicationEventListener(t);
match = true;
}
if (t instanceof HttpSessionListener
|| (t instanceof ServletContextListener &&
newServletContextListenerAllowed)) {
// Add listener directly to the list of instances rather than to
// the list of class names.
context.addApplicationLifecycleListener(t);
match = true;
}
if (match) return;
if (t instanceof ServletContextListener) {
throw new IllegalArgumentException(sm.getString(
"applicationContext.addListener.iae.sclNotAllowed",
t.getClass().getName()));
} else {
throw new IllegalArgumentException(sm.getString(
"applicationContext.addListener.iae.wrongType",
t.getClass().getName()));
}
}
/**
* {@inheritDoc}
*/
public void sessionCreated( HttpSessionEvent se )
{
for ( HttpSessionListener listener : HttpSessionListenerService.getListeners( ) )
{
listener.sessionCreated( se );
}
}
/**
* {@inheritDoc}
*/
public void sessionDestroyed( HttpSessionEvent se )
{
for ( HttpSessionListener listener : HttpSessionListenerService.getListeners( ) )
{
listener.sessionDestroyed( se );
}
}
/**
* {@inheritDoc}
* @see javax.servlet.http.HttpSessionListener#sessionCreated(javax.servlet.http.HttpSessionEvent)
*/
public void sessionCreated(final HttpSessionEvent event) {
LOG.debug("Begin BootstrapListener session created...");
init();
for (HttpSessionListener listener : listeners.values()) {
listener.sessionCreated(event);
}
LOG.debug("...end BootstrapListener session created.");
}
/**
* {@inheritDoc}
* @see javax.servlet.http.HttpSessionListener#sessionDestroyed(javax.servlet.http.HttpSessionEvent)
*/
public void sessionDestroyed(final HttpSessionEvent event) {
LOG.debug("Begin BootstrapListener session destroyed...");
init();
for (HttpSessionListener listener : listeners.values()) {
listener.sessionDestroyed(event);
}
LOG.debug("...end BootstrapListener session destroyed.");
}