1 16 17 package org.springframework.web.servlet.handler; 18 19 import java.util.Collections ; 20 import java.util.Enumeration ; 21 22 import javax.servlet.Servlet ; 23 import javax.servlet.ServletConfig ; 24 import javax.servlet.ServletContext ; 25 import javax.servlet.ServletException ; 26 27 import org.springframework.beans.BeansException; 28 import org.springframework.beans.factory.BeanInitializationException; 29 import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor; 30 import org.springframework.web.context.ServletConfigAware; 31 import org.springframework.web.context.ServletContextAware; 32 33 67 public class SimpleServletPostProcessor implements 68 DestructionAwareBeanPostProcessor, ServletContextAware, ServletConfigAware { 69 70 private boolean useSharedServletConfig = true; 71 72 private ServletContext servletContext; 73 74 private ServletConfig servletConfig; 75 76 77 85 public void setUseSharedServletConfig(boolean useSharedServletConfig) { 86 this.useSharedServletConfig = useSharedServletConfig; 87 } 88 89 public void setServletContext(ServletContext servletContext) { 90 this.servletContext = servletContext; 91 } 92 93 public void setServletConfig(ServletConfig servletConfig) { 94 this.servletConfig = servletConfig; 95 } 96 97 98 public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { 99 return bean; 100 } 101 102 public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { 103 if (bean instanceof Servlet ) { 104 ServletConfig config = this.servletConfig; 105 if (config == null || !this.useSharedServletConfig) { 106 config = new DelegatingServletConfig(beanName, this.servletContext); 107 } 108 try { 109 ((Servlet ) bean).init(config); 110 } 111 catch (ServletException ex) { 112 throw new BeanInitializationException("Servlet.init threw exception", ex); 113 } 114 } 115 return bean; 116 } 117 118 public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException { 119 if (bean instanceof Servlet ) { 120 ((Servlet ) bean).destroy(); 121 } 122 } 123 124 125 129 private static class DelegatingServletConfig implements ServletConfig { 130 131 private final String servletName; 132 133 private final ServletContext servletContext; 134 135 public DelegatingServletConfig(String servletName, ServletContext servletContext) { 136 this.servletName = servletName; 137 this.servletContext = servletContext; 138 } 139 140 public String getServletName() { 141 return servletName; 142 } 143 144 public ServletContext getServletContext() { 145 return servletContext; 146 } 147 148 public String getInitParameter(String paramName) { 149 return null; 150 } 151 152 public Enumeration getInitParameterNames() { 153 return Collections.enumeration(Collections.EMPTY_SET); 154 } 155 } 156 157 } 158 | Popular Tags |