1. /*
  2. * Copyright 2002-2004 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.springframework.web.context.support;
  17. import java.io.File;
  18. import javax.servlet.ServletContext;
  19. import org.springframework.context.ApplicationContext;
  20. import org.springframework.context.support.ApplicationObjectSupport;
  21. import org.springframework.web.context.WebApplicationContext;
  22. import org.springframework.web.util.WebUtils;
  23. /**
  24. * Convenient superclass for application objects running in a WebApplicationContext.
  25. * Provides getWebApplicationContext, getServletContext, and getTempDir methods.
  26. * @author Juergen Hoeller
  27. * @since 28.08.2003
  28. */
  29. public abstract class WebApplicationObjectSupport extends ApplicationObjectSupport {
  30. /**
  31. * Return the current application context as WebApplicationContext.
  32. */
  33. protected final WebApplicationContext getWebApplicationContext() {
  34. ApplicationContext ctx = getApplicationContext();
  35. if (!(ctx instanceof WebApplicationContext)) {
  36. throw new IllegalStateException("WebApplicationObjectSupport instance [" + this +
  37. "] does not run in a WebApplicationContext but in: " + ctx);
  38. }
  39. return (WebApplicationContext) getApplicationContext();
  40. }
  41. /**
  42. * Return the current ServletContext.
  43. */
  44. protected final ServletContext getServletContext() {
  45. return getWebApplicationContext().getServletContext();
  46. }
  47. /**
  48. * Return the temporary directory for the current web application,
  49. * as provided by the servlet container.
  50. * @return the File representing the temporary directory
  51. */
  52. protected final File getTempDir() {
  53. return WebUtils.getTempDir(getServletContext());
  54. }
  55. }