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

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

源代码1 项目: spring-analysis-note   文件: ContextLoader.java
/**
 * Close Spring's web application context for the given servlet context.
 * <p>If overriding {@link #loadParentContext(ServletContext)}, you may have
 * to override this method as well.
 * @param servletContext the ServletContext that the WebApplicationContext runs in
 */
public void closeWebApplicationContext(ServletContext servletContext) {
	servletContext.log("Closing Spring root WebApplicationContext");
	try {
		if (this.context instanceof ConfigurableWebApplicationContext) {
			((ConfigurableWebApplicationContext) this.context).close();
		}
	}
	finally {
		ClassLoader ccl = Thread.currentThread().getContextClassLoader();
		if (ccl == ContextLoader.class.getClassLoader()) {
			currentContext = null;
		}
		else if (ccl != null) {
			currentContextPerThread.remove(ccl);
		}
		servletContext.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
	}
}
 
源代码2 项目: white-label-event-app   文件: InitListener.java
@Override
public void contextInitialized(ServletContextEvent sce) {
    final ServletContext context = sce.getServletContext();
    context.log("InitListener");

    ResourcesConfigStrategy configStrategy = new ResourcesConfigStrategy();
    try {
        configStrategy.configure();
    }
    catch (ConfigException e) {
        throw new RuntimeException(e);
    }

    BackendSingletons.fdb = configStrategy.getFirebaseDatabase();
    BackendSingletons.eventmobiConfig = configStrategy.getEventmobiConfig();

    context.log("Firebase database: " + BackendSingletons.fdb.getReference());
    context.log("Eventmobi API key: " + BackendSingletons.eventmobiConfig.getApiKey());
    context.log("Eventmobi event name: " + BackendSingletons.eventmobiConfig.getEventName());
}
 
源代码3 项目: ontopia   文件: NavigatorUtils.java
/**
 * INTERNAL: Gets the navigator application instance belonging to
 * the web application.
 */
public final static NavigatorApplicationIF getNavigatorApplication(ServletContext servletContext) {

  NavigatorApplicationIF navApp = (NavigatorApplicationIF)
    servletContext.getAttribute(NavigatorApplicationIF.NAV_APP_KEY);

  // If there is no current navigator application we need to create one.
  if (navApp == null) {
      // Initialise new configuration and register it with application context
    navApp = new NavigatorApplication(servletContext);
    servletContext.setAttribute(NavigatorApplicationIF.NAV_APP_KEY, navApp);
    servletContext.log("Setup navigator configuration and " +
                       "assigned it to application context.");
    }
  return navApp;
}
 
源代码4 项目: java-technology-stack   文件: ContextLoader.java
/**
 * Close Spring's web application context for the given servlet context.
 * <p>If overriding {@link #loadParentContext(ServletContext)}, you may have
 * to override this method as well.
 * @param servletContext the ServletContext that the WebApplicationContext runs in
 */
public void closeWebApplicationContext(ServletContext servletContext) {
	servletContext.log("Closing Spring root WebApplicationContext");
	try {
		if (this.context instanceof ConfigurableWebApplicationContext) {
			((ConfigurableWebApplicationContext) this.context).close();
		}
	}
	finally {
		ClassLoader ccl = Thread.currentThread().getContextClassLoader();
		if (ccl == ContextLoader.class.getClassLoader()) {
			currentContext = null;
		}
		else if (ccl != null) {
			currentContextPerThread.remove(ccl);
		}
		servletContext.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
	}
}
 
源代码5 项目: java-technology-stack   文件: WebUtils.java
/**
 * Set a system property to the web application root directory.
 * The key of the system property can be defined with the "webAppRootKey"
 * context-param in {@code web.xml}. Default is "webapp.root".
 * <p>Can be used for tools that support substitution with {@code System.getProperty}
 * values, like log4j's "${key}" syntax within log file locations.
 * @param servletContext the servlet context of the web application
 * @throws IllegalStateException if the system property is already set,
 * or if the WAR file is not expanded
 * @see #WEB_APP_ROOT_KEY_PARAM
 * @see #DEFAULT_WEB_APP_ROOT_KEY
 * @see WebAppRootListener
 */
