1 16 17 package org.springframework.web.bind; 18 19 import java.lang.reflect.Array ; 20 import java.util.Iterator ; 21 import java.util.Map ; 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 48 public class WebDataBinder extends DataBinder { 49 50 60 public static final String DEFAULT_FIELD_MARKER_PREFIX = "_"; 61 62 63 private String fieldMarkerPrefix = DEFAULT_FIELD_MARKER_PREFIX; 64 65 private boolean bindEmptyMultipartFiles = true; 66 67 68 73 public WebDataBinder(Object target) { 74 super(target); 75 } 76 77 82 public WebDataBinder(Object target, String objectName) { 83 super(target, objectName); 84 } 85 86 87 109 public void setFieldMarkerPrefix(String fieldMarkerPrefix) { 110 this.fieldMarkerPrefix = fieldMarkerPrefix; 111 } 112 113 116 public String getFieldMarkerPrefix() { 117 return fieldMarkerPrefix; 118 } 119 120 128 public void setBindEmptyMultipartFiles(boolean bindEmptyMultipartFiles) { 129 this.bindEmptyMultipartFiles = bindEmptyMultipartFiles; 130 } 131 132 135 public boolean isBindEmptyMultipartFiles() { 136 return bindEmptyMultipartFiles; 137 } 138 139 140 145 protected void doBind(MutablePropertyValues mpvs) { 146 checkFieldMarkers(mpvs); 147 super.doBind(mpvs); 148 } 149 150 161 protected void checkFieldMarkers(MutablePropertyValues mpvs) { 162 if (getFieldMarkerPrefix() != null) { 163 String 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 field = pv.getName().substring(fieldMarkerPrefix.length()); 169 if (getPropertyAccessor().isWritableProperty(field) && !mpvs.contains(field)) { 170 Class fieldType = getPropertyAccessor().getPropertyType(field); 171 mpvs.addPropertyValue(field, getEmptyValue(field, fieldType)); 172 } 173 mpvs.removePropertyValue(pv); 174 } 175 } 176 } 177 } 178 179 188 protected Object getEmptyValue(String field, Class fieldType) { 189 if (fieldType != null && boolean.class.equals(fieldType) || Boolean .class.equals(fieldType)) { 190 return Boolean.FALSE; 192 } 193 else if (fieldType != null && fieldType.isArray()) { 194 return Array.newInstance(fieldType.getComponentType(), 0); 196 } 197 else { 198 return null; 200 } 201 } 202 203 204 214 protected void bindMultipartFiles(Map multipartFiles, MutablePropertyValues mpvs) { 215 for (Iterator it = multipartFiles.entrySet().iterator(); it.hasNext();) { 216 Map.Entry entry = (Map.Entry ) it.next(); 217 String key = (String ) 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 |