@InitBinder("employeeForm") public void initBinder(WebDataBinder binder){ binder.setValidator(employeeValidator); binder.registerCustomEditor(Date.class, new DateEditor()); binder.registerCustomEditor(Integer.class, "age", new AgeEditor()); }
/** * Add {@link BindingResult} attributes to the model for attributes that require it. */ private void updateBindingResult(NativeWebRequest request, ModelMap model) throws Exception { List<String> keyNames = new ArrayList<String>(model.keySet()); for (String name : keyNames) { Object value = model.get(name); if (isBindingCandidate(name, value)) { String bindingResultKey = BindingResult.MODEL_KEY_PREFIX + name; if (!model.containsAttribute(bindingResultKey)) { WebDataBinder dataBinder = binderFactory.createBinder(request, value, name); model.put(bindingResultKey, dataBinder.getBindingResult()); } } } }
private Object resolveCookieValue(String cookieName, boolean required, String defaultValue, MethodParameter methodParam, NativeWebRequest webRequest, Object handlerForInitBinderCall) throws Exception { Class<?> paramType = methodParam.getParameterType(); if (cookieName.length() == 0) { cookieName = getRequiredParameterName(methodParam); } Object cookieValue = resolveCookieValue(cookieName, paramType, webRequest); if (cookieValue == null) { if (defaultValue != null) { cookieValue = resolveDefaultValue(defaultValue); } else if (required) { raiseMissingCookieException(cookieName, paramType); } cookieValue = checkValue(cookieName, cookieValue, paramType); } WebDataBinder binder = createBinder(webRequest, null, cookieName); initBinder(handlerForInitBinderCall, cookieName, binder, webRequest); return binder.convertIfNecessary(cookieValue, paramType, methodParam); }
private WebDataBinder resolveModelAttribute(String attrName, MethodParameter methodParam, ExtendedModelMap implicitModel, NativeWebRequest webRequest, Object handler) throws Exception { // Bind request parameter onto object... String name = attrName; if ("".equals(name)) { name = Conventions.getVariableNameForParameter(methodParam); } Class<?> paramType = methodParam.getParameterType(); Object bindObject; if (implicitModel.containsKey(name)) { bindObject = implicitModel.get(name); } else if (this.methodResolver.isSessionAttribute(name, paramType)) { bindObject = this.sessionAttributeStore.retrieveAttribute(webRequest, name); if (bindObject == null) { raiseSessionRequiredException("Session attribute '" + name + "' required - not found in session"); } } else { bindObject = BeanUtils.instantiateClass(paramType); } WebDataBinder binder = createBinder(webRequest, bindObject, name); initBinder(handler, name, binder, webRequest); return binder; }
@Override public void initBinder(WebDataBinder binder, WebRequest request) { binder.setAutoGrowNestedPaths(this.autoGrowNestedPaths); if (this.directFieldAccess) { binder.initDirectFieldAccess(); } if (this.messageCodesResolver != null) { binder.setMessageCodesResolver(this.messageCodesResolver); } if (this.bindingErrorProcessor != null) { binder.setBindingErrorProcessor(this.bindingErrorProcessor); } if (this.validator != null && binder.getTarget() != null && this.validator.supports(binder.getTarget().getClass())) { binder.setValidator(this.validator); } if (this.conversionService != null) { binder.setConversionService(this.conversionService); } if (this.propertyEditorRegistrars != null) { for (PropertyEditorRegistrar propertyEditorRegistrar : this.propertyEditorRegistrars) { propertyEditorRegistrar.registerCustomEditors(binder); } } }
@InitBinder public void initBinder(WebDataBinder binder) { binder.setAutoGrowNestedPaths(false); binder.registerCustomEditor( Long.class, new CustomNumberEditor(Long.class, true)); binder.registerCustomEditor( Double.class, new CustomNumberEditor(Double.class, true)); binder.registerCustomEditor( BigDecimal.class, new CustomNumberEditor( BigDecimal.class, new DecimalFormat("#,##0.00"), true)); binder.registerCustomEditor( Boolean.class, new CustomBooleanEditor(true)); binder.registerCustomEditor( Date.class, new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy"), true)); binder.registerCustomEditor( Object.class, new ObjectTypeEditorHelper()); }
@InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor( Long.class, new CustomNumberEditor(Long.class, true)); binder.registerCustomEditor( Double.class, new CustomNumberEditor(Double.class, true)); binder.registerCustomEditor( BigDecimal.class, new CustomNumberEditor( BigDecimal.class, new DecimalFormat("#,##0.00"), true)); binder.registerCustomEditor( Boolean.class, new CustomBooleanEditor(true)); binder.registerCustomEditor( Date.class, new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy"), true)); binder.registerCustomEditor( Object.class, new ObjectTypeEditorHelper()); }
@Test public void updateModelSessionAttributesSaved() throws Exception { String attributeName = "sessionAttr"; String attribute = "value"; ModelAndViewContainer container = new ModelAndViewContainer(); container.addAttribute(attributeName, attribute); WebDataBinder dataBinder = new WebDataBinder(attribute, attributeName); WebDataBinderFactory binderFactory = mock(WebDataBinderFactory.class); given(binderFactory.createBinder(this.webRequest, attribute, attributeName)).willReturn(dataBinder); ModelFactory modelFactory = new ModelFactory(null, binderFactory, this.sessionAttrsHandler); modelFactory.updateModel(this.webRequest, container); assertEquals(attribute, container.getModel().get(attributeName)); assertEquals(attribute, this.sessionAttributeStore.retrieveAttribute(this.webRequest, attributeName)); }
@InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor( Long.class, new CustomNumberEditor(Long.class, true)); binder.registerCustomEditor( Double.class, new CustomNumberEditor(Double.class, true)); binder.registerCustomEditor( BigDecimal.class, new CustomNumberEditor( BigDecimal.class, new DecimalFormat("#,##0.00"), true)); binder.registerCustomEditor( Boolean.class, new CustomBooleanEditor(false)); binder.registerCustomEditor( Date.class, new CustomDateEditor(new SimpleDateFormat("dd/MM/yyyy"), true)); }
/*** * @param binder * @InitBinder 用来配置全局 Controller ,设置 WebDataBinder,WebDataBinder 用来自动绑定前台请求参数到 Model 中。 */ @InitBinder public void initBinder(WebDataBinder binder) { //忽略 request 中的参数 dis ,更多关于 WebDataBinder ,可参考文档。 //binder.setDisallowedFields("dis"); // binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() { // @Override // public void setAsText(String text) throws IllegalArgumentException { // LocalDate.parse(text, DateTimeFormatter.ISO_DATE); // } // }); //自动绑定 LocalDate // // @GetMapping // public ResponseEntity<List<Order>> getOrdersByDate( // @RequestParam(name = "date")LocalDate date) { // // retrieve and return orders by date // } }
/** * Add {@link BindingResult} attributes to the model for attributes that require it. */ private void updateBindingResult(NativeWebRequest request, ModelMap model) throws Exception { List<String> keyNames = new ArrayList<String>(model.keySet()); for (String name : keyNames) { Object value = model.get(name); if (isBindingCandidate(name, value)) { String bindingResultKey = BindingResult.MODEL_KEY_PREFIX + name; if (!model.containsAttribute(bindingResultKey)) { WebDataBinder dataBinder = dataBinderFactory.createBinder(request, value, name); model.put(bindingResultKey, dataBinder.getBindingResult()); } } } }
@InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(SignatureForm.class, new EnumPropertyEditor(SignatureForm.class)); binder.registerCustomEditor(ASiCContainerType.class, new EnumPropertyEditor(ASiCContainerType.class)); binder.registerCustomEditor(SignatureLevel.class, new EnumPropertyEditor(SignatureLevel.class)); binder.registerCustomEditor(DigestAlgorithm.class, new EnumPropertyEditor(DigestAlgorithm.class)); binder.registerCustomEditor(EncryptionAlgorithm.class, new EnumPropertyEditor(EncryptionAlgorithm.class)); }
@InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(SignatureForm.class, new EnumPropertyEditor(SignatureForm.class)); binder.registerCustomEditor(ASiCContainerType.class, new EnumPropertyEditor(ASiCContainerType.class)); binder.registerCustomEditor(SignaturePackaging.class, new EnumPropertyEditor(SignaturePackaging.class)); binder.registerCustomEditor(SignatureLevel.class, new EnumPropertyEditor(SignatureLevel.class)); binder.registerCustomEditor(DigestAlgorithm.class, new EnumPropertyEditor(DigestAlgorithm.class)); binder.registerCustomEditor(EncryptionAlgorithm.class, new EnumPropertyEditor(EncryptionAlgorithm.class)); }
@InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(ASiCContainerType.class, new EnumPropertyEditor(ASiCContainerType.class)); binder.registerCustomEditor(SignatureForm.class, new EnumPropertyEditor(SignatureForm.class)); binder.registerCustomEditor(SignaturePackaging.class, new EnumPropertyEditor(SignaturePackaging.class)); binder.registerCustomEditor(SignatureLevel.class, new EnumPropertyEditor(SignatureLevel.class)); }
/** * 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 BindException if data binding and validation result in an error * and the next method parameter is not of type {@link Errors}. * @throws Exception if WebDataBinder initialization fails. */ @Override public final Object resolveArgument( MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest request, WebDataBinderFactory binderFactory) throws Exception { String name = ModelFactory.getNameForParameter(parameter); Object attribute = (mavContainer.containsAttribute(name)) ? mavContainer.getModel().get(name) : createAttribute(name, parameter, binderFactory, request); WebDataBinder binder = binderFactory.createBinder(request, attribute, name); if (binder.getTarget() != null) { bindRequestParameters(binder, request); validateIfApplicable(binder, parameter); if (binder.getBindingResult().hasErrors()) { if (isBindExceptionRequired(binder, parameter)) { throw new BindException(binder.getBindingResult()); } } } // Add resolved attribute and BindingResult at the end of the model Map<String, Object> bindingResultModel = binder.getBindingResult().getModel(); mavContainer.removeAttributes(bindingResultModel); mavContainer.addAllAttributes(bindingResultModel); return binder.getTarget(); }
/** * 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}); break; } } }
/** * Whether to raise a {@link BindException} on validation errors. * @param binder the data binder used to perform data binding * @param parameter the method argument * @return {@code true} if the next method argument is not of type {@link Errors}. */ 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; }
/** * Initialize a WebDataBinder with {@code @InitBinder} methods. * If the {@code @InitBinder} annotation specifies attributes names, it is * invoked only if the names include the target object name. * @throws Exception if one of the invoked @{@link InitBinder} methods fail. */ @Override public void initBinder(WebDataBinder binder, NativeWebRequest request) throws Exception { for (InvocableHandlerMethod binderMethod : this.binderMethods) { if (isBinderMethodApplicable(binderMethod, binder)) { Object returnValue = binderMethod.invokeForRequest(request, null, binder); if (returnValue != null) { throw new IllegalStateException("@InitBinder methods should return void: " + binderMethod); } } } }
@Override public final Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { Class<?> paramType = parameter.getParameterType(); NamedValueInfo namedValueInfo = getNamedValueInfo(parameter); Object arg = resolveName(namedValueInfo.name, parameter, webRequest); if (arg == null) { if (namedValueInfo.defaultValue != null) { arg = resolveDefaultValue(namedValueInfo.defaultValue); } else if (namedValueInfo.required) { handleMissingValue(namedValueInfo.name, parameter); } arg = handleNullValue(namedValueInfo.name, arg, paramType); } else if ("".equals(arg) && (namedValueInfo.defaultValue != null)) { arg = resolveDefaultValue(namedValueInfo.defaultValue); } if (binderFactory != null) { WebDataBinder binder = binderFactory.createBinder(webRequest, null, namedValueInfo.name); arg = binder.convertIfNecessary(arg, paramType, parameter); } handleResolvedValue(arg, namedValueInfo.name, parameter, mavContainer, webRequest); return arg; }
protected void initBinder(Object handler, String attrName, WebDataBinder binder, NativeWebRequest webRequest) throws Exception { if (this.bindingInitializer != null) { this.bindingInitializer.initBinder(binder, webRequest); } if (handler != null) { Set<Method> initBinderMethods = this.methodResolver.getInitBinderMethods(); if (!initBinderMethods.isEmpty()) { boolean debug = logger.isDebugEnabled(); for (Method initBinderMethod : initBinderMethods) { Method methodToInvoke = BridgeMethodResolver.findBridgedMethod(initBinderMethod); String[] targetNames = AnnotationUtils.findAnnotation(initBinderMethod, InitBinder.class).value(); if (targetNames.length == 0 || Arrays.asList(targetNames).contains(attrName)) { Object[] initBinderArgs = resolveInitBinderArguments(handler, methodToInvoke, binder, webRequest); if (debug) { logger.debug("Invoking init-binder method: " + methodToInvoke); } ReflectionUtils.makeAccessible(methodToInvoke); Object returnValue = methodToInvoke.invoke(handler, initBinderArgs); if (returnValue != null) { throw new IllegalStateException( "InitBinder methods must not have a return value: " + methodToInvoke); } } } } } }
@SuppressWarnings("unchecked") private Object resolveRequestParam(String paramName, boolean required, String defaultValue, MethodParameter methodParam, NativeWebRequest webRequest, Object handlerForInitBinderCall) throws Exception { Class<?> paramType = methodParam.getParameterType(); if (Map.class.isAssignableFrom(paramType) && paramName.length() == 0) { return resolveRequestParamMap((Class<? extends Map<?, ?>>) paramType, webRequest); } if (paramName.length() == 0) { paramName = getRequiredParameterName(methodParam); } Object paramValue = null; MultipartRequest multipartRequest = webRequest.getNativeRequest(MultipartRequest.class); if (multipartRequest != null) { List<MultipartFile> files = multipartRequest.getFiles(paramName); if (!files.isEmpty()) { paramValue = (files.size() == 1 ? files.get(0) : files); } } if (paramValue == null) { String[] paramValues = webRequest.getParameterValues(paramName); if (paramValues != null) { paramValue = (paramValues.length == 1 ? paramValues[0] : paramValues); } } if (paramValue == null) { if (defaultValue != null) { paramValue = resolveDefaultValue(defaultValue); } else if (required) { raiseMissingParameterException(paramName, paramType); } paramValue = checkValue(paramName, paramValue, paramType); } WebDataBinder binder = createBinder(webRequest, null, paramName); initBinder(handlerForInitBinderCall, paramName, binder, webRequest); return binder.convertIfNecessary(paramValue, paramType, methodParam); }
@SuppressWarnings("unchecked") private Object resolveRequestHeader(String headerName, boolean required, String defaultValue, MethodParameter methodParam, NativeWebRequest webRequest, Object handlerForInitBinderCall) throws Exception { Class<?> paramType = methodParam.getParameterType(); if (Map.class.isAssignableFrom(paramType)) { return resolveRequestHeaderMap((Class<? extends Map<?, ?>>) paramType, webRequest); } if (headerName.length() == 0) { headerName = getRequiredParameterName(methodParam); } Object headerValue = null; String[] headerValues = webRequest.getHeaderValues(headerName); if (headerValues != null) { headerValue = (headerValues.length == 1 ? headerValues[0] : headerValues); } if (headerValue == null) { if (defaultValue != null) { headerValue = resolveDefaultValue(defaultValue); } else if (required) { raiseMissingHeaderException(headerName, paramType); } headerValue = checkValue(headerName, headerValue, paramType); } WebDataBinder binder = createBinder(webRequest, null, headerName); initBinder(handlerForInitBinderCall, headerName, binder, webRequest); return binder.convertIfNecessary(headerValue, paramType, methodParam); }
private Object resolvePathVariable(String pathVarName, MethodParameter methodParam, NativeWebRequest webRequest, Object handlerForInitBinderCall) throws Exception { Class<?> paramType = methodParam.getParameterType(); if (pathVarName.length() == 0) { pathVarName = getRequiredParameterName(methodParam); } String pathVarValue = resolvePathVariable(pathVarName, paramType, webRequest); WebDataBinder binder = createBinder(webRequest, null, pathVarName); initBinder(handlerForInitBinderCall, pathVarName, binder, webRequest); return binder.convertIfNecessary(pathVarValue, paramType, methodParam); }
private void doBind(WebDataBinder binder, NativeWebRequest webRequest, boolean validate, Object[] validationHints, boolean failOnErrors) throws Exception { doBind(binder, webRequest); if (validate) { binder.validate(validationHints); } if (failOnErrors && binder.getBindingResult().hasErrors()) { throw new BindException(binder.getBindingResult()); } }
/** * Create a new {@link WebDataBinder} for the given target object and * initialize it through a {@link WebBindingInitializer}. * @throws Exception in case of invalid state or arguments */ @Override public final WebDataBinder createBinder(NativeWebRequest webRequest, Object target, String objectName) throws Exception { WebDataBinder dataBinder = createBinderInstance(target, objectName, webRequest); if (this.initializer != null) { this.initializer.initBinder(dataBinder, webRequest); } initBinder(dataBinder, webRequest); return dataBinder; }
@InitBinder("fileUpload") protected void initBinderFileBucket(WebDataBinder binder) { binder.setValidator(fileValidator); }
/** * @param object 需要校验的队形 * @param <T> * @return * @throws ConstraintViolationException 约束违反异常 */ public static <T>T validate(T object) throws BindException { WebDataBinder binder = new WebDataBinder(object, object.getClass().getSimpleName()); validator.validate(object, binder.getBindingResult()); if (binder.getBindingResult().hasErrors() ) { throw new BindException(binder.getBindingResult()); } return object; }
/** * 校验对象的某个参数 * @param object 需要校验的对象 * @param propertyName 校验的参数 * @param <T> * @return * @throws BindException 字段绑定异常 */ public static <T>T validateProperty(T object, String propertyName) throws BindException { WebDataBinder binder = new WebDataBinder(object, object.getClass().getSimpleName()); validator.validateProperty(object, propertyName, binder.getBindingResult()); if (binder.getBindingResult().hasErrors() ) { throw new BindException(binder.getBindingResult()); } return object; }
@InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat( TodoListUtils.DATE_FORMAT); binder.registerCustomEditor(Date.class, new CustomDateEditor( dateFormat, false)); binder.registerCustomEditor(Priority.class, new TodoPriorityPropertyEditor()); }
@InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(UseCase3Pk.class, new PropertyEditorSupport() { @Override public String getAsText() { return getValue().toString(); } @Override public void setAsText(String text) throws IllegalArgumentException { setValue(UseCase3Pk.fromString(text)); } }); }