下面列出了javax.servlet.ServletContext#addListener ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.setServletContext(servletContext);
rootContext.register(ThymeleafConfig.class);
servletContext.addListener(new ToolListener());
servletContext.addListener(new SakaiContextLoaderListener(rootContext));
servletContext.addFilter("sakai.request", RequestFilter.class)
.addMappingForUrlPatterns(
EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE),
true,
"/*");
Dynamic servlet = servletContext.addServlet("sakai.message.bundle.manager", new DispatcherServlet(rootContext));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
/**
* Initializes the context loader listener which bootstraps Spring and provides access to the application context.
*
* @param servletContext the servlet context.
*/
protected void initContextLoaderListener(ServletContext servletContext)
{
// Add the context loader listener for the base (i.e. root) Spring configuration.
// We register all our @Configuration annotated classes with the context so Spring will load all the @Bean's via these classes.
// We also set the application context in an application context holder before "registering" so static @Bean's
// (e.g. PropertySourcesPlaceholderConfigurer) will have access to it since they can't take advantage of autowiring or having a class be
// ApplicationContextAware to get it.
AnnotationConfigWebApplicationContext contextLoaderListenerContext = new AnnotationConfigWebApplicationContext();
ApplicationContextHolder.setApplicationContext(contextLoaderListenerContext);
contextLoaderListenerContext
.register(CoreSpringModuleConfig.class, DaoSpringModuleConfig.class, DaoEnvSpringModuleConfig.class, ServiceSpringModuleConfig.class,
ServiceEnvSpringModuleConfig.class, UiSpringModuleConfig.class, UiEnvSpringModuleConfig.class, RestSpringModuleConfig.class,
AppSpringModuleConfig.class);
servletContext.addListener(new ContextLoaderListener(contextLoaderListenerContext));
}
@Override
public void onStartup(Set<Class<?>> types, ServletContext context) throws ServletException {
if (log.isDebugEnabled()) {
log.debug(Localizer.getMessage(MSG + ".onStartup", context.getServletContextName()));
}
// Setup a simple default Instance Manager
if (context.getAttribute(InstanceManager.class.getName())==null) {
context.setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager());
}
boolean validate = Boolean.parseBoolean(
context.getInitParameter(Constants.XML_VALIDATION_TLD_INIT_PARAM));
String blockExternalString = context.getInitParameter(
Constants.XML_BLOCK_EXTERNAL_INIT_PARAM);
boolean blockExternal;
if (blockExternalString == null) {
blockExternal = true;
} else {
blockExternal = Boolean.parseBoolean(blockExternalString);
}
// scan the application for TLDs
TldScanner scanner = newTldScanner(context, true, validate, blockExternal);
try {
scanner.scan();
} catch (IOException | SAXException e) {
throw new ServletException(e);
}
// add any listeners defined in TLDs
for (String listener : scanner.getListeners()) {
context.addListener(listener);
}
context.setAttribute(TldCache.SERVLET_CONTEXT_ATTRIBUTE_NAME,
new TldCache(context, scanner.getUriTldResourcePathMap(),
scanner.getTldResourcePathTaglibXmlMap()));
}
@Override
public void initialize(final ServerCoreComponents coreComponents) {
final PlatformConfiguration configuration = coreComponents.getConfiguration();
final ServletContext servletContext = coreComponents.getInstance(ServletContext.class);
if(!configuration.getBooleanProperty(METRICS_NOOP_PROPERTY, true)) {
final PrometheusMeterRegistry prometheusRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
final List<Tag> tagList = TagUtil.convertTags(ContextManagerImpl.getInstance().getGlobalContexts());
new ClassLoaderMetrics(tagList).bindTo(prometheusRegistry);
new JvmMemoryMetrics(tagList).bindTo(prometheusRegistry);
new JvmGcMetrics(tagList).bindTo(prometheusRegistry);
new ProcessorMetrics(tagList).bindTo(prometheusRegistry);
new JvmThreadMetrics(tagList).bindTo(prometheusRegistry);
servletContext.addFilter(METRICS_SERVLET_FILTER_NAME, new RequestMetricsFilter())
.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, ALL_URL_MAPPING);
servletContext.addListener(new MetricsHttpSessionListener());
servletContext.addServlet(METRICS_SERVLET_NAME, new MetricsServlet(prometheusRegistry))
.addMapping(configuration.getProperty(METRICS_ENDPOINT_PROPERTY));
MetricsImpl.getInstance().init(prometheusRegistry);
}
}
@Override
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.scan("com.baeldung");
container.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = container.addServlet("mvc", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
/**
* Register a {@link ContextLoaderListener} against the given servlet context. The
* {@code ContextLoaderListener} is initialized with the application context returned
* from the {@link #createRootApplicationContext()} template method.
* @param servletContext the servlet context to register the listener against
*/
protected void registerContextLoaderListener(ServletContext servletContext) {
WebApplicationContext rootAppContext = createRootApplicationContext();
if (rootAppContext != null) {
ContextLoaderListener listener = new ContextLoaderListener(rootAppContext);
listener.setContextInitializers(getRootApplicationContextInitializers());
servletContext.addListener(listener);
}
else {
logger.debug("No ContextLoaderListener registered, as " +
"createRootApplicationContext() did not return an application context");
}
}
private void processBootstrap(final Class<GuiceRsBootstrap> bootstrap, final ServletContext context)
{
ImmutableList.Builder<Module> modules = ImmutableList.builder();
Module module;
module = GuiceRsServerControlModule.fromInitParameter(context);
if (module != null) {
modules.add(module);
}
modules.add((binder) -> {
binder.bind(GuiceRsBootstrap.class).to(bootstrap).asEagerSingleton();
binder.bind(ServletContext.class).toInstance(context);
});
final Injector injector = Guice.createInjector(modules.build())
.getInstance(GuiceRsBootstrap.class)
.initialize(context);
if (injector instanceof AutoCloseable) {
context.addListener(new CloseableInjectorDestroyListener((AutoCloseable) injector));
}
injector.findBindingsByType(TypeLiteral.get(GuiceRsServletInitializer.class))
.stream()
.map(binding -> binding.getProvider().get())
.forEach(initializer -> initializer.register(injector, context));
// return 404 Not Found if all URL patterns don't match
context.addServlet("default", new DefaultServlet())
.addMapping("/");
}
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
ctx.addFilter("traceeFilter", TraceeFilter.class).addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/*");
ctx.addListener(TraceeServletRequestListener.class);
ctx.addListener(TraceeSessionListener.class);
final ServletRegistration.Dynamic sillyServlet = ctx.addServlet("sillyServlet", SillyServlet.class);
sillyServlet.addMapping("/sillyServlet", "/sillyFlushingServlet");
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy("springSecurityFilterChain"))
.addMappingForUrlPatterns(null, false, "/api/*");
// 静态资源映射
servletContext.getServletRegistration("default").addMapping("/static/*", "*.html", "*.ico");
servletContext.addListener(HttpSessionEventPublisher.class);
super.onStartup(servletContext);
}
/**
* Register and configure all Servlet container components necessary to power the web application.
*/
@Override
public void onStartup(final ServletContext sc) throws ServletException {
LOGGER.info("MainWebAppInitializer.onStartup()");
sc.setInitParameter("javax.faces.FACELETS_SKIP_COMMENTS", "true");
// Create the 'root' Spring application context
final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.register(SpringCoreConfig.class);
sc.addListener(new ContextLoaderListener(root));
}
private void addRootContext(ServletContext container) {
// Create the application context
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(SpringContextConfig.class);
// Register application context with ContextLoaderListener
container.addListener(new ContextLoaderListener(rootContext));
}
private void addRootContext(ServletContext container) {
// Create the application context
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(SpringContextConfig.class);
// Register application context with ContextLoaderListener
container.addListener(new ContextLoaderListener(rootContext));
container.addListener(new AppSessionListener());
container.setInitParameter("contextConfigLocation", "org.packt.secured.mvc.core");
container.setSessionTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE)); // if URL, enable sessionManagement URL rewriting
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
this.servletContext = servletContext;
servletContext.setSessionTrackingModes(Collections.singleton(SessionTrackingMode.COOKIE));
servletContext.addListener(new CockpitContainerBootstrap());
servletContext.addListener(new AdminContainerBootstrap());
servletContext.addListener(new TasklistContainerBootstrap());
servletContext.addListener(new WelcomeContainerBootstrap());
servletContext.addListener(new HttpSessionMutexListener());
registerFilter("Authentication Filter", AuthenticationFilter.class, "/api/*", "/app/*");
registerFilter("Security Filter", LazySecurityFilter.class, singletonMap("configFile", properties.getWebapp().getSecurityConfigFile()), "/api/*", "/app/*");
registerFilter("CsrfPreventionFilter", SpringBootCsrfPreventionFilter.class, properties.getWebapp().getCsrf().getInitParams(),"/api/*", "/app/*");
Map<String, String> headerSecurityProperties = properties.getWebapp()
.getHeaderSecurity()
.getInitParams();
registerFilter("HttpHeaderSecurity", HttpHeaderSecurityFilter.class, headerSecurityProperties,"/api/*", "/app/*");
registerFilter("Engines Filter", LazyProcessEnginesFilter.class, "/api/*", "/app/*");
registerFilter("EmptyBodyFilter", EmptyBodyFilter.class, "/api/*", "/app/*");
registerFilter("CacheControlFilter", CacheControlFilter.class, "/api/*", "/app/*");
registerServlet("Cockpit Api", CockpitApplication.class, "/api/cockpit/*");
registerServlet("Admin Api", AdminApplication.class, "/api/admin/*");
registerServlet("Tasklist Api", TasklistApplication.class, "/api/tasklist/*");
registerServlet("Engine Api", EngineRestApplication.class, "/api/engine/*");
registerServlet("Welcome Api", WelcomeApplication.class, "/api/welcome/*");
}
private void addRootContext(ServletContext container) {
// Create the application context
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(SpringContextConfig.class);
// Register application context with ContextLoaderListener
container.addListener(new ContextLoaderListener(rootContext));
}
protected void createWebApplicationContext(ServletContext servletContext, Class clazz) {
log.info("Creating Web Application Context started");
List<Class> configClasses = new ArrayList<>();
configClasses.add(clazz);
// let's determine if this is a cloud based server
Cloud cloud = getCloud();
String activeProfiles = System.getProperty(SPRING_PROFILES_ACTIVE);
if (StringUtils.isEmpty(activeProfiles)) {
if (cloud == null) {
// if no active profiles are specified, we default to these profiles
activeProfiles = String.format("%s,%s,%s,%s,%s", MONGODB_LOCAL,REDIS_LOCAL,RABBIT_LOCAL,ELASTICSEARCH_LOCAL,LOCAL);
} else {
activeProfiles = String.format("%s,%s,%s,%s,%s", MONGODB_CLOUD,REDIS_CLOUD,RABBIT_CLOUD,ELASTICSEARCH_CLOUD,CLOUD);
}
}
log.info("Active spring profiles: " + activeProfiles);
// load local or cloud based configs
if (cloud != null) {
// list available service - fail servlet initializing if we are missing one that we require below
printAvailableCloudServices(cloud.getServiceInfos());
}
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(configClasses.toArray(new Class[configClasses.size()]));
servletContext.addListener(new ContextLoaderListener(appContext));
servletContext.addListener(new RequestContextListener());
// log.info("Creating Web Application Context completed");
}
public void init(ServletContext servletContext){
servletContext.addListener(this);
}
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext sc = sce.getServletContext();
sc.addListener(SCL3.class.getName());
}
/** A Molgenis common web application initializer */
protected void onStartup(ServletContext servletContext, Class<?> appConfig, int maxFileSize) {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.registerShutdownHook();
rootContext.setAllowBeanDefinitionOverriding(false);
rootContext.register(appConfig);
// Manage the lifecycle of the root application context
servletContext.addListener(new ContextLoaderListener(rootContext));
// Register and map the dispatcher servlet
DispatcherServlet dispatcherServlet = new DispatcherServlet(rootContext);
dispatcherServlet.setDispatchOptionsRequest(true);
// instead of throwing a 404 when a handler is not found allow for custom handling
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
ServletRegistration.Dynamic dispatcherServletRegistration =
servletContext.addServlet("dispatcher", dispatcherServlet);
if (dispatcherServletRegistration == null) {
LOG.warn(
"ServletContext already contains a complete ServletRegistration for servlet 'dispatcher'");
} else {
final long maxSize = (long) maxFileSize * MB;
dispatcherServletRegistration.addMapping("/");
dispatcherServletRegistration.setMultipartConfig(
new MultipartConfigElement(null, maxSize, maxSize, FILE_SIZE_THRESHOLD));
dispatcherServletRegistration.setAsyncSupported(true);
}
// Add filters
Dynamic browserDetectionFiler =
servletContext.addFilter("browserDetectionFilter", BrowserDetectionFilter.class);
browserDetectionFiler.setAsyncSupported(true);
browserDetectionFiler.addMappingForUrlPatterns(
EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC), false, "*");
Dynamic etagFilter = servletContext.addFilter("etagFilter", ShallowEtagHeaderFilter.class);
etagFilter.setAsyncSupported(true);
etagFilter.addMappingForServletNames(
EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC), true, "dispatcher");
// enable use of request scoped beans in FrontController
servletContext.addListener(new RequestContextListener());
servletContext.addListener(HttpSessionEventPublisher.class);
}
private AnnotationConfigWebApplicationContext initContext(ServletContext servletContext) {
AnnotationConfigWebApplicationContext context = getContext();
servletContext.addListener(new ContextLoaderListener(context));
return context;
}
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx)
throws ServletException {
ctx.addListener(new SCL());
}