public static void setWebAppRootSystemProperty(ServletContext servletContext) throws IllegalStateException {
	Assert.notNull(servletContext, "ServletContext must not be null");
	String root = servletContext.getRealPath("/");
	if (root == null) {
		throw new IllegalStateException(
				"Cannot set web app root system property when WAR file is not expanded");
	}
	String param = servletContext.getInitParameter(WEB_APP_ROOT_KEY_PARAM);
	String key = (param != null ? param : DEFAULT_WEB_APP_ROOT_KEY);
	String oldValue = System.getProperty(key);
	if (oldValue != null && !StringUtils.pathEquals(oldValue, root)) {
		throw new IllegalStateException("Web app root system property already set to different value: '" +
				key + "' = [" + oldValue + "] instead of [" + root + "] - " +
				"Choose unique values for the 'webAppRootKey' context-param in your web.xml files!");
	}
	System.setProperty(key, root);
	servletContext.log("Set web app root system property: '" + key + "' = [" + root + "]");
}
 
源代码6 项目: birt   文件: ChartImageManager.java
/**
 * Deletes all files and sub-directories under directories. Returns true if
 * all deletions were successful. If a deletion fails, the method stops
 * attempting to delete and returns false.
 */

private static boolean deleteDir( File dir, ServletContext context )
{
	if ( dir.isDirectory( ) )
	{
		String[] children = dir.list( );
		for ( int i = 0; i < children.length; i++ )
		{
			boolean success = deleteDir( new File( dir, children[i] ),
					context );
			if ( !success )
			{
				return false;
			}
		}
	}
	// The directory is now empty so delete it
	context.log( "Cleaned file: " + dir.getPath( ) ); //$NON-NLS-1$
	return dir.delete( );
}
 
源代码7 项目: spring4-understanding   文件: WebUtils.java
/**
 * Set a system property to the web application root directory.
 * The key of the system property can be defined with the "webAppRootKey"
 * context-param in {@code web.xml}. Default is "webapp.root".
 * <p>Can be used for tools that support substitution with {@code System.getProperty}
 * values, like log4j's "${key}" syntax within log file locations.
 * @param servletContext the servlet context of the web application
 * @throws IllegalStateException if the system property is already set,
 * or if the WAR file is not expanded
 * @see #WEB_APP_ROOT_KEY_PARAM
 * @see #DEFAULT_WEB_APP_ROOT_KEY
 * @see WebAppRootListener
 * @see Log4jWebConfigurer
 */
public static void setWebAppRootSystemProperty(ServletContext servletContext) throws IllegalStateException {
	Assert.notNull(servletContext, "ServletContext must not be null");
	String root = servletContext.getRealPath("/");
	if (root == null) {
		throw new IllegalStateException(
			"Cannot set web app root system property when WAR file is not expanded");
	}
	String param = servletContext.getInitParameter(WEB_APP_ROOT_KEY_PARAM);
	String key = (param != null ? param : DEFAULT_WEB_APP_ROOT_KEY);
	String oldValue = System.getProperty(key);
	if (oldValue != null && !StringUtils.pathEquals(oldValue, root)) {
		throw new IllegalStateException(
			"Web app root system property already set to different value: '" +
			key + "' = [" + oldValue + "] instead of [" + root + "] - " +
			"Choose unique values for the 'webAppRootKey' context-param in your web.xml files!");
	}
	System.setProperty(key, root);
	servletContext.log("Set web app root system property: '" + key + "' = [" + root + "]");
}
 
