KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > web > bind > WebDataBinder


1 /*
2  * Copyright 2002-2006 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.bind;
18
19 import java.lang.reflect.Array JavaDoc;
20 import java.util.Iterator JavaDoc;
21 import java.util.Map JavaDoc;
22
23 import org.springframework.beans.MutablePropertyValues;
24 import org.springframework.beans.PropertyValue;
25 import org.springframework.validation.DataBinder;
26 import org.springframework.web.multipart.MultipartFile;
27
28 /**
29  * Special DataBinder to perform data binding from web request parameters
30  * to JavaBeans. Designed for web environments, but not dependent on the
31  * Servlet API; serves as base class for more specific DataBinder variants,
32  * such as ServletRequestDataBinder.
33  *
34  * <p>Includes support for field markers which address a common problem with
35  * HTML checkboxes and select options: detecting that a field was part of
36  * the form, but did not generate a request parameter because it was empty.
37  * A field marker allows to detect that state and reset the corresponding
38  * bean property accordingly.
39  *
40  * @author Juergen Hoeller
41  * @since 1.2
42  * @see #registerCustomEditor
43  * @see #setAllowedFields
44  * @see #setRequiredFields
45  * @see #setFieldMarkerPrefix
46  * @see ServletRequestDataBinder
47  */

48 public class WebDataBinder extends DataBinder {
49
50     /**
51      * Default prefix that field marker parameters start with, followed by the field
52      * name: e.g. "_subscribeToNewsletter" for a field "subscribeToNewsletter".
53      * <p>Such a marker parameter indicates that the field was visible, that is,
54      * existed in the form that caused the submission. If no corresponding field
55      * value parameter was found, the field will be reset. The value of the field
56      * marker parameter does not matter in this case; an arbitrary value can be used.
57      * This is particularly useful for HTML checkboxes and select options.
58      * @see #setFieldMarkerPrefix
59      */

60     public static final String JavaDoc DEFAULT_FIELD_MARKER_PREFIX = "_";
61
62
63     private String JavaDoc fieldMarkerPrefix = DEFAULT_FIELD_MARKER_PREFIX;
64
65     private boolean bindEmptyMultipartFiles = true;
66
67
68     /**
69      * Create a new WebDataBinder instance, with default object name.
70      * @param target target object to bind onto
71      * @see #DEFAULT_OBJECT_NAME
72      */

73     public WebDataBinder(Object JavaDoc target) {
74         super(target);
75     }
76
77     /**
78      * Create a new WebDataBinder instance.
79      * @param target target object to bind onto
80      * @param objectName objectName of the target object
81      */

82     public WebDataBinder(Object JavaDoc target, String JavaDoc objectName) {
83         super(target, objectName);
84     }
85
86
87     /**
88      * Specify a prefix that can be used for parameters that mark potentially
89      * empty fields, having "prefix + field" as name. Such a marker parameter is
90      * checked by existence: You can send any value for it, for example "visible".
91      * This is particularly useful for HTML checkboxes and select options.
92      * <p>Default is "_", for "_FIELD" parameters (e.g. "_subscribeToNewsletter").
93      * Set this to null if you want to turn off the empty field check completely.
94      * <p>HTML checkboxes only send a value when they're checked, so it is not
95      * possible to detect that a formerly checked box has just been unchecked,
96      * at least not with standard HTML means.
97      * <p>One way to address this is to look for a checkbox parameter value if
98      * you know that the checkbox has been visible in the form, resetting the
99      * checkbox if no value found. In Spring web MVC, this typically happens
100      * in a custom <code>onBind</code> implementation.
101      * <p>This auto-reset mechanism addresses this deficiency, provided
102      * that a marker parameter is sent for each checkbox field, like
103      * "_subscribeToNewsletter" for a "subscribeToNewsletter" field.
104      * As the marker parameter is sent in any case, the data binder can
105      * detect an empty field and automatically reset its value.
106      * @see #DEFAULT_FIELD_MARKER_PREFIX
107      * @see org.springframework.web.servlet.mvc.BaseCommandController#onBind
108      */

109     public void setFieldMarkerPrefix(String JavaDoc fieldMarkerPrefix) {
110         this.fieldMarkerPrefix = fieldMarkerPrefix;
111     }
112
113     /**
114      * Return the prefix for parameters that mark potentially empty fields.
115      */

116     public String JavaDoc getFieldMarkerPrefix() {
117         return fieldMarkerPrefix;
118     }
119
120     /**
121      * Set whether to bind empty MultipartFile parameters. Default is "true".
122      * <p>Turn this off if you want to keep an already bound MultipartFile
123      * when the user resubmits the form without choosing a different file.
124      * Else, the already bound MultipartFile will be replaced by an empty
125      * MultipartFile holder.
126      * @see org.springframework.web.multipart.MultipartFile
127      */

128     public void setBindEmptyMultipartFiles(boolean bindEmptyMultipartFiles) {
129         this.bindEmptyMultipartFiles = bindEmptyMultipartFiles;
130     }
131
132     /**
133      * Return whether to bind empty MultipartFile parameters.
134      */

135     public boolean isBindEmptyMultipartFiles() {
136         return bindEmptyMultipartFiles;
137     }
138
139
140     /**
141      * This implementation performs a field marker check
142      * before delegating to the superclass binding process.
143      * @see #checkFieldMarkers
144      */

145     protected void doBind(MutablePropertyValues mpvs) {
146         checkFieldMarkers(mpvs);
147         super.doBind(mpvs);
148     }
149
150     /**
151      * Check the given property values for field markers,
152      * i.e. for fields that start with the field marker prefix.
153      * <p>The existence of a field marker indicates that the specified
154      * field existed in the form. If the property values do not contain
155      * a corresponding field value, the field will be considered as empty
156      * and will be reset appropriately.
157      * @param mpvs the property values to be bound (can be modified)
158      * @see #getFieldMarkerPrefix
159      * @see #getEmptyValue(String, Class)
160      */

161     protected void checkFieldMarkers(MutablePropertyValues mpvs) {
162         if (getFieldMarkerPrefix() != null) {
163             String JavaDoc fieldMarkerPrefix = getFieldMarkerPrefix();
164             PropertyValue[] pvArray = mpvs.getPropertyValues();
165             for (int i = 0; i < pvArray.length; i++) {
166                 PropertyValue pv = pvArray[i];
167                 if (pv.getName().startsWith(fieldMarkerPrefix)) {
168                     String JavaDoc field = pv.getName().substring(fieldMarkerPrefix.length());
169                     if (getPropertyAccessor().isWritableProperty(field) && !mpvs.contains(field)) {
170                         Class JavaDoc fieldType = getPropertyAccessor().getPropertyType(field);
171                         mpvs.addPropertyValue(field, getEmptyValue(field, fieldType));
172                     }
173                     mpvs.removePropertyValue(pv);
174                 }
175             }
176         }
177     }
178
179     /**
180      * Determine an empty value for the specified field.
181      * <p>Default implementation returns <code>Boolean.FALSE</code>
182      * for boolean fields and an empty array of array types.
183      * Else, <code>null</code> is used as default.
184      * @param field the name of the field
185      * @param fieldType the type of the field
186      * @return the empty value (for most fields: null)
187      */

188     protected Object JavaDoc getEmptyValue(String JavaDoc field, Class JavaDoc fieldType) {
189         if (fieldType != null && boolean.class.equals(fieldType) || Boolean JavaDoc.class.equals(fieldType)) {
190             // Special handling of boolean property.
191
return Boolean.FALSE;
192         }
193         else if (fieldType != null && fieldType.isArray()) {
194             // Special handling of array property.
195
return Array.newInstance(fieldType.getComponentType(), 0);
196         }
197         else {
198             // Default value: try null.
199
return null;
200         }
201     }
202
203
204     /**
205      * Bind the multipart files contained in the given request, if any
206      * (in case of a multipart request).
207      * <p>Multipart files will only be added to the property values if they
208      * are not empty or if we're configured to bind empty multipart files too.
209      * @param multipartFiles Map of field name String to MultipartFile object
210      * @param mpvs the property values to be bound (can be modified)
211      * @see org.springframework.web.multipart.MultipartFile
212      * @see #setBindEmptyMultipartFiles
213      */

214     protected void bindMultipartFiles(Map JavaDoc multipartFiles, MutablePropertyValues mpvs) {
215         for (Iterator JavaDoc it = multipartFiles.entrySet().iterator(); it.hasNext();) {
216             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) it.next();
217             String JavaDoc key = (String JavaDoc) entry.getKey();
218             MultipartFile value = (MultipartFile) entry.getValue();
219             if (isBindEmptyMultipartFiles() || !value.isEmpty()) {
220                 mpvs.addPropertyValue(key, value);
221             }
222         }
223     }
224
225 }
226
Popular Tags