/
FormModelMethodArgumentResolver.java
586 lines (488 loc) · 23.6 KB
/
FormModelMethodArgumentResolver.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
package com.sishuok.es.common.web.bind.method.annotation;
import com.sishuok.es.common.web.bind.annotation.FormModel;
import com.sishuok.es.common.web.bind.util.MapWapper;
import org.springframework.beans.BeanUtils;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.mock.web.MockMultipartHttpServletRequest;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.DataBinder;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.ServletRequestParameterPropertyValues;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.util.WebUtils;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <p>用于绑定@FormModel的方法参数解析器
* <p>User: Zhang Kaitao
* <p>Date: 13-1-12 下午5:01
* <p>Version: 1.0
*
* @since 3.1
*/
public class FormModelMethodArgumentResolver extends BaseMethodArgumentResolver {
/**
* 提取索引的模式 如[0].
*/
private final Pattern INDEX_PATTERN = Pattern.compile("\\[(\\d+)\\]\\.?");
private int autoGrowCollectionLimit = Integer.MAX_VALUE;
public FormModelMethodArgumentResolver() {
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
if (parameter.hasParameterAnnotation(FormModel.class)) {
return true;
}
return false;
}
/**
* Resolve the argument from the model or if not found instantiate it with
* its default if it is available. The model attribute is then populated
* with request values via data binding and optionally validated
* if {@code @java.validation.Valid} is present on the argument.
*
* @throws org.springframework.validation.BindException
* if data binding and validation result in an error
* and the next method parameter is not of type {@link org.springframework.validation.Errors}.
* @throws Exception if WebDataBinder initialization fails.
*/
public final Object resolveArgument(MethodParameter parameter,
ModelAndViewContainer mavContainer,
NativeWebRequest request,
WebDataBinderFactory binderFactory) throws Exception {
String name = parameter.getParameterAnnotation(FormModel.class).value();
Object target = (mavContainer.containsAttribute(name)) ?
mavContainer.getModel().get(name) : createAttribute(name, parameter, binderFactory, request);
WebDataBinder binder = binderFactory.createBinder(request, target, name);
target = binder.getTarget();
if (target != null) {
bindRequestParameters(mavContainer, binderFactory, binder, request, parameter);
validateIfApplicable(binder, parameter);
if (binder.getBindingResult().hasErrors()) {
if (isBindExceptionRequired(binder, parameter)) {
throw new BindException(binder.getBindingResult());
}
}
}
target = binder.convertIfNecessary(binder.getTarget(), parameter.getParameterType());
mavContainer.addAttribute(name, target);
return target;
}
/**
* Extension point to create the model attribute if not found in the model.
* The default implementation uses the default constructor.
*
* @param attributeName the name of the attribute, never {@code null}
* @param parameter the method parameter
* @param binderFactory for creating WebDataBinder instance
* @param request the current request
* @return the created model attribute, never {@code null}
*/
protected Object createAttribute(String attributeName, MethodParameter parameter,
WebDataBinderFactory binderFactory, NativeWebRequest request) throws Exception {
String value = getRequestValueForAttribute(attributeName, request);
if (value != null) {
Object attribute = createAttributeFromRequestValue(value, attributeName, parameter, binderFactory, request);
if (attribute != null) {
return attribute;
}
}
Class<?> parameterType = parameter.getParameterType();
if (parameterType.isArray() || List.class.isAssignableFrom(parameterType)) {
return ArrayList.class.newInstance();
}
if (Set.class.isAssignableFrom(parameterType)) {
return HashSet.class.newInstance();
}
if (MapWapper.class.isAssignableFrom(parameterType)) {
return MapWapper.class.newInstance();
}
return BeanUtils.instantiateClass(parameter.getParameterType());
}
/**
* Obtain a value from the request that may be used to instantiate the
* model attribute through type conversion from String to the target type.
* <p>The default implementation looks for the attribute name to match
* a URI variable first and then a request parameter.
*
* @param attributeName the model attribute name
* @param request the current request
* @return the request value to try to convert or {@code null}
*/
protected String getRequestValueForAttribute(String attributeName, NativeWebRequest request) {
Map<String, String> variables = getUriTemplateVariables(request);
if (StringUtils.hasText(variables.get(attributeName))) {
return variables.get(attributeName);
} else if (StringUtils.hasText(request.getParameter(attributeName))) {
return request.getParameter(attributeName);
} else {
return null;
}
}
/**
* Create a model attribute from a String request value (e.g. URI template
* variable, request parameter) using type conversion.
* <p>The default implementation converts only if there a registered
* {@link org.springframework.core.convert.converter.Converter} that can perform the conversion.
*
* @param sourceValue the source value to create the model attribute from
* @param attributeName the name of the attribute, never {@code null}
* @param parameter the method parameter
* @param binderFactory for creating WebDataBinder instance
* @param request the current request
* @return the created model attribute, or {@code null}
* @throws Exception
*/
protected Object createAttributeFromRequestValue(String sourceValue,
String attributeName,
MethodParameter parameter,
WebDataBinderFactory binderFactory,
NativeWebRequest request) throws Exception {
DataBinder binder = binderFactory.createBinder(request, null, attributeName);
ConversionService conversionService = binder.getConversionService();
if (conversionService != null) {
TypeDescriptor source = TypeDescriptor.valueOf(String.class);
TypeDescriptor target = new TypeDescriptor(parameter);
if (conversionService.canConvert(source, target)) {
return binder.convertIfNecessary(sourceValue, parameter.getParameterType(), parameter);
}
}
return null;
}
/**
* {@inheritDoc}
* <p>Downcast {@link org.springframework.web.bind.WebDataBinder} to {@link org.springframework.web.bind.ServletRequestDataBinder} before binding.
*
* @throws Exception
* @see org.springframework.web.servlet.mvc.method.annotation.ServletRequestDataBinderFactory
*/
protected void bindRequestParameters(
ModelAndViewContainer mavContainer,
WebDataBinderFactory binderFactory,
WebDataBinder binder,
NativeWebRequest request,
MethodParameter parameter) throws Exception {
Map<String, Boolean> hasProcessedPrefixMap = new HashMap<String, Boolean>();
Class<?> targetType = binder.getTarget().getClass();
ServletRequest servletRequest = prepareServletRequest(binder.getTarget(), request, parameter);
WebDataBinder simpleBinder = binderFactory.createBinder(request, null, null);
if (Collection.class.isAssignableFrom(targetType)) {//bind collection or array
Type type = parameter.getGenericParameterType();
Class<?> componentType = Object.class;
Collection target = (Collection) binder.getTarget();
List targetList = new ArrayList(target);
if (type instanceof ParameterizedType) {
componentType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
}
if (parameter.getParameterType().isArray()) {
componentType = parameter.getParameterType().getComponentType();
}
for (Object key : servletRequest.getParameterMap().keySet()) {
String prefixName = getPrefixName((String) key);
//每个prefix 只处理一次
if (hasProcessedPrefixMap.containsKey(prefixName)) {
continue;
} else {
hasProcessedPrefixMap.put(prefixName, Boolean.TRUE);
}
if (isSimpleComponent(prefixName)) { //bind simple type
Map<String, Object> paramValues = WebUtils.getParametersStartingWith(servletRequest, prefixName);
Matcher matcher = INDEX_PATTERN.matcher(prefixName);
if(!matcher.matches()) { //处理如 array=1&array=2的情况
for (Object value : paramValues.values()) {
targetList.add(simpleBinder.convertIfNecessary(value, componentType));
}
} else { //处理如 array[0]=1&array[1]=2的情况
int index = Integer.valueOf(matcher.group(1));
if (targetList.size() <= index) {
growCollectionIfNecessary(targetList, index);
}
targetList.set(index, simpleBinder.convertIfNecessary(paramValues.values(), componentType));
}
} else { //处理如 votes[1].title=votes[1].title&votes[0].title=votes[0].title&votes[0].id=0&votes[1].id=1
Object component = null;
//先查找老的 即已经在集合中的数据(而不是新添加一个)
Matcher matcher = INDEX_PATTERN.matcher(prefixName);
if(!matcher.matches()) {
throw new IllegalArgumentException("bind collection error, need integer index, key:" + key);
}
int index = Integer.valueOf(matcher.group(1));
if (targetList.size() <= index) {
growCollectionIfNecessary(targetList, index);
}
Iterator iterator = targetList.iterator();
for (int i = 0; i < index; i++) {
iterator.next();
}
component = iterator.next();
if(component == null) {
component = BeanUtils.instantiate(componentType);
}
WebDataBinder componentBinder = binderFactory.createBinder(request, component, null);
component = componentBinder.getTarget();
if (component != null) {
ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(servletRequest, prefixName, "");
componentBinder.bind(pvs);
validateIfApplicable(componentBinder, parameter);
if (componentBinder.getBindingResult().hasErrors()) {
if (isBindExceptionRequired(componentBinder, parameter)) {
throw new BindException(componentBinder.getBindingResult());
}
}
targetList.set(index, component);
}
}
target.clear();
target.addAll(targetList);
}
} else if (MapWapper.class.isAssignableFrom(targetType)) {
Type type = parameter.getGenericParameterType();
Class<?> keyType = Object.class;
Class<?> valueType = Object.class;
if (type instanceof ParameterizedType) {
keyType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
valueType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[1];
}
MapWapper mapWapper = ((MapWapper) binder.getTarget());
Map target = mapWapper.getInnerMap();
if(target == null) {
target = new HashMap();
mapWapper.setInnerMap(target);
}
for (Object key : servletRequest.getParameterMap().keySet()) {
String prefixName = getPrefixName((String) key);
//每个prefix 只处理一次
if (hasProcessedPrefixMap.containsKey(prefixName)) {
continue;
} else {
hasProcessedPrefixMap.put(prefixName, Boolean.TRUE);
}
Object keyValue = simpleBinder.convertIfNecessary(getMapKey(prefixName), keyType);
if (isSimpleComponent(prefixName)) { //bind simple type
Map<String, Object> paramValues = WebUtils.getParametersStartingWith(servletRequest, prefixName);
for (Object value : paramValues.values()) {
target.put(keyValue, simpleBinder.convertIfNecessary(value, valueType));
}
} else {
Object component = target.get(keyValue);
if(component == null) {
component = BeanUtils.instantiate(valueType);
}
WebDataBinder componentBinder = binderFactory.createBinder(request, component, null);
component = componentBinder.getTarget();
if (component != null) {
ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(servletRequest, prefixName, "");
componentBinder.bind(pvs);
validateComponent(componentBinder, parameter);
target.put(keyValue, component);
}
}
}
} else {//bind model
ServletRequestDataBinder servletBinder = (ServletRequestDataBinder) binder;
servletBinder.bind(servletRequest);
}
}
private void growCollectionIfNecessary(final Collection collection, final int index) {
if(index >= collection.size() && index < this.autoGrowCollectionLimit) {
for (int i = collection.size(); i <= index; i++) {
collection.add(null);
}
}
}
private Object getMapKey(String prefixName) {
String key = prefixName;
if (key.startsWith("['")) {
key = key.replaceAll("\\[\'", "").replaceAll("\'\\]", "");
}
if (key.startsWith("[\"")) {
key = key.replaceAll("\\[\"", "").replaceAll("\"\\]", "");
}
if (key.endsWith(".")) {
key = key.substring(0, key.length() - 1);
}
return key;
}
private boolean isSimpleComponent(String prefixName) {
return !prefixName.endsWith(".");
}
private String getPrefixName(String name) {
int begin = 0;
int end = name.indexOf("]") + 1;
if (name.indexOf("].") >= 0) {
end = end + 1;
}
return name.substring(begin, end);
}
private ServletRequest prepareServletRequest(Object target, NativeWebRequest request, MethodParameter parameter) {
String modelPrefixName = parameter.getParameterAnnotation(FormModel.class).value();
HttpServletRequest nativeRequest = (HttpServletRequest) request.getNativeRequest();
MultipartRequest multipartRequest = WebUtils.getNativeRequest(nativeRequest, MultipartRequest.class);
MockHttpServletRequest mockRequest = null;
if (multipartRequest != null) {
MockMultipartHttpServletRequest mockMultipartRequest = new MockMultipartHttpServletRequest();
for(MultipartFile file : multipartRequest.getFileMap().values()) {
mockMultipartRequest.addFile(new MultipartFileWrapper(getNewParameterName(file.getName(), modelPrefixName), file));
}
mockRequest = mockMultipartRequest;
} else {
mockRequest = new MockHttpServletRequest();
}
for (Entry<String, String> entry : getUriTemplateVariables(request).entrySet()) {
String parameterName = entry.getKey();
String value = entry.getValue();
if (isFormModelAttribute(parameterName, modelPrefixName)) {
mockRequest.setParameter(getNewParameterName(parameterName, modelPrefixName), value);
}
}
for (Object parameterEntry : nativeRequest.getParameterMap().entrySet()) {
Entry<String, String[]> entry = (Entry<String, String[]>) parameterEntry;
String parameterName = entry.getKey();
String[] value = entry.getValue();
if (isFormModelAttribute(parameterName, modelPrefixName)) {
mockRequest.setParameter(getNewParameterName(parameterName, modelPrefixName), value);
}
}
return mockRequest;
}
private String getNewParameterName(String parameterName, String modelPrefixName) {
int modelPrefixNameLength = modelPrefixName.length();
if (parameterName.charAt(modelPrefixNameLength) == '.') {
return parameterName.substring(modelPrefixNameLength + 1);
}
if (parameterName.charAt(modelPrefixNameLength) == '[') {
return parameterName.substring(modelPrefixNameLength);
}
throw new IllegalArgumentException("illegal request parameter, can not binding to @FormBean(" + modelPrefixName + ")");
}
private boolean isFormModelAttribute(String parameterName, String modelPrefixName) {
int modelPrefixNameLength = modelPrefixName.length();
if (parameterName.length() == modelPrefixNameLength) {
return false;
}
if (!parameterName.startsWith(modelPrefixName)) {
return false;
}
char ch = (char) parameterName.charAt(modelPrefixNameLength);
if (ch == '.' || ch == '[') {
return true;
}
return false;
}
protected void validateComponent(WebDataBinder binder, MethodParameter parameter) throws BindException {
boolean validateParameter = validateParameter(parameter);
Annotation[] annotations = binder.getTarget().getClass().getAnnotations();
for (Annotation annot : annotations) {
if (annot.annotationType().getSimpleName().startsWith("Valid") && validateParameter) {
Object hints = AnnotationUtils.getValue(annot);
binder.validate(hints instanceof Object[] ? (Object[]) hints : new Object[]{hints});
}
}
if (binder.getBindingResult().hasErrors()) {
if (isBindExceptionRequired(binder, parameter)) {
throw new BindException(binder.getBindingResult());
}
}
}
private boolean validateParameter(MethodParameter parameter) {
Annotation[] annotations = parameter.getParameterAnnotations();
for (Annotation annot : annotations) {
if (annot.annotationType().getSimpleName().startsWith("Valid")) {
return true;
}
}
return false;
}
/**
* Validate the model attribute if applicable.
* <p>The default implementation checks for {@code @javax.validation.Valid}.
*
* @param binder the DataBinder to be used
* @param parameter the method parameter
*/
protected void validateIfApplicable(WebDataBinder binder, MethodParameter parameter) {
Annotation[] annotations = parameter.getParameterAnnotations();
for (Annotation annot : annotations) {
if (annot.annotationType().getSimpleName().startsWith("Valid")) {
Object hints = AnnotationUtils.getValue(annot);
binder.validate(hints instanceof Object[] ? (Object[]) hints : new Object[]{hints});
}
}
}
/**
* Whether to raise a {@link org.springframework.validation.BindException} on bind or validation errors.
* The default implementation returns {@code true} if the next method
* argument is not of type {@link org.springframework.validation.Errors}.
*
* @param binder the data binder used to perform data binding
* @param parameter the method argument
*/
protected boolean isBindExceptionRequired(WebDataBinder binder, MethodParameter parameter) {
int i = parameter.getParameterIndex();
Class<?>[] paramTypes = parameter.getMethod().getParameterTypes();
boolean hasBindingResult = (paramTypes.length > (i + 1) && Errors.class.isAssignableFrom(paramTypes[i + 1]));
return !hasBindingResult;
}
private static class MultipartFileWrapper implements MultipartFile {
private String name;
private MultipartFile delegate;
private MultipartFileWrapper(String name, MultipartFile delegate) {
this.name = name;
this.delegate = delegate;
}
@Override
public String getName() {
return name;
}
@Override
public String getOriginalFilename() {
return delegate.getOriginalFilename();
}
@Override
public String getContentType() {
return delegate.getContentType();
}
@Override
public boolean isEmpty() {
return delegate.isEmpty();
}
@Override
public long getSize() {
return delegate.getSize();
}
@Override
public byte[] getBytes() throws IOException {
return delegate.getBytes();
}
@Override
public InputStream getInputStream() throws IOException {
return delegate.getInputStream();
}
@Override
public void transferTo(File dest) throws IOException, IllegalStateException {
delegate.transferTo(dest);
}
}
}