下面列出了怎么用javax.servlet.ServletContextEvent的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void contextInitialized(ServletContextEvent event) {
try {
// Birt must generate messages in here, because it has no struts like EMM
// Messages are then available via I18nString
DBMessagesResource dbMessagesResource = new DBMessagesResource();
dbMessagesResource.init();
ServletContext servletContext = event.getServletContext();
if (ConfigService.getInstance().getBooleanValue(ConfigValue.IsLiveInstance)) {
createMessagesPropertiesFiles(servletContext);
}
} catch (Exception e) {
logger.error("MessagesPropertiesGeneratorContextListener init: " + e.getMessage(), 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));
}
@Override
public void contextInitialized(ServletContextEvent event) {
ServletContext servletContext = event.getServletContext();
WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
configService = webApplicationContext.getBean("ConfigService", ConfigService.class);
if (servletContext.getAttribute(ExtensionConstants.EXTENSION_SYSTEM_APPLICATION_SCOPE_ATTRIBUTE) != null) {
logger.fatal ("Extension system already initialized for the application context");
} else {
try {
ExtensionSystemImpl extensionSystem = createExtensionSystem( servletContext);
servletContext.setAttribute(ExtensionConstants.EXTENSION_SYSTEM_APPLICATION_SCOPE_ATTRIBUTE, extensionSystem);
extensionSystem.startUp();
} catch (Exception e) {
logger.fatal("Error initializing extension system", e);
}
}
}
/**
* If a contextConfigLocation init-param has been specified for the ContextLoaderListener,
* then it should take precedence. This is generally not a recommended practice, but
* when it does happen, the init-param should be considered more specific than the
* programmatic configuration, given that it still quite possibly externalized in
* hybrid web.xml + WebApplicationInitializer cases.
*/
@Test
public void abstractRefreshableWAC_respectsInitParam_overProgrammaticConfigLocations() {
XmlWebApplicationContext ctx = new XmlWebApplicationContext();
ctx.setConfigLocation("programmatic.xml");
ContextLoaderListener cll = new ContextLoaderListener(ctx);
MockServletContext sc = new MockServletContext();
sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");
try {
cll.contextInitialized(new ServletContextEvent(sc));
fail("expected exception");
}
catch (Throwable t) {
// assert that an attempt was made to load the correct XML
assertTrue(t.getMessage(), t.getMessage().endsWith(
"Could not open ServletContext resource [/from-init-param.xml]"));
}
}
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext sc = sce.getServletContext();
servletContext = sc;
// Try and use one of the Servlet 3.0 methods that should be blocked
try {
sc.getEffectiveMajorVersion();
log.append("FAIL-01");
} catch (UnsupportedOperationException uoe) {
log.append("PASS-01");
} catch (Exception e) {
log.append("FAIL-02");
}
}
@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);
}
}
@Override
public void contextInitialized(ServletContextEvent sce) {
super.contextInitialized(sce);
ServerContainer sc =
(ServerContainer) sce.getServletContext().getAttribute(
Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);
try {
sc.addEndpoint(Async.class);
sc.addEndpoint(Basic.class);
sc.addEndpoint(BasicLimitLow.class);
sc.addEndpoint(BasicLimitHigh.class);
sc.addEndpoint(WriterError.class);
sc.addEndpoint(RootEcho.class);
} catch (DeploymentException e) {
throw new IllegalStateException(e);
}
}
@Override
public final void contextInitialized(final ServletContextEvent servletContextEvent) {
try {
final WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContextEvent.getServletContext());
final StartupJobExecutionService executionService = webApplicationContext.getBean("StartupJobExecutionService", StartupJobExecutionService.class);
if(LOGGER.isInfoEnabled()) {
LOGGER.info("Starting execution of startup jobs");
}
final ExecutionResult result = executionService.executeAllPendingJobs();
logResult(result);
} catch (final Exception e) {
LOGGER.error("Error processing startup jobs", e);
}
}
/**
* context初始化.
*/
@Override
public void contextInitialized(ServletContextEvent event) {
System.out.println("contextInitialized");
ServletContext servletContext = event.getServletContext();
if (null == this.context) {
//配置的application文件路径
String cfgFile = servletContext.getInitParameter("contextConfigLocation");
this.context = new WebApplicationContext(cfgFile);
//存入上下文,后面servlet会取用
servletContext.setAttribute(ROOT_CXT_ATTR, this.context);
}
//源码中是在这里初始化context,调用refresh方法的,我们在上面new的时候先做了
// initWebApplicationContext(this.context);
}
/**
* If setConfigLocation has not been called explicitly against the application context,
* then fall back to the ContextLoaderListener init-param if present.
*/
@Test
public void abstractRefreshableWAC_fallsBackToInitParam() {
XmlWebApplicationContext ctx = new XmlWebApplicationContext();
//ctx.setConfigLocation("programmatic.xml"); // nothing set programmatically
ContextLoaderListener cll = new ContextLoaderListener(ctx);
MockServletContext sc = new MockServletContext();
sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM, "from-init-param.xml");
try {
cll.contextInitialized(new ServletContextEvent(sc));
fail("expected exception");
}
catch (Throwable t) {
// assert that an attempt was made to load the correct XML
assertTrue(t.getMessage().endsWith(
"Could not open ServletContext resource [/from-init-param.xml]"));
}
}
@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 contextDestroyed(ServletContextEvent sce) {
// Shutdown our room.
Room room = DrawboardEndpoint.getRoom(false);
if (room != null) {
room.shutdown();
}
}
/**
* Record the fact that this web application has been initialized.
*
* @param event
* The servlet context event
*/
@Override
public void contextInitialized(ServletContextEvent event) {
this.context = event.getServletContext();
log("contextInitialized()");
}
/**
* Record the fact that this web application has been initialized.
*
* @param event The servlet context event
*/
@Override
public void contextInitialized(ServletContextEvent event) {
this.context = event.getServletContext();
log("contextInitialized()");
}
/**
* Record the fact that this web application has been destroyed.
*
* @param event
* The servlet context event
*/
@Override
public void contextDestroyed(ServletContextEvent event) {
log("contextDestroyed()");
this.context = null;
}
/**
* Record the fact that this web application has been destroyed.
*
* @param event The servlet context event
*/
@Override
public void contextDestroyed(ServletContextEvent event) {
log("contextDestroyed()");
this.context = null;
}
@Override
public void contextInitialized(ServletContextEvent evt) {
ServletContext sc = evt.getServletContext();
//项目发布,当前运行环境的绝对路径
conf.put("realPath", sc.getRealPath("/").replaceFirst("/", ""));
//servletContextPath,默认""
conf.put("contextPath", sc.getContextPath());
}
/**
* Ensure that ContextLoaderListener and AnnotationConfigApplicationContext interact nicely.
*/
@Test
public void annotationConfigWAC() {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.scan("does.not.matter");
ContextLoaderListener cll = new ContextLoaderListener(ctx);
cll.contextInitialized(new ServletContextEvent(new MockServletContext()));
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// Bug 57446. Same ServletContext should be presented as at init
if (servletContext == sce.getServletContext()) {
log.append("PASS-02");
} else {
//log.append("FAIL-03");
}
}
@Override
public void contextInitialized(ServletContextEvent sce) {
super.contextInitialized(sce);
ServerContainer sc =
(ServerContainer) sce.getServletContext().getAttribute(
Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);
try {
// Reset blocking state
BlockingPojo.resetBlock();
sc.addEndpoint(BlockingPojo.class);
} catch (DeploymentException e) {
throw new IllegalStateException(e);
}
}
@Override
public void contextInitialized(ServletContextEvent sce) {
// Create a reporter and add it to the registry.
// For demo purposes we use SLF4JReporter which should not be used for production systems
SLF4JReporter reporter = SLF4JReporter.builder().withName("example").withStepSize(10).build();
MyApp.metricRegistry.addReporter(reporter);
sce.getServletContext().setAttribute(REPORTER_ATTRIBUTE, reporter);
}
@Override
public void contextInitialized(ServletContextEvent event) {
try {
ServletContext servletContext = event.getServletContext();
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
DBase.DATASOURCE = (DataSource) applicationContext.getBean("dataSource");
if (DBase.DATASOURCE == null) {
logger.error("Datasource in DBase for Backend was empty. Backend will try to create its own datasource from emm.properties data");
}
} catch (Exception e) {
logger.error("Cannot set Datasource in DBase for Backend. Backend will try to create its own datasource from emm.properties data", e);
}
}
@Override
public void contextInitialized(ServletContextEvent event) {
try {
if (I18nString.MESSAGE_RESOURCES == null) {
DBMessagesResource dbMessagesResource = new DBMessagesResource();
dbMessagesResource.init();
}
} catch (Exception e) {
logger.error("I18NContextListenerForWebservice init: " + e.getMessage(), e);
}
}
@Override
public void contextDestroyed(ServletContextEvent event) {
if (log.isLoggable(Level.FINER)) {
log.entering(FHIRServletContextListener.class.getName(), "contextDestroyed");
}
try {
// Set our "initComplete" flag back to false.
event.getServletContext().setAttribute(FHIR_SERVER_INIT_COMPLETE, Boolean.FALSE);
// If we previously initialized the Kafka publisher, then shut it down now.
if (kafkaPublisher != null) {
kafkaPublisher.shutdown();
kafkaPublisher = null;
}
// If we previously initialized the NATS publisher, then shut it down now.
if (natsPublisher != null) {
natsPublisher.shutdown();
natsPublisher = null;
}
} catch (Exception e) {
} finally {
if (log.isLoggable(Level.FINER)) {
log.exiting(FHIRServletContextListener.class.getName(), "contextDestroyed");
}
}
}
@Test
public void testContextLoaderListenerWithLocalContextInitializers() {
MockServletContext sc = new MockServletContext("");
sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
"org/springframework/web/context/WEB-INF/ContextLoaderTests-acc-context.xml");
sc.addInitParameter(ContextLoader.CONTEXT_INITIALIZER_CLASSES_PARAM, StringUtils.arrayToCommaDelimitedString(
new Object[] {TestContextInitializer.class.getName(), TestWebContextInitializer.class.getName()}));
ContextLoaderListener listener = new ContextLoaderListener();
listener.contextInitialized(new ServletContextEvent(sc));
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
TestBean testBean = wac.getBean(TestBean.class);
assertThat(testBean.getName(), equalTo("testName"));
assertThat(wac.getServletContext().getAttribute("initialized"), notNullValue());
}
@Test
public void testContextLoaderListenerWithGlobalContextInitializers() {
MockServletContext sc = new MockServletContext("");
sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
"org/springframework/web/context/WEB-INF/ContextLoaderTests-acc-context.xml");
sc.addInitParameter(ContextLoader.GLOBAL_INITIALIZER_CLASSES_PARAM, StringUtils.arrayToCommaDelimitedString(
new Object[] {TestContextInitializer.class.getName(), TestWebContextInitializer.class.getName()}));
ContextLoaderListener listener = new ContextLoaderListener();
listener.contextInitialized(new ServletContextEvent(sc));
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
TestBean testBean = wac.getBean(TestBean.class);
assertThat(testBean.getName(), equalTo("testName"));
assertThat(wac.getServletContext().getAttribute("initialized"), notNullValue());
}
@Test
public void testContextLoaderListenerWithProgrammaticInitializers() {
MockServletContext sc = new MockServletContext("");
sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
"org/springframework/web/context/WEB-INF/ContextLoaderTests-acc-context.xml");
ContextLoaderListener listener = new ContextLoaderListener();
listener.setContextInitializers(new TestContextInitializer(), new TestWebContextInitializer());
listener.contextInitialized(new ServletContextEvent(sc));
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
TestBean testBean = wac.getBean(TestBean.class);
assertThat(testBean.getName(), equalTo("testName"));
assertThat(wac.getServletContext().getAttribute("initialized"), notNullValue());
}
@Test
public void testContextLoaderListenerWithProgrammaticAndGlobalInitializers() {
MockServletContext sc = new MockServletContext("");
sc.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
"org/springframework/web/context/WEB-INF/ContextLoaderTests-acc-context.xml");
sc.addInitParameter(ContextLoader.GLOBAL_INITIALIZER_CLASSES_PARAM, TestWebContextInitializer.class.getName());
ContextLoaderListener listener = new ContextLoaderListener();
listener.setContextInitializers(new TestContextInitializer());
listener.contextInitialized(new ServletContextEvent(sc));
WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
TestBean testBean = wac.getBean(TestBean.class);
assertThat(testBean.getName(), equalTo("testName"));
assertThat(wac.getServletContext().getAttribute("initialized"), notNullValue());
}
@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);
}
/**
* Ensure that ContextLoaderListener and GenericWebApplicationContext interact nicely.
*/
@Test
public void genericWAC() {
GenericWebApplicationContext ctx = new GenericWebApplicationContext();
ContextLoaderListener cll = new ContextLoaderListener(ctx);
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(ctx);
scanner.scan("bogus.pkg");
cll.contextInitialized(new ServletContextEvent(new MockServletContext()));
}