KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > web > servlet > HttpServletBean


1 /*
2  * Copyright 2002-2007 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
17 package org.springframework.web.servlet;
18
19 import java.util.Enumeration JavaDoc;
20 import java.util.HashSet JavaDoc;
21 import java.util.Set JavaDoc;
22
23 import javax.servlet.ServletConfig JavaDoc;
24 import javax.servlet.ServletContext JavaDoc;
25 import javax.servlet.ServletException JavaDoc;
26 import javax.servlet.http.HttpServlet JavaDoc;
27
28 import org.apache.commons.logging.Log;
29 import org.apache.commons.logging.LogFactory;
30
31 import org.springframework.beans.BeanWrapper;
32 import org.springframework.beans.BeanWrapperImpl;
33 import org.springframework.beans.BeansException;
34 import org.springframework.beans.MutablePropertyValues;
35 import org.springframework.beans.PropertyValue;
36 import org.springframework.beans.PropertyValues;
37 import org.springframework.core.io.Resource;
38 import org.springframework.core.io.ResourceEditor;
39 import org.springframework.core.io.ResourceLoader;
40 import org.springframework.util.StringUtils;
41 import org.springframework.web.context.support.ServletContextResourceLoader;
42
43 /**
44  * Simple extension of {@link javax.servlet.http.HttpServlet} which treats
45  * its config parameters as bean properties.
46  *
47  * <p>A very handy superclass for any type of servlet. Type conversion is automatic.
48  * It is also possible for subclasses to specify required properties.
49  *
50  * <p>This servlet leaves request handling to subclasses, inheriting the default
51  * behavior of HttpServlet (<code>doGet</code>, <code>doPost</code>, etc).
52  *
53  * <p>This servlet superclass has no dependency on a Spring application context,
54  * in contrast to the {@link FrameworkServlet} class which loads its own context.
55  *
56  * @author Rod Johnson
57  * @author Juergen Hoeller
58  * @see #addRequiredProperty
59  * @see #initServletBean
60  * @see #doGet
61  * @see #doPost
62  * @see FrameworkServlet
63  */

64 public abstract class HttpServletBean extends HttpServlet JavaDoc {
65
66     /** Logger available to subclasses */
67     protected final Log logger = LogFactory.getLog(getClass());
68
69     /**
70      * Set of required properties (Strings) that must be supplied as
71      * config parameters to this servlet.
72      */

73     private final Set JavaDoc requiredProperties = new HashSet JavaDoc();
74
75
76     /**
77      * Subclasses can invoke this method to specify that this property
78      * (which must match a JavaBean property they expose) is mandatory,
79      * and must be supplied as a config parameter. This should be called
80      * from the constructor of a subclass.
81      * <p>This method is only relevant in case of traditional initialization
82      * driven by a ServletConfig instance.
83      * @param property name of the required property
84      */

85     protected final void addRequiredProperty(String JavaDoc property) {
86         this.requiredProperties.add(property);
87     }
88
89     /**
90      * Map config parameters onto bean properties of this servlet, and
91      * invoke subclass initialization.
92      * @throws ServletException if bean properties are invalid (or required
93      * properties are missing), or if subclass initialization fails.
94      */

95     public final void init() throws ServletException JavaDoc {
96         if (logger.isDebugEnabled()) {
97             logger.debug("Initializing servlet '" + getServletName() + "'");
98         }
99
100         // Set bean properties from init parameters.
101
try {
102             PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
103             BeanWrapper bw = new BeanWrapperImpl(this);
104             ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
105             bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader));
106             initBeanWrapper(bw);
107             bw.setPropertyValues(pvs, true);
108         }
109         catch (BeansException ex) {
110             logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
111             throw ex;
112         }
113
114         // Let subclasses do whatever initialization they like.
115
initServletBean();
116
117         if (logger.isDebugEnabled()) {
118             logger.debug("Servlet '" + getServletName() + "' configured successfully");
119         }
120     }
121
122     /**
123      * Initialize the BeanWrapper for this HttpServletBean,
124      * possibly with custom editors.
125      * <p>This default implementation is empty.
126      * @param bw the BeanWrapper to initialize
127      * @throws BeansException if thrown by BeanWrapper methods
128      * @see org.springframework.beans.BeanWrapper#registerCustomEditor
129      */

130     protected void initBeanWrapper(BeanWrapper bw) throws BeansException {
131     }
132
133
134     /**
135      * Overridden method that simply returns <code>null</code> when no
136      * ServletConfig set yet.
137      * @see #getServletConfig()
138      */

139     public final String JavaDoc getServletName() {
140         return (getServletConfig() != null ? getServletConfig().getServletName() : null);
141     }
142
143     /**
144      * Overridden method that simply returns <code>null</code> when no
145      * ServletConfig set yet.
146      * @see #getServletConfig()
147      */

148     public final ServletContext JavaDoc getServletContext() {
149         return (getServletConfig() != null ? getServletConfig().getServletContext() : null);
150     }
151
152
153     /**
154      * Subclasses may override this to perform custom initialization.
155      * All bean properties of this servlet will have been set before this
156      * method is invoked.
157      * <p>This default implementation is empty.
158      * @throws ServletException if subclass initialization fails
159      */

160     protected void initServletBean() throws ServletException JavaDoc {
161     }
162
163
164     /**
165      * PropertyValues implementation created from ServletConfig init parameters.
166      */

167     private static class ServletConfigPropertyValues extends MutablePropertyValues {
168
169         /**
170          * Create new ServletConfigPropertyValues.
171          * @param config ServletConfig we'll use to take PropertyValues from
172          * @param requiredProperties set of property names we need, where
173          * we can't accept default values
174          * @throws ServletException if any required properties are missing
175          */

176         public ServletConfigPropertyValues(ServletConfig JavaDoc config, Set JavaDoc requiredProperties)
177             throws ServletException JavaDoc {
178             
179             Set JavaDoc missingProps = (requiredProperties != null && !requiredProperties.isEmpty()) ?
180                     new HashSet JavaDoc(requiredProperties) : null;
181
182             Enumeration JavaDoc en = config.getInitParameterNames();
183             while (en.hasMoreElements()) {
184                 String JavaDoc property = (String JavaDoc) en.nextElement();
185                 Object JavaDoc value = config.getInitParameter(property);
186                 addPropertyValue(new PropertyValue(property, value));
187                 if (missingProps != null) {
188                     missingProps.remove(property);
189                 }
190             }
191
192             // Fail if we are still missing properties.
193
if (missingProps != null && missingProps.size() > 0) {
194                 throw new ServletException JavaDoc(
195                     "Initialization from ServletConfig for servlet '" + config.getServletName() +
196                     "' failed; the following required properties were missing: " +
197                     StringUtils.collectionToDelimitedString(missingProps, ", "));
198             }
199         }
200     }
201
202 }
203
Popular Tags