Java Code Examples for javax.servlet.ServletContext#addListener()

The following examples show how to use javax.servlet.ServletContext#addListener() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebAppConfiguration.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@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);
}
 
Example 2
Source File: WarInitializer.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * 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));
}
 
Example 3
Source File: JasperInitializer.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@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()));
}
 
Example 4
Source File: MetricsModule.java    From dolphin-platform with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 5
Source File: MainWebAppInitializer.java    From tutorials with MIT License 5 votes vote down vote up
@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("/");
}
 
Example 6
Source File: AbstractContextLoaderInitializer.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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");
	}
}
 
Example 7
Source File: GuiceRsServletContainerInitializer.java    From digdag with Apache License 2.0 5 votes vote down vote up
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("/");
}
 
Example 8
Source File: TraceeFilterIT.java    From tracee with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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");
}
 
Example 9
Source File: AbstractWebApplicationInitializer.java    From bearchoke with Apache License 2.0 5 votes vote down vote up
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");
    }
 
Example 10
Source File: WebAppInitializer.java    From springsecuritystudy with MIT License 5 votes vote down vote up
@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);
}
 
Example 11
Source File: SpringWebInitializer.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
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));
  
}
 
Example 12
Source File: MainWebAppInitializer.java    From tutorials with MIT License 5 votes vote down vote up
/**
 * 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));
}
 
Example 13
Source File: SpringWebinitializer.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
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));
   
}
 
Example 14
Source File: SpringWebInitializer.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
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   
}
 
Example 15
Source File: CamundaBpmWebappInitializer.java    From camunda-bpm-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@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/*");
}
 
Example 16
Source File: TestListener.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx)
        throws ServletException {
    ctx.addListener(new SCL());
}
 
Example 17
Source File: WebApplicationConfiguration.java    From junit-servers with MIT License 4 votes vote down vote up
private AnnotationConfigWebApplicationContext initContext(ServletContext servletContext) {
	AnnotationConfigWebApplicationContext context = getContext();
	servletContext.addListener(new ContextLoaderListener(context));
	return context;
}
 
Example 18
Source File: MolgenisWebAppInitializer.java    From molgenis with GNU Lesser General Public License v3.0 4 votes vote down vote up
/** 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);
}
 
Example 19
Source File: TestListener.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce) {
    ServletContext sc = sce.getServletContext();
    sc.addListener(SCL3.class.getName());
}
 
Example 20
Source File: SecurityService.java    From live-chat-engine with Apache License 2.0 4 votes vote down vote up
public void init(ServletContext servletContext){
	servletContext.addListener(this);
}