下面列出了javax.servlet.http.HttpSessionAttributeListener#javax.servlet.ServletContextListener 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testContextLoaderListenerWithDefaultContext() {
MockServletContext sc = new MockServletContext("");
sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
"/org/springframework/web/context/WEB-INF/applicationContext.xml " +
"/org/springframework/web/context/WEB-INF/context-addition.xml");
ServletContextListener listener = new ContextLoaderListener();
ServletContextEvent event = new ServletContextEvent(sc);
listener.contextInitialized(event);
String contextAttr = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
WebApplicationContext context = (WebApplicationContext) sc.getAttribute(contextAttr);
assertTrue("Correct WebApplicationContext exposed in ServletContext", context instanceof XmlWebApplicationContext);
assertTrue(WebApplicationContextUtils.getRequiredWebApplicationContext(sc) instanceof XmlWebApplicationContext);
LifecycleBean lb = (LifecycleBean) context.getBean("lifecycle");
assertTrue("Has father", context.containsBean("father"));
assertTrue("Has rod", context.containsBean("rod"));
assertTrue("Has kerry", context.containsBean("kerry"));
assertTrue("Not destroyed", !lb.isDestroyed());
assertFalse(context.containsBean("beans1.bean1"));
assertFalse(context.containsBean("beans1.bean2"));
listener.contextDestroyed(event);
assertTrue("Destroyed", lb.isDestroyed());
assertNull(sc.getAttribute(contextAttr));
assertNull(WebApplicationContextUtils.getWebApplicationContext(sc));
}
@Test
public void testContextLoaderWithInvalidContext() throws Exception {
MockServletContext sc = new MockServletContext("");
sc.addInitParameter(ContextLoader.CONTEXT_CLASS_PARAM,
"org.springframework.web.context.support.InvalidWebApplicationContext");
ServletContextListener listener = new ContextLoaderListener();
ServletContextEvent event = new ServletContextEvent(sc);
try {
listener.contextInitialized(event);
fail("Should have thrown ApplicationContextException");
}
catch (ApplicationContextException ex) {
// expected
assertTrue(ex.getCause() instanceof ClassNotFoundException);
}
}
public void contextInitialized() {
if(!started) {
return;
}
//new listeners can be added here, so we don't use an iterator
final ServletContextEvent event = new ServletContextEvent(servletContext);
for (int i = 0; i < servletContextListeners.length; ++i) {
ManagedListener listener = servletContextListeners[i];
IN_PROGRAMATIC_SC_LISTENER_INVOCATION.set(listener.isProgramatic() ? PROGRAMATIC_LISTENER : DECLARED_LISTENER);
try {
this.<ServletContextListener>get(listener).contextInitialized(event);
} finally {
IN_PROGRAMATIC_SC_LISTENER_INVOCATION.remove();
}
}
}
@Override
public void undeploy() {
try {
deployment.createThreadSetupAction(new ThreadSetupHandler.Action<Void, Object>() {
@Override
public Void call(HttpServerExchange exchange, Object ignore) throws ServletException {
for(ServletContextListener listener : deployment.getDeploymentInfo().getDeploymentCompleteListeners()) {
try {
listener.contextDestroyed(new ServletContextEvent(deployment.getServletContext()));
} catch (Throwable t) {
UndertowServletLogger.REQUEST_LOGGER.failedToDestroy(listener, t);
}
}
deployment.destroy();
deployment = null;
state = State.UNDEPLOYED;
return null;
}
}).call(null, null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void testContextLoaderListenerWithDefaultContext() {
MockServletContext sc = new MockServletContext("");
sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
"/org/springframework/web/context/WEB-INF/applicationContext.xml " +
"/org/springframework/web/context/WEB-INF/context-addition.xml");
ServletContextListener listener = new ContextLoaderListener();
ServletContextEvent event = new ServletContextEvent(sc);
listener.contextInitialized(event);
String contextAttr = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
WebApplicationContext context = (WebApplicationContext) sc.getAttribute(contextAttr);
assertTrue("Correct WebApplicationContext exposed in ServletContext", context instanceof XmlWebApplicationContext);
assertTrue(WebApplicationContextUtils.getRequiredWebApplicationContext(sc) instanceof XmlWebApplicationContext);
LifecycleBean lb = (LifecycleBean) context.getBean("lifecycle");
assertTrue("Has father", context.containsBean("father"));
assertTrue("Has rod", context.containsBean("rod"));
assertTrue("Has kerry", context.containsBean("kerry"));
assertTrue("Not destroyed", !lb.isDestroyed());
assertFalse(context.containsBean("beans1.bean1"));
assertFalse(context.containsBean("beans1.bean2"));
listener.contextDestroyed(event);
assertTrue("Destroyed", lb.isDestroyed());
assertNull(sc.getAttribute(contextAttr));
assertNull(WebApplicationContextUtils.getWebApplicationContext(sc));
}
@Test
public void testContextLoaderWithInvalidContext() throws Exception {
MockServletContext sc = new MockServletContext("");
sc.addInitParameter(ContextLoader.CONTEXT_CLASS_PARAM,
"org.springframework.web.context.support.InvalidWebApplicationContext");
ServletContextListener listener = new ContextLoaderListener();
ServletContextEvent event = new ServletContextEvent(sc);
try {
listener.contextInitialized(event);
fail("Should have thrown ApplicationContextException");
}
catch (ApplicationContextException ex) {
// expected
assertTrue(ex.getCause() instanceof ClassNotFoundException);
}
}
public void contextInitialized(ServletContextEvent sce) {
ctx = WebApplicationContextUtils.getWebApplicationContext(sce
.getServletContext());
if (ctx == null) {
logger.warn("cannot find applicationContext");
return;
}
Collection<ServletContextListener> servletContextListeners = ctx
.getBeansOfType(ServletContextListener.class).values();
for (ServletContextListener servletContextListener : servletContextListeners) {
servletContextListener.contextInitialized(sce);
}
}
/**
* 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;
}
/**
* Initialize the servlet container initializers.
*/
@Override
public void initializeInitializers() {
boolean error = false;
for (ServletContainerInitializer initializer : initializers) {
try {
initializer.onStartup(annotationManager.getAnnotatedClasses(), this);
} catch (Throwable t) {
LOGGER.log(WARNING, t, () -> "Initializer " + initializer.getClass().getName() + " failing onStartup");
error = true;
}
}
if (!error) {
@SuppressWarnings("unchecked")
List<ServletContextListener> listeners = (List<ServletContextListener>) contextListeners.clone();
listeners.stream().forEach((listener) -> {
listener.contextInitialized(new ServletContextEvent(this));
});
} else {
status = ERROR;
}
}
@Override
public void addListener(final Class<? extends EventListener> listenerClass) {
ensureNotInitialized();
ensureNotProgramaticListener();
if (ApplicationListeners.listenerState() != NO_LISTENER
&& ServletContextListener.class.isAssignableFrom(listenerClass)) {
throw UndertowServletMessages.MESSAGES.cannotAddServletContextListener();
}
InstanceFactory<? extends EventListener> factory = null;
try {
factory = deploymentInfo.getClassIntrospecter().createInstanceFactory(listenerClass);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
final ListenerInfo listener = new ListenerInfo(listenerClass, factory);
deploymentInfo.addListener(listener);
deployment.getApplicationListeners().addListener(new ManagedListener(listener, true));
}
public void contextInitialized() {
if(!started) {
return;
}
//new listeners can be added here, so we don't use an iterator
final ServletContextEvent event = new ServletContextEvent(servletContext);
for (int i = 0; i < servletContextListeners.length; ++i) {
ManagedListener listener = servletContextListeners[i];
IN_PROGRAMATIC_SC_LISTENER_INVOCATION.set(listener.isProgramatic() ? PROGRAMATIC_LISTENER : DECLARED_LISTENER);
try {
this.<ServletContextListener>get(listener).contextInitialized(event);
} finally {
IN_PROGRAMATIC_SC_LISTENER_INVOCATION.remove();
}
}
}
@Override
public void undeploy() {
try {
deployment.createThreadSetupAction(new ThreadSetupHandler.Action<Void, Object>() {
@Override
public Void call(HttpServerExchange exchange, Object ignore) throws ServletException {
for(ServletContextListener listener : deployment.getDeploymentInfo().getDeploymentCompleteListeners()) {
try {
listener.contextDestroyed(new ServletContextEvent(deployment.getServletContext()));
} catch (Throwable t) {
UndertowServletLogger.REQUEST_LOGGER.failedToDestroy(listener, t);
}
}
deployment.destroy();
deployment = null;
state = State.UNDEPLOYED;
return null;
}
}).call(null, null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void testContextLoaderListenerWithDefaultContext() {
MockServletContext sc = new MockServletContext("");
sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
"/org/springframework/web/context/WEB-INF/applicationContext.xml " +
"/org/springframework/web/context/WEB-INF/context-addition.xml");
ServletContextListener listener = new ContextLoaderListener();
ServletContextEvent event = new ServletContextEvent(sc);
listener.contextInitialized(event);
WebApplicationContext context = (WebApplicationContext) sc.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
assertTrue("Correct WebApplicationContext exposed in ServletContext", context instanceof XmlWebApplicationContext);
assertTrue(WebApplicationContextUtils.getRequiredWebApplicationContext(sc) instanceof XmlWebApplicationContext);
LifecycleBean lb = (LifecycleBean) context.getBean("lifecycle");
assertTrue("Has father", context.containsBean("father"));
assertTrue("Has rod", context.containsBean("rod"));
assertTrue("Has kerry", context.containsBean("kerry"));
assertTrue("Not destroyed", !lb.isDestroyed());
assertFalse(context.containsBean("beans1.bean1"));
assertFalse(context.containsBean("beans1.bean2"));
listener.contextDestroyed(event);
assertTrue("Destroyed", lb.isDestroyed());
assertNull(sc.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE));
assertNull(WebApplicationContextUtils.getWebApplicationContext(sc));
}
@Test
public void testContextLoaderWithInvalidContext() throws Exception {
MockServletContext sc = new MockServletContext("");
sc.addInitParameter(ContextLoader.CONTEXT_CLASS_PARAM,
"org.springframework.web.context.support.InvalidWebApplicationContext");
ServletContextListener listener = new ContextLoaderListener();
ServletContextEvent event = new ServletContextEvent(sc);
try {
listener.contextInitialized(event);
fail("Should have thrown ApplicationContextException");
}
catch (ApplicationContextException ex) {
// expected
assertTrue(ex.getCause() instanceof ClassNotFoundException);
}
}
@Override
public void onStartup(ServletContext webappContext) throws ServletException {
ModuleDataExtractor extractor = new ModuleDataExtractor(module);
microserverEnvironment.assureModule(module);
String fullRestResource = "/" + module.getContext() + "/*";
ServerData serverData = new ServerData(microserverEnvironment.getModuleBean(module).getPort(),
Arrays.asList(),
rootContext, fullRestResource, module);
List<FilterData> filterDataList = extractor.createFilteredDataList(serverData);
List<ServletData> servletDataList = extractor.createServletDataList(serverData);
new ServletConfigurer(serverData, LinkedListX.fromIterable(servletDataList)).addServlets(webappContext);
new FilterConfigurer(serverData, LinkedListX.fromIterable(filterDataList)).addFilters(webappContext);
PersistentList<ServletContextListener> servletContextListenerData = LinkedListX.fromIterable(module.getListeners(serverData)).filter(i->!(i instanceof ContextLoader));
PersistentList<ServletRequestListener> servletRequestListenerData = LinkedListX.fromIterable(module.getRequestListeners(serverData));
new ServletContextListenerConfigurer(serverData, servletContextListenerData, servletRequestListenerData).addListeners(webappContext);
}
@Override
public void onStartup(ServletContext webappContext) throws ServletException {
ModuleDataExtractor extractor = new ModuleDataExtractor(module);
microserverEnvironment.assureModule(module);
String fullRestResource = "/" + module.getContext() + "/*";
ServerData serverData = new ServerData(microserverEnvironment.getModuleBean(module).getPort(),
Arrays.asList(),
rootContext, fullRestResource, module);
List<FilterData> filterDataList = extractor.createFilteredDataList(serverData);
List<ServletData> servletDataList = extractor.createServletDataList(serverData);
new ServletConfigurer(serverData, LinkedListX.fromIterable(servletDataList)).addServlets(webappContext);
new FilterConfigurer(serverData, LinkedListX.fromIterable(filterDataList)).addFilters(webappContext);
PersistentList<ServletContextListener> servletContextListenerData = LinkedListX.fromIterable(module.getListeners(serverData)).filter(i->!(i instanceof ContextLoader));
PersistentList<ServletRequestListener> servletRequestListenerData = LinkedListX.fromIterable(module.getRequestListeners(serverData));
new ServletContextListenerConfigurer(serverData, servletContextListenerData, servletRequestListenerData).addListeners(webappContext);
}
default List<ServletContextListener> getListeners(ServerData data) {
List<ServletContextListener> list = new ArrayList<>();
if (data.getRootContext() instanceof WebApplicationContext) {
list.add(new ContextLoaderListener(
(WebApplicationContext) data.getRootContext()));
}
ListX<Plugin> modules = PluginLoader.INSTANCE.plugins.get();
ListX<ServletContextListener> listeners = modules.stream()
.filter(module -> module.servletContextListeners() != null)
.concatMap(Plugin::servletContextListeners)
.map(fn -> fn.apply(data))
.to(ListX::fromIterable);
return listeners.plusAll(list);
}
@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()));
}
}
@Test
public void testContextLoaderWithCustomContext() throws Exception {
MockServletContext sc = new MockServletContext("");
sc.addInitParameter(ContextLoader.CONTEXT_CLASS_PARAM,
"org.springframework.web.servlet.SimpleWebApplicationContext");
ServletContextListener listener = new ContextLoaderListener();
ServletContextEvent event = new ServletContextEvent(sc);
listener.contextInitialized(event);
String contextAttr = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
WebApplicationContext wc = (WebApplicationContext) sc.getAttribute(contextAttr);
assertTrue("Correct WebApplicationContext exposed in ServletContext",
wc instanceof SimpleWebApplicationContext);
}
@Test
public void testContextLoaderWithInvalidLocation() throws Exception {
MockServletContext sc = new MockServletContext("");
sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "/WEB-INF/myContext.xml");
ServletContextListener listener = new ContextLoaderListener();
ServletContextEvent event = new ServletContextEvent(sc);
try {
listener.contextInitialized(event);
fail("Should have thrown BeanDefinitionStoreException");
}
catch (BeanDefinitionStoreException ex) {
// expected
assertTrue(ex.getCause() instanceof FileNotFoundException);
}
}
@Test
public void testContextLoaderWithDefaultLocation() throws Exception {
MockServletContext sc = new MockServletContext("");
ServletContextListener listener = new ContextLoaderListener();
ServletContextEvent event = new ServletContextEvent(sc);
try {
listener.contextInitialized(event);
fail("Should have thrown BeanDefinitionStoreException");
}
catch (BeanDefinitionStoreException ex) {
// expected
assertTrue(ex.getCause() instanceof IOException);
assertTrue(ex.getCause().getMessage().contains("/WEB-INF/applicationContext.xml"));
}
}
@Override
public <T extends EventListener> void addListener(final T t) {
ensureNotInitialized();
ensureNotProgramaticListener();
if (ApplicationListeners.listenerState() != NO_LISTENER
&& ServletContextListener.class.isAssignableFrom(t.getClass())) {
throw UndertowServletMessages.MESSAGES.cannotAddServletContextListener();
}
ListenerInfo listener = new ListenerInfo(t.getClass(), new ImmediateInstanceFactory<EventListener>(t));
deploymentInfo.addListener(listener);
deployment.getApplicationListeners().addListener(new ManagedListener(listener, true));
}
public void contextDestroyed() {
if(!started) {
return;
}
final ServletContextEvent event = new ServletContextEvent(servletContext);
for (int i = servletContextListeners.length - 1; i >= 0; --i) {
ManagedListener listener = servletContextListeners[i];
try {
this.<ServletContextListener>get(listener).contextDestroyed(event);
} catch (Throwable t) {
UndertowServletLogger.REQUEST_LOGGER.errorInvokingListener("contextDestroyed", listener.getListenerInfo().getListenerClass(), t);
}
}
}
@Test
public void testContextLoaderWithCustomContext() throws Exception {
MockServletContext sc = new MockServletContext("");
sc.addInitParameter(ContextLoader.CONTEXT_CLASS_PARAM,
"org.springframework.web.servlet.SimpleWebApplicationContext");
ServletContextListener listener = new ContextLoaderListener();
ServletContextEvent event = new ServletContextEvent(sc);
listener.contextInitialized(event);
String contextAttr = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
WebApplicationContext wc = (WebApplicationContext) sc.getAttribute(contextAttr);
assertTrue("Correct WebApplicationContext exposed in ServletContext",
wc instanceof SimpleWebApplicationContext);
}
public void contextDestroyed(ServletContextEvent sce) {
if (ctx == null) {
logger.warn("cannot find applicationContext");
return;
}
Collection<ServletContextListener> servletContextListeners = ctx
.getBeansOfType(ServletContextListener.class).values();
for (ServletContextListener servletContextListener : servletContextListeners) {
servletContextListener.contextDestroyed(sce);
}
}
@Test
public void testContextLoaderWithDefaultLocation() throws Exception {
MockServletContext sc = new MockServletContext("");
ServletContextListener listener = new ContextLoaderListener();
ServletContextEvent event = new ServletContextEvent(sc);
try {
listener.contextInitialized(event);
fail("Should have thrown BeanDefinitionStoreException");
}
catch (BeanDefinitionStoreException ex) {
// expected
assertTrue(ex.getCause() instanceof IOException);
assertTrue(ex.getCause().getMessage().contains("/WEB-INF/applicationContext.xml"));
}
}
@Override
public <T extends EventListener> void addListener(final T t) {
ensureNotInitialized();
ensureNotProgramaticListener();
if (ApplicationListeners.listenerState() != NO_LISTENER
&& ServletContextListener.class.isAssignableFrom(t.getClass())) {
throw UndertowServletMessages.MESSAGES.cannotAddServletContextListener();
}
ListenerInfo listener = new ListenerInfo(t.getClass(), new ImmediateInstanceFactory<EventListener>(t));
deploymentInfo.addListener(listener);
deployment.getApplicationListeners().addListener(new ManagedListener(listener, true));
}
public void contextDestroyed() {
if(!started) {
return;
}
final ServletContextEvent event = new ServletContextEvent(servletContext);
for (int i = servletContextListeners.length - 1; i >= 0; --i) {
ManagedListener listener = servletContextListeners[i];
try {
this.<ServletContextListener>get(listener).contextDestroyed(event);
} catch (Throwable t) {
UndertowServletLogger.REQUEST_LOGGER.errorInvokingListener("contextDestroyed", listener.getListenerInfo().getListenerClass(), t);
}
}
}
@Test
public void testContextLoaderWithDefaultContextAndParent() throws Exception {
MockServletContext sc = new MockServletContext("");
sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
"/org/springframework/web/context/WEB-INF/applicationContext.xml "
+ "/org/springframework/web/context/WEB-INF/context-addition.xml");
sc.addInitParameter(ContextLoader.LOCATOR_FACTORY_SELECTOR_PARAM,
"classpath:org/springframework/web/context/ref1.xml");
sc.addInitParameter(ContextLoader.LOCATOR_FACTORY_KEY_PARAM, "a.qualified.name.of.some.sort");
ServletContextListener listener = new ContextLoaderListener();
ServletContextEvent event = new ServletContextEvent(sc);
listener.contextInitialized(event);
WebApplicationContext context = (WebApplicationContext) sc.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
assertTrue("Correct WebApplicationContext exposed in ServletContext",
context instanceof XmlWebApplicationContext);
LifecycleBean lb = (LifecycleBean) context.getBean("lifecycle");
assertTrue("Has father", context.containsBean("father"));
assertTrue("Has rod", context.containsBean("rod"));
assertTrue("Has kerry", context.containsBean("kerry"));
assertTrue("Not destroyed", !lb.isDestroyed());
assertTrue(context.containsBean("beans1.bean1"));
assertTrue(context.isTypeMatch("beans1.bean1", org.springframework.beans.factory.access.TestBean.class));
assertTrue(context.containsBean("beans1.bean2"));
assertTrue(context.isTypeMatch("beans1.bean2", org.springframework.beans.factory.access.TestBean.class));
listener.contextDestroyed(event);
assertTrue("Destroyed", lb.isDestroyed());
}