Skip to content

Commit d77af71

Browse files
committed
Revised common validation methods in AbstractMessageConverterMethodArgumentResolver
The protected validation methods are analogous to ModelAttributeMethodProcessor now. Issue: SPR-12655 (cherry picked from commit 7191050)
1 parent 5db4e4b commit d77af71

File tree

5 files changed

+105
-143
lines changed

5 files changed

+105
-143
lines changed

spring-web/src/main/java/org/springframework/web/method/annotation/ModelAttributeMethodProcessor.java

Lines changed: 15 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -109,15 +109,12 @@ public final Object resolveArgument(MethodParameter parameter, ModelAndViewConta
109109
if (binder.getTarget() != null) {
110110
bindRequestParameters(binder, webRequest);
111111
validateIfApplicable(binder, parameter);
112-
if (binder.getBindingResult().hasErrors()) {
113-
if (isBindExceptionRequired(binder, parameter)) {
114-
throw new BindException(binder.getBindingResult());
115-
}
112+
if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
113+
throw new BindException(binder.getBindingResult());
116114
}
117115
}
118116

119117
// Add resolved attribute and BindingResult at the end of the model
120-
121118
Map<String, Object> bindingResultModel = binder.getBindingResult().getModel();
122119
mavContainer.removeAttributes(bindingResultModel);
123120
mavContainer.addAllAttributes(bindingResultModel);
@@ -129,15 +126,15 @@ public final Object resolveArgument(MethodParameter parameter, ModelAndViewConta
129126
* Extension point to create the model attribute if not found in the model.
130127
* The default implementation uses the default constructor.
131128
* @param attributeName the name of the attribute (never {@code null})
132-
* @param parameter the method parameter
129+
* @param methodParam the method parameter
133130
* @param binderFactory for creating WebDataBinder instance
134131
* @param request the current request
135132
* @return the created model attribute (never {@code null})
136133
*/
137-
protected Object createAttribute(String attributeName, MethodParameter parameter,
138-
WebDataBinderFactory binderFactory, NativeWebRequest request) throws Exception {
134+
protected Object createAttribute(String attributeName, MethodParameter methodParam,
135+
WebDataBinderFactory binderFactory, NativeWebRequest request) throws Exception {
139136

140-
return BeanUtils.instantiateClass(parameter.getParameterType());
137+
return BeanUtils.instantiateClass(methodParam.getParameterType());
141138
}
142139

143140
/**
@@ -155,10 +152,10 @@ protected void bindRequestParameters(WebDataBinder binder, NativeWebRequest requ
155152
* Spring's {@link org.springframework.validation.annotation.Validated},
156153
* and custom annotations whose name starts with "Valid".
157154
* @param binder the DataBinder to be used
158-
* @param parameter the method parameter
155+
* @param methodParam the method parameter
159156
*/
160-
protected void validateIfApplicable(WebDataBinder binder, MethodParameter parameter) {
161-
Annotation[] annotations = parameter.getParameterAnnotations();
157+
protected void validateIfApplicable(WebDataBinder binder, MethodParameter methodParam) {
158+
Annotation[] annotations = methodParam.getParameterAnnotations();
162159
for (Annotation ann : annotations) {
163160
Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class);
164161
if (validatedAnn != null || ann.annotationType().getSimpleName().startsWith("Valid")) {
@@ -171,16 +168,15 @@ protected void validateIfApplicable(WebDataBinder binder, MethodParameter parame
171168
}
172169

173170
/**
174-
* Whether to raise a {@link BindException} on validation errors.
171+
* Whether to raise a fatal bind exception on validation errors.
175172
* @param binder the data binder used to perform data binding
176-
* @param parameter the method argument
177-
* @return {@code true} if the next method argument is not of type {@link Errors}.
173+
* @param methodParam the method argument
174+
* @return {@code true} if the next method argument is not of type {@link Errors}
178175
*/
179-
protected boolean isBindExceptionRequired(WebDataBinder binder, MethodParameter parameter) {
180-
int i = parameter.getParameterIndex();
181-
Class<?>[] paramTypes = parameter.getMethod().getParameterTypes();
176+
protected boolean isBindExceptionRequired(WebDataBinder binder, MethodParameter methodParam) {
177+
int i = methodParam.getParameterIndex();
178+
Class<?>[] paramTypes = methodParam.getMethod().getParameterTypes();
182179
boolean hasBindingResult = (paramTypes.length > (i + 1) && Errors.class.isAssignableFrom(paramTypes[i + 1]));
183-
184180
return !hasBindingResult;
185181
}
186182

spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodArgumentResolver.java

Lines changed: 35 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package org.springframework.web.servlet.mvc.method.annotation;
1818

1919
import java.io.IOException;
20+
import java.lang.annotation.Annotation;
2021
import java.lang.reflect.Type;
2122
import java.util.ArrayList;
2223
import java.util.Collections;
@@ -30,6 +31,7 @@
3031

3132
import org.springframework.core.MethodParameter;
3233
import org.springframework.core.ResolvableType;
34+
import org.springframework.core.annotation.AnnotationUtils;
3335
import org.springframework.http.HttpInputMessage;
3436
import org.springframework.http.InvalidMediaTypeException;
3537
import org.springframework.http.MediaType;
@@ -38,7 +40,9 @@
3840
import org.springframework.http.server.ServletServerHttpRequest;
3941
import org.springframework.util.Assert;
4042
import org.springframework.validation.Errors;
43+
import org.springframework.validation.annotation.Validated;
4144
import org.springframework.web.HttpMediaTypeNotSupportedException;
45+
import org.springframework.web.bind.WebDataBinder;
4246
import org.springframework.web.context.request.NativeWebRequest;
4347
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
4448

@@ -113,8 +117,8 @@ protected <T> Object readWithMessageConverters(NativeWebRequest webRequest,
113117
* @throws HttpMediaTypeNotSupportedException if no suitable message converter is found
114118
*/
115119
@SuppressWarnings("unchecked")
116-
protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, MethodParameter methodParam,
117-
Type targetType) throws IOException, HttpMediaTypeNotSupportedException {
120+
protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage,
121+
MethodParameter methodParam, Type targetType) throws IOException, HttpMediaTypeNotSupportedException {
118122

119123
MediaType contentType;
120124
try {
@@ -165,14 +169,38 @@ protected ServletServerHttpRequest createInputMessage(NativeWebRequest webReques
165169
}
166170

167171
/**
168-
* Whether to raise a handler method invocation exception on validation errors.
169-
* @param parameter the method argument
172+
* Validate the request part if applicable.
173+
* <p>The default implementation checks for {@code @javax.validation.Valid},
174+
* Spring's {@link org.springframework.validation.annotation.Validated},
175+
* and custom annotations whose name starts with "Valid".
176+
* @param binder the DataBinder to be used
177+
* @param methodParam the method parameter
178+
* @see #isBindExceptionRequired
179+
* @since 4.1.5
180+
*/
181+
protected void validateIfApplicable(WebDataBinder binder, MethodParameter methodParam) {
182+
Annotation[] annotations = methodParam.getParameterAnnotations();
183+
for (Annotation ann : annotations) {
184+
Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class);
185+
if (validatedAnn != null || ann.annotationType().getSimpleName().startsWith("Valid")) {
186+
Object hints = (validatedAnn != null ? validatedAnn.value() : AnnotationUtils.getValue(ann));
187+
Object[] validationHints = (hints instanceof Object[] ? (Object[]) hints : new Object[] {hints});
188+
binder.validate(validationHints);
189+
break;
190+
}
191+
}
192+
}
193+
194+
/**
195+
* Whether to raise a fatal bind exception on validation errors.
196+
* @param binder the data binder used to perform data binding
197+
* @param methodParam the method argument
170198
* @return {@code true} if the next method argument is not of type {@link Errors}
171199
* @since 4.1.5
172200
*/
173-
protected boolean isBindingErrorFatal(MethodParameter parameter) {
174-
int i = parameter.getParameterIndex();
175-
Class<?>[] paramTypes = parameter.getMethod().getParameterTypes();
201+
protected boolean isBindExceptionRequired(WebDataBinder binder, MethodParameter methodParam) {
202+
int i = methodParam.getParameterIndex();
203+
Class<?>[] paramTypes = methodParam.getMethod().getParameterTypes();
176204
boolean hasBindingResult = (paramTypes.length > (i + 1) && Errors.class.isAssignableFrom(paramTypes[i + 1]));
177205
return !hasBindingResult;
178206
}

spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartMethodArgumentResolver.java

Lines changed: 27 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616

1717
package org.springframework.web.servlet.mvc.method.annotation;
1818

19-
import java.lang.annotation.Annotation;
2019
import java.util.ArrayList;
2120
import java.util.Collection;
2221
import java.util.List;
@@ -25,13 +24,10 @@
2524

2625
import org.springframework.core.GenericCollectionTypeResolver;
2726
import org.springframework.core.MethodParameter;
28-
import org.springframework.core.annotation.AnnotationUtils;
2927
import org.springframework.http.HttpInputMessage;
3028
import org.springframework.http.converter.HttpMessageConverter;
3129
import org.springframework.util.Assert;
3230
import org.springframework.validation.BindingResult;
33-
import org.springframework.validation.Errors;
34-
import org.springframework.validation.annotation.Validated;
3531
import org.springframework.web.bind.MethodArgumentNotValidException;
3632
import org.springframework.web.bind.WebDataBinder;
3733
import org.springframework.web.bind.annotation.RequestBody;
@@ -84,9 +80,9 @@ public RequestPartMethodArgumentResolver(List<HttpMessageConverter<?>> messageCo
8480
/**
8581
* Supports the following:
8682
* <ul>
87-
* <li>Annotated with {@code @RequestPart}
88-
* <li>Of type {@link MultipartFile} unless annotated with {@code @RequestParam}.
89-
* <li>Of type {@code javax.servlet.http.Part} unless annotated with {@code @RequestParam}.
83+
* <li>annotated with {@code @RequestPart}
84+
* <li>of type {@link MultipartFile} unless annotated with {@code @RequestParam}
85+
* <li>of type {@code javax.servlet.http.Part} unless annotated with {@code @RequestParam}
9086
* </ul>
9187
*/
9288
@Override
@@ -154,7 +150,10 @@ else if (isPartArray(parameter)) {
154150
arg = readWithMessageConverters(inputMessage, parameter, parameter.getParameterType());
155151
WebDataBinder binder = binderFactory.createBinder(request, arg, partName);
156152
if (arg != null) {
157-
validate(binder, parameter);
153+
validateIfApplicable(binder, parameter);
154+
if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
155+
throw new MethodArgumentNotValidException(parameter, binder.getBindingResult());
156+
}
158157
}
159158
mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + partName, binder.getBindingResult());
160159
}
@@ -164,8 +163,8 @@ else if (isPartArray(parameter)) {
164163
}
165164
}
166165

167-
RequestPart annot = parameter.getParameterAnnotation(RequestPart.class);
168-
boolean isRequired = (annot == null || annot.required());
166+
RequestPart ann = parameter.getParameterAnnotation(RequestPart.class);
167+
boolean isRequired = (ann == null || ann.required());
169168

170169
if (arg == null && isRequired) {
171170
throw new MissingServletRequestPartException(partName);
@@ -181,80 +180,51 @@ private static void assertIsMultipartRequest(HttpServletRequest request) {
181180
}
182181
}
183182

184-
private String getPartName(MethodParameter param) {
185-
RequestPart annot = param.getParameterAnnotation(RequestPart.class);
186-
String partName = (annot != null ? annot.value() : "");
183+
private String getPartName(MethodParameter methodParam) {
184+
RequestPart ann = methodParam.getParameterAnnotation(RequestPart.class);
185+
String partName = (ann != null ? ann.value() : "");
187186
if (partName.length() == 0) {
188-
partName = param.getParameterName();
187+
partName = methodParam.getParameterName();
189188
if (partName == null) {
190189
throw new IllegalArgumentException("Request part name for argument type [" +
191-
param.getNestedParameterType().getName() +
190+
methodParam.getNestedParameterType().getName() +
192191
"] not specified, and parameter name information not found in class file either.");
193192
}
194193
}
195194
return partName;
196195
}
197196

198-
private boolean isMultipartFileCollection(MethodParameter param) {
199-
Class<?> collectionType = getCollectionParameterType(param);
200-
return (collectionType != null && collectionType.equals(MultipartFile.class));
197+
private boolean isMultipartFileCollection(MethodParameter methodParam) {
198+
Class<?> collectionType = getCollectionParameterType(methodParam);
199+
return MultipartFile.class.equals(collectionType);
201200
}
202201

203-
private boolean isMultipartFileArray(MethodParameter param) {
204-
Class<?> paramType = param.getNestedParameterType().getComponentType();
205-
return (paramType != null && MultipartFile.class.equals(paramType));
202+
private boolean isMultipartFileArray(MethodParameter methodParam) {
203+
Class<?> paramType = methodParam.getNestedParameterType().getComponentType();
204+
return MultipartFile.class.equals(paramType);
206205
}
207206

208-
private boolean isPartCollection(MethodParameter param) {
209-
Class<?> collectionType = getCollectionParameterType(param);
207+
private boolean isPartCollection(MethodParameter methodParam) {
208+
Class<?> collectionType = getCollectionParameterType(methodParam);
210209
return (collectionType != null && "javax.servlet.http.Part".equals(collectionType.getName()));
211210
}
212211

213-
private boolean isPartArray(MethodParameter param) {
214-
Class<?> paramType = param.getNestedParameterType().getComponentType();
212+
private boolean isPartArray(MethodParameter methodParam) {
213+
Class<?> paramType = methodParam.getNestedParameterType().getComponentType();
215214
return (paramType != null && "javax.servlet.http.Part".equals(paramType.getName()));
216215
}
217216

218-
private Class<?> getCollectionParameterType(MethodParameter param) {
219-
Class<?> paramType = param.getNestedParameterType();
217+
private Class<?> getCollectionParameterType(MethodParameter methodParam) {
218+
Class<?> paramType = methodParam.getNestedParameterType();
220219
if (Collection.class.equals(paramType) || List.class.isAssignableFrom(paramType)){
221-
Class<?> valueType = GenericCollectionTypeResolver.getCollectionParameterType(param);
220+
Class<?> valueType = GenericCollectionTypeResolver.getCollectionParameterType(methodParam);
222221
if (valueType != null) {
223222
return valueType;
224223
}
225224
}
226225
return null;
227226
}
228227

229-
/**
230-
* Validate the request part if applicable.
231-
* <p>The default implementation checks for {@code @javax.validation.Valid},
232-
* Spring's {@link org.springframework.validation.annotation.Validated},
233-
* and custom annotations whose name starts with "Valid".
234-
* @param binder the DataBinder to be used
235-
* @param param the method parameter
236-
* @throws MethodArgumentNotValidException in case of a binding error which
237-
* is meant to be fatal (i.e. without a declared {@link Errors} parameter)
238-
* @see #isBindingErrorFatal
239-
*/
240-
protected void validate(WebDataBinder binder, MethodParameter param) throws MethodArgumentNotValidException {
241-
Annotation[] annotations = param.getParameterAnnotations();
242-
for (Annotation ann : annotations) {
243-
Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class);
244-
if (validatedAnn != null || ann.annotationType().getSimpleName().startsWith("Valid")) {
245-
Object hints = (validatedAnn != null ? validatedAnn.value() : AnnotationUtils.getValue(ann));
246-
Object[] validationHints = (hints instanceof Object[] ? (Object[]) hints : new Object[] {hints});
247-
binder.validate(validationHints);
248-
BindingResult bindingResult = binder.getBindingResult();
249-
if (bindingResult.hasErrors()) {
250-
if (isBindingErrorFatal(param)) {
251-
throw new MethodArgumentNotValidException(param, bindingResult);
252-
}
253-
}
254-
}
255-
}
256-
}
257-
258228

259229
/**
260230
* Inner class to avoid hard-coded dependency on Servlet 3.0 Part type...

0 commit comments

Comments
 (0)