javax.servlet.ServletContext#addListener ( )源码实例Demo

下面列出了javax.servlet.ServletContext#addListener ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: sakai   文件: WebAppConfiguration.java
@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);
}
 
源代码2 项目: herd   文件: WarInitializer.java
/**
 * 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));
}
 
源代码3 项目: Tomcat8-Source-Read   文件: JasperInitializer.java
@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()));
}
 
源代码4 项目: dolphin-platform   文件: MetricsModule.java
@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);
    }
}
 
源代码5 项目: tutorials   文件: MainWebAppInitializer.java
@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("/");
}
 
源代码8 项目: tracee   文件: TraceeFilterIT.java
@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");
}
 
源代码9 项目: springsecuritystudy   文件: WebAppInitializer.java
@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);
}
 
源代码10 项目: tutorials   文件: MainWebAppInitializer.java
/**
 * 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));
}
 
源代码11 项目: Spring-5.0-Cookbook   文件: SpringWebinitializer.java
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));
   
}
 
源代码12 项目: Spring-5.0-Cookbook   文件: SpringWebInitializer.java
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/*");
}
 
源代码14 项目: Spring-5.0-Cookbook   文件: SpringWebInitializer.java
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");
    }
 
源代码16 项目: live-chat-engine   文件: SecurityService.java
public void init(ServletContext servletContext){
	servletContext.addListener(this);
}
 
源代码17 项目: tomcatsrc   文件: TestListener.java
@Override
public void contextInitialized(ServletContextEvent sce) {
    ServletContext sc = sce.getServletContext();
    sc.addListener(SCL3.class.getName());
}
 
源代码18 项目: molgenis   文件: MolgenisWebAppInitializer.java
/** 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;
}
 
源代码20 项目: Tomcat7.0.67   文件: TestListener.java
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx)
        throws ServletException {
    ctx.addListener(new SCL());
}