源代码8 项目: lams   文件: ContextLoader.java
/**
 * Close Spring's web application context for the given servlet context. If
 * the default {@link #loadParentContext(ServletContext)} implementation,
 * which uses ContextSingletonBeanFactoryLocator, has loaded any shared
 * parent context, release one reference to that shared parent context.
 * <p>If overriding {@link #loadParentContext(ServletContext)}, you may have
 * to override this method as well.
 * @param servletContext the ServletContext that the WebApplicationContext runs in
 */
public void closeWebApplicationContext(ServletContext servletContext) {
	servletContext.log("Closing Spring root WebApplicationContext");
	try {
		if (this.context instanceof ConfigurableWebApplicationContext) {
			((ConfigurableWebApplicationContext) this.context).close();
		}
	}
	finally {
		ClassLoader ccl = Thread.currentThread().getContextClassLoader();
		if (ccl == ContextLoader.class.getClassLoader()) {
			currentContext = null;
		}
		else if (ccl != null) {
			currentContextPerThread.remove(ccl);
		}
		servletContext.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
		if (this.parentContextRef != null) {
			this.parentContextRef.release();
		}
	}
}
 
源代码9 项目: lams   文件: WebUtils.java
/**
 * Set a system property to the web application root directory.
 * The key of the system property can be defined with the "webAppRootKey"
 * context-param in {@code web.xml}. Default is "webapp.root".
 * <p>Can be used for tools that support substitution with {@code System.getProperty}
 * values, like log4j's "${key}" syntax within log file locations.
 * @param servletContext the servlet context of the web application
 * @throws IllegalStateException if the system property is already set,
 * or if the WAR file is not expanded
 * @see #WEB_APP_ROOT_KEY_PARAM
 * @see #DEFAULT_WEB_APP_ROOT_KEY
 * @see WebAppRootListener
 * @see Log4jWebConfigurer
 */
public static void setWebAppRootSystemProperty(ServletContext servletContext) throws IllegalStateException {
	Assert.notNull(servletContext, "ServletContext must not be null");
	String root = servletContext.getRealPath("/");
	if (root == null) {
		throw new IllegalStateException(
				"Cannot set web app root system property when WAR file is not expanded");
	}
	String param = servletContext.getInitParameter(WEB_APP_ROOT_KEY_PARAM);
	String key = (param != null ? param : DEFAULT_WEB_APP_ROOT_KEY);
	String oldValue = System.getProperty(key);
	if (oldValue != null && !StringUtils.pathEquals(oldValue, root)) {
		throw new IllegalStateException("Web app root system property already set to different value: '" +
				key + "' = [" + oldValue + "] instead of [" + root + "] - " +
				"Choose unique values for the 'webAppRootKey' context-param in your web.xml files!");
	}
	System.setProperty(key, root);
	servletContext.log("Set web app root system property: '" + key + "' = [" + root + "]");
}
 
源代码10 项目: knox   文件: GatewayForwardingServletTest.java
@Test
public void testRedirectDefaults() throws ServletException, IOException {
  IMocksControl mockControl = EasyMock.createControl();
  ServletConfig config = mockControl.createMock(ServletConfig.class);
  ServletContext context = mockControl.createMock(ServletContext.class);
  HttpServletRequest request = mockControl.createMock(HttpServletRequest.class);
  HttpServletResponse response = mockControl.createMock(HttpServletResponse.class);
  RequestDispatcher dispatcher = mockControl.createMock(RequestDispatcher.class);
  // setup expectations
  EasyMock.expect(config.getServletName()).andStubReturn("default");
  EasyMock.expect(config.getServletContext()).andStubReturn(context);
  EasyMock.expect(config.getInitParameter("redirectTo")).andReturn("/gateway/sandbox");
  EasyMock.expect(request.getMethod()).andReturn("GET").anyTimes();
  EasyMock.expect(request.getPathInfo()).andReturn("/webhdfs/v1/tmp").anyTimes();
  EasyMock.expect(request.getQueryString()).andReturn("op=LISTSTATUS");
  EasyMock.expect(response.getStatus()).andReturn(200).anyTimes();
  EasyMock.expect(context.getContext("/gateway/sandbox")).andReturn(context);
  EasyMock.expect(context.getRequestDispatcher("/webhdfs/v1/tmp?op=LISTSTATUS")).andReturn(dispatcher);
  dispatcher.forward(request, response);
  EasyMock.expectLastCall().once();
  // logging
  context.log(EasyMock.anyObject());
  EasyMock.expectLastCall().anyTimes();
  // run the test
  mockControl.replay();
  GatewayForwardingServlet servlet = new GatewayForwardingServlet();
  servlet.init(config);
  servlet.service(request, response);
  mockControl.verify();
}
 
源代码11 项目: iaf   文件: IbisApplicationInitializer.java
@Override
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
	WebApplicationContext wac = super.initWebApplicationContext(servletContext);
	SpringBus bus = (SpringBus) wac.getBean("cxf");
	servletContext.log("Successfully started IBIS WebApplicationInitializer with SpringBus ["+bus.getId()+"]");
	return wac;
}
 
源代码12 项目: spring4-understanding   文件: Log4jWebConfigurer.java
/**
 * Shut down log4j, properly releasing all file locks
 * and resetting the web app root system property.
 * @param servletContext the current ServletContext
 * @see WebUtils#removeWebAppRootSystemProperty
 */
public static void shutdownLogging(ServletContext servletContext) {
	servletContext.log("Shutting down log4j");
	try {
		org.springframework.util.Log4jConfigurer.shutdownLogging();
	}
	finally {
		// Remove the web app root system property.
		if (exposeWebAppRoot(servletContext)) {
			WebUtils.removeWebAppRootSystemProperty(servletContext);
		}
	}
}
 
public void init(final ServletConfig config) {
    try {
        this.delegate.init(config);

    } catch (final Throwable t) {
        // let the service method know initialization failed.
        this.initSuccess = false;

        /*
         * no matter what went wrong, our role is to capture this error and
         * prevent it from blocking initialization of the servlet. logging
         * overkill so that our deployer will find a record of this problem
         * even if unfamiliar with Commons Logging and properly configuring
         * it.
         */

        final String message = "SafeDispatcherServlet: \n"
            + "The Spring DispatcherServlet we wrap threw on init.\n"
            + "But for our having caught this error, the servlet would not have initialized.";

        // logger it via Commons Logging
        LOGGER.error(message, t);

        // logger it to the ServletContext
        ServletContext context = config.getServletContext();
        context.log(message, t);

        /*
         * record the error so that the application has access to later
         * display a proper error message based on the exception.
         */
        context.setAttribute(CAUGHT_THROWABLE_KEY, t);

    }
}
 
源代码14 项目: ats-framework   文件: AgentWsContextListener.java
@Override
public void contextInitialized( ServletContextEvent servletEvent ) {

    ServletContext servletContext = servletEvent.getServletContext();
    servletContext.log("Servlet context initialized event is received. Starting registering configurators");
    try {
        new ClasspathUtils().logProblematicJars();
    } catch (RuntimeException e) {
        log.warn("Error caught while trying to get all JARs in classpath", e);
        // do not rethrow exception as this will stop deployment on incompliant servers like JBoss
    }

    // create the default web service configurator
    String pathToConfigFile = servletContext.getRealPath("/WEB-INF");
    AgentConfigurator defaultConfigurator = new AgentConfigurator(pathToConfigFile);
    TemplateActionsConfigurator templateActionsConfigurator = new TemplateActionsConfigurator(pathToConfigFile);
    List<Configurator> configurators = new ArrayList<Configurator>();
    configurators.add(defaultConfigurator);
    configurators.add(templateActionsConfigurator);

    log.info("Initializing ATS Agent web service, start component registration");

    try {
        MainComponentLoader.getInstance().initialize(configurators);
    } catch (AgentException ae) {
        throw new RuntimeException("Unable to initialize Agent component loader", ae);
    }
}
 
源代码15 项目: lams   文件: SpringServletContainerInitializer.java
/**
 * Delegate the {@code ServletContext} to any {@link WebApplicationInitializer}
 * implementations present on the application classpath.
 * <p>Because this class declares @{@code HandlesTypes(WebApplicationInitializer.class)},
 * Servlet 3.0+ containers will automatically scan the classpath for implementations
 * of Spring's {@code WebApplicationInitializer} interface and provide the set of all
 * such types to the {@code webAppInitializerClasses} parameter of this method.
 * <p>If no {@code WebApplicationInitializer} implementations are found on the classpath,
 * this method is effectively a no-op. An INFO-level log message will be issued notifying
 * the user that the {@code ServletContainerInitializer} has indeed been invoked but that
 * no {@code WebApplicationInitializer} implementations were found.
 * <p>Assuming that one or more {@code WebApplicationInitializer} types are detected,
 * they will be instantiated (and <em>sorted</em> if the @{@link
 * org.springframework.core.annotation.Order @Order} annotation is present or
 * the {@link org.springframework.core.Ordered Ordered} interface has been
 * implemented). Then the {@link WebApplicationInitializer#onStartup(ServletContext)}
 * method will be invoked on each instance, delegating the {@code ServletContext} such
 * that each instance may register and configure servlets such as Spring's
 * {@code DispatcherServlet}, listeners such as Spring's {@code ContextLoaderListener},
 * or any other Servlet API componentry such as filters.
 * @param webAppInitializerClasses all implementations of
 * {@link WebApplicationInitializer} found on the application classpath
 * @param servletContext the servlet context to be initialized
 * @see WebApplicationInitializer#onStartup(ServletContext)
 * @see AnnotationAwareOrderComparator
 */
@Override
public void onStartup(Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)
		throws ServletException {

	List<WebApplicationInitializer> initializers = new LinkedList<WebApplicationInitializer>();

	if (webAppInitializerClasses != null) {
		for (Class<?> waiClass : webAppInitializerClasses) {
			// Be defensive: Some servlet containers provide us with invalid classes,
			// no matter what @HandlesTypes says...
			if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&
					WebApplicationInitializer.class.isAssignableFrom(waiClass)) {
				try {
					initializers.add((WebApplicationInitializer) waiClass.newInstance());
				}
				catch (Throwable ex) {
					throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);
				}
			}
		}
	}

	if (initializers.isEmpty()) {
		servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
		return;
	}

	servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");
	AnnotationAwareOrderComparator.sort(initializers);
	for (WebApplicationInitializer initializer : initializers) {
		initializer.onStartup(servletContext);
	}
}
 
源代码16 项目: lams   文件: Log4jWebConfigurer.java
/**
 * Shut down log4j, properly releasing all file locks
 * and resetting the web app root system property.
 * @param servletContext the current ServletContext
 * @see WebUtils#removeWebAppRootSystemProperty
 */
public static void shutdownLogging(ServletContext servletContext) {
	servletContext.log("Shutting down log4j");
	try {
		org.springframework.util.Log4jConfigurer.shutdownLogging();
	}
	finally {
		// Remove the web app root system property.
		if (exposeWebAppRoot(servletContext)) {
			WebUtils.removeWebAppRootSystemProperty(servletContext);
		}
	}
}
 
源代码17 项目: lams   文件: CsrfGuardServletContextListener.java
/**
 * Prints the configuration to the ServletContext log file with the given prefix.
 * Has no effect unless the CONFIG_PRINT_PARAM init parameter is "true."
 * @param context The ServletContext
 * @param prefix  The string used as a prefix when printing the configuration to the log
 * @see javax.servlet.ServletContext#log(String)
 */
public static void printConfigIfConfigured(ServletContext context, String prefix) {
	String printConfig = context.getInitParameter(CONFIG_PRINT_PARAM);

	if (printConfig == null || "".equals(printConfig.trim())) {
		printConfig = CsrfGuard.getInstance().isPrintConfig() ? "true" : null;
	}
	
	if (printConfig != null && Boolean.parseBoolean(printConfig)) {
		context.log(prefix 
				+ CsrfGuard.getInstance().toString());
	}
}
 
/**
 * Delegate the {@code ServletContext} to any {@link WebApplicationInitializer}
 * implementations present on the application classpath.
 *
 * <p>Because this class declares @{@code HandlesTypes(WebApplicationInitializer.class)},
 * Servlet 3.0+ containers will automatically scan the classpath for implementations
 * of Spring's {@code WebApplicationInitializer} interface and provide the set of all
 * such types to the {@code webAppInitializerClasses} parameter of this method.
 *
 * <p>If no {@code WebApplicationInitializer} implementations are found on the
 * classpath, this method is effectively a no-op. An INFO-level log message will be
 * issued notifying the user that the {@code ServletContainerInitializer} has indeed
 * been invoked but that no {@code WebApplicationInitializer} implementations were
 * found.
 *
 * <p>Assuming that one or more {@code WebApplicationInitializer} types are detected,
 * they will be instantiated (and <em>sorted</em> if the @{@link
 * org.springframework.core.annotation.Order @Order} annotation is present or
 * the {@link org.springframework.core.Ordered Ordered} interface has been
 * implemented). Then the {@link WebApplicationInitializer#onStartup(ServletContext)}
 * method will be invoked on each instance, delegating the {@code ServletContext} such
 * that each instance may register and configure servlets such as Spring's
 * {@code DispatcherServlet}, listeners such as Spring's {@code ContextLoaderListener},
 * or any other Servlet API componentry such as filters.
 *
 * @param webAppInitializerClasses all implementations of
 * {@link WebApplicationInitializer} found on the application classpath
 * @param servletContext the servlet context to be initialized
 * @see WebApplicationInitializer#onStartup(ServletContext)
 * @see AnnotationAwareOrderComparator
 */
@Override
public void onStartup(Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)
		throws ServletException {

	List<WebApplicationInitializer> initializers = new LinkedList<WebApplicationInitializer>();

	if (webAppInitializerClasses != null) {
		for (Class<?> waiClass : webAppInitializerClasses) {
			// Be defensive: Some servlet containers provide us with invalid classes,
			// no matter what @HandlesTypes says...
			if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&
					WebApplicationInitializer.class.isAssignableFrom(waiClass)) {
				try {
					initializers.add((WebApplicationInitializer) waiClass.newInstance());
				}
				catch (Throwable ex) {
					throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);
				}
			}
		}
	}

	if (initializers.isEmpty()) {
		servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
		return;
	}

	AnnotationAwareOrderComparator.sort(initializers);
	servletContext.log("Spring WebApplicationInitializers detected on classpath: " + initializers);

	for (WebApplicationInitializer initializer : initializers) {
		initializer.onStartup(servletContext);
	}
}
 
源代码19 项目: lams   文件: ContextLoader.java
/**
 * Initialize Spring's web application context for the given servlet context,
 * using the application context provided at construction time, or creating a new one
 * according to the "{@link #CONTEXT_CLASS_PARAM contextClass}" and
 * "{@link #CONFIG_LOCATION_PARAM contextConfigLocation}" context-params.
 * @param servletContext current servlet context
 * @return the new WebApplicationContext
 * @see #ContextLoader(WebApplicationContext)
 * @see #CONTEXT_CLASS_PARAM
 * @see #CONFIG_LOCATION_PARAM
 */
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
	if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
		throw new IllegalStateException(
				"Cannot initialize context because there is already a root application context present - " +
				"check whether you have multiple ContextLoader* definitions in your web.xml!");
	}

	Log logger = LogFactory.getLog(ContextLoader.class);
	servletContext.log("Initializing Spring root WebApplicationContext");
	if (logger.isInfoEnabled()) {
		logger.info("Root WebApplicationContext: initialization started");
	}
	long startTime = System.currentTimeMillis();

	try {
		// Store context in local instance variable, to guarantee that
		// it is available on ServletContext shutdown.
		if (this.context == null) {
			this.context = createWebApplicationContext(servletContext);
		}
		if (this.context instanceof ConfigurableWebApplicationContext) {
			ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
			if (!cwac.isActive()) {
				// The context has not yet been refreshed -> provide services such as
				// setting the parent context, setting the application context id, etc
				if (cwac.getParent() == null) {
					// The context instance was injected without an explicit parent ->
					// determine parent for root web application context, if any.
					ApplicationContext parent = loadParentContext(servletContext);
					cwac.setParent(parent);
				}
				configureAndRefreshWebApplicationContext(cwac, servletContext);
			}
		}
		servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

		ClassLoader ccl = Thread.currentThread().getContextClassLoader();
		if (ccl == ContextLoader.class.getClassLoader()) {
			currentContext = this.context;
		}
		else if (ccl != null) {
			currentContextPerThread.put(ccl, this.context);
		}

		if (logger.isDebugEnabled()) {
			logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
					WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
		}
		if (logger.isInfoEnabled()) {
			long elapsedTime = System.currentTimeMillis() - startTime;
			logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
		}

		return this.context;
	}
	catch (RuntimeException ex) {
		logger.error("Context initialization failed", ex);
		servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
		throw ex;
	}
	catch (Error err) {
		logger.error("Context initialization failed", err);
		servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
		throw err;
	}
}
 
源代码20 项目: spring4-understanding   文件: ContextLoader.java
/**
 * Initialize Spring's web application context for the given servlet context,
 * using the application context provided at construction time, or creating a new one
 * according to the "{@link #CONTEXT_CLASS_PARAM contextClass}" and
 * "{@link #CONFIG_LOCATION_PARAM contextConfigLocation}" context-params.
 * @param servletContext current servlet context
 * @return the new WebApplicationContext
 * @see #ContextLoader(WebApplicationContext)
 * @see #CONTEXT_CLASS_PARAM
 * @see #CONFIG_LOCATION_PARAM
 */
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
	if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
		throw new IllegalStateException(
				"Cannot initialize context because there is already a root application context present - " +
				"check whether you have multiple ContextLoader* definitions in your web.xml!");
	}

	Log logger = LogFactory.getLog(ContextLoader.class);
	servletContext.log("Initializing Spring root WebApplicationContext");
	if (logger.isInfoEnabled()) {
		logger.info("Root WebApplicationContext: initialization started");
	}
	long startTime = System.currentTimeMillis();

	try {
		// Store context in local instance variable, to guarantee that
		// it is available on ServletContext shutdown.
		if (this.context == null) {
			this.context = createWebApplicationContext(servletContext);
		}
		if (this.context instanceof ConfigurableWebApplicationContext) {
			ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
			if (!cwac.isActive()) {
				// The context has not yet been refreshed -> provide services such as
				// setting the parent context, setting the application context id, etc
				if (cwac.getParent() == null) {
					// The context instance was injected without an explicit parent ->
					// determine parent for root web application context, if any.
					ApplicationContext parent = loadParentContext(servletContext);
					cwac.setParent(parent);
				}
				configureAndRefreshWebApplicationContext(cwac, servletContext);
			}
		}
		servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

		ClassLoader ccl = Thread.currentThread().getContextClassLoader();
		if (ccl == ContextLoader.class.getClassLoader()) {
			currentContext = this.context;
		}
		else if (ccl != null) {
			currentContextPerThread.put(ccl, this.context);
		}

		if (logger.isDebugEnabled()) {
			logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
					WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
		}
		if (logger.isInfoEnabled()) {
			long elapsedTime = System.currentTimeMillis() - startTime;
			logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
		}

		return this.context;
	}
	catch (RuntimeException ex) {
		logger.error("Context initialization failed", ex);
		servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
		throw ex;
	}
	catch (Error err) {
		logger.error("Context initialization failed", err);
		servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
		throw err;
	}
}