Java Code Examples for org.springframework.validation.BindException#getBindingResult()
The following examples show how to use
org.springframework.validation.BindException#getBindingResult() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TdsErrorHandling.java From tds with BSD 3-Clause "New" or "Revised" License | 6 votes |
@ExceptionHandler(BindException.class) public ResponseEntity<String> handle(BindException ex) { BindingResult validationResult = ex.getBindingResult(); List<ObjectError> errors = validationResult.getAllErrors(); Formatter f = new Formatter(); f.format("Validation errors: "); for (ObjectError err : errors) { f.format(" %s%n", err.getDefaultMessage()); } logger.warn(f.toString(), ex); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentType(MediaType.TEXT_PLAIN); return new ResponseEntity<>(f.toString(), responseHeaders, HttpStatus.BAD_REQUEST); }
Example 2
Source File: LogicAdvice.java From api-boot with Apache License 2.0 | 6 votes |
/** * @param e * @return * @Valid注解会验证属性, 不通过会先交给BindingResult, * 如果没有这个参数则会抛出异常BindException, * @ExceptionHandler捕捉到异常则会进入该方法 */ @ExceptionHandler(BindException.class) @ResponseStatus(HttpStatus.OK) public ApiBootResult illegalParamsExceptionHandler(BindException e) { BindingResult result = e.getBindingResult(); //获取错误字段集合 List<FieldError> fieldErrors = result.getFieldErrors(); //错误消息集合 //JSONObject msg = new JSONObject(); StringBuffer errorMsg = new StringBuffer(); for (int i = 0; i < fieldErrors.size(); i++) { FieldError fieldError = fieldErrors.get(i); //获取错误信息 String errorMessage = resolveLocalErrorMessage(fieldError); //添加到错误消息 errorMsg.append(errorMessage + (i == fieldErrors.size() - 1 ? "" : " | ")); } return ApiBootResult.builder().errorMessage(errorMsg.toString()).build(); }
Example 3
Source File: PostBackManager.java From sinavi-jfw with Apache License 2.0 | 6 votes |
private static void saveValidationMessage(BindException e) { PostBack.Action action = getPostBackAction(e); BindingResult br = e.getBindingResult(); String modelName = e.getObjectName(); if (br != null && br.hasFieldErrors()) { List<FieldError> fieldErrors = br.getFieldErrors(); for (FieldError fieldError : fieldErrors) { String msg = detectValidationMessage(action, fieldError); DispatchType dispatchType = getDispatchType(e); switch(dispatchType) { case JSP: case FORWARD: getMessageContext().saveValidationMessageToRequest(msg, fieldError.getField(), fieldError.getCodes()[3], modelName); break; case REDIRECT: getMessageContext().saveValidationMessageToFlash(msg, fieldError.getField(), fieldError.getCodes()[3], modelName); break; default: throw new InternalException(PostBackManager.class, "E-POSTBACK#0001"); } } } }
Example 4
Source File: PostBack.java From sinavi-jfw with Apache License 2.0 | 6 votes |
/** * <p> * コンストラクタ。{@code PostBack}インスタンスを生成します。 * </p> * @param t ポストバックのトリガーとなった例外 */ public PostBack(Throwable t) { this.t = t; if (t instanceof BindException) { BindException be = (BindException)t; this.exceptionType = be.getClass(); this.modelName = be.getObjectName(); this.model = be.getTarget(); this.bindingResult = be.getBindingResult(); } else { this.exceptionType = t.getClass(); this.modelName = null; this.model = null; this.bindingResult = null; } }
Example 5
Source File: GlobalDefaultExceptionHandler.java From unified-dispose-springboot with Apache License 2.0 | 5 votes |
/** * BindException 参数错误异常 */ @ExceptionHandler(BindException.class) public Result handleBindException(BindException e) throws Throwable { errorDispose(e); outPutError(BindException.class, CommonErrorCode.PARAM_ERROR, e); BindingResult bindingResult = e.getBindingResult(); return getBindResultDTO(bindingResult); }
Example 6
Source File: ExceptionTranslator.java From youran with Apache License 2.0 | 5 votes |
/** * param参数校验失败 * * @param ex * @return */ @ExceptionHandler(BindException.class) @ResponseBody public ResponseEntity<ReplyVO> processValidationError(BindException ex) { BindingResult result = ex.getBindingResult(); return processBindingResult(result); }
Example 7
Source File: ModelAttributeMethodProcessor.java From spring-analysis-note with MIT License | 4 votes |
/** * 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 @Nullable public final Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer, NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception { Assert.state(mavContainer != null, "ModelAttributeMethodProcessor requires ModelAndViewContainer"); Assert.state(binderFactory != null, "ModelAttributeMethodProcessor requires WebDataBinderFactory"); String name = ModelFactory.getNameForParameter(parameter); ModelAttribute ann = parameter.getParameterAnnotation(ModelAttribute.class); if (ann != null) { mavContainer.setBinding(name, ann.binding()); } Object attribute = null; BindingResult bindingResult = null; if (mavContainer.containsAttribute(name)) { attribute = mavContainer.getModel().get(name); } else { // Create attribute instance try { attribute = createAttribute(name, parameter, binderFactory, webRequest); } catch (BindException ex) { if (isBindExceptionRequired(parameter)) { // No BindingResult parameter -> fail with BindException throw ex; } // Otherwise, expose null/empty value and associated BindingResult if (parameter.getParameterType() == Optional.class) { attribute = Optional.empty(); } bindingResult = ex.getBindingResult(); } } if (bindingResult == null) { // Bean property binding and validation; // skipped in case of binding failure on construction. WebDataBinder binder = binderFactory.createBinder(webRequest, attribute, name); if (binder.getTarget() != null) { if (!mavContainer.isBindingDisabled(name)) { bindRequestParameters(binder, webRequest); } validateIfApplicable(binder, parameter); if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) { throw new BindException(binder.getBindingResult()); } } // Value type adaptation, also covering java.util.Optional if (!parameter.getParameterType().isInstance(attribute)) { attribute = binder.convertIfNecessary(binder.getTarget(), parameter.getParameterType(), parameter); } bindingResult = binder.getBindingResult(); } // Add resolved attribute and BindingResult at the end of the model Map<String, Object> bindingResultModel = bindingResult.getModel(); mavContainer.removeAttributes(bindingResultModel); mavContainer.addAllAttributes(bindingResultModel); return attribute; }
Example 8
Source File: ModelAttributeMethodProcessor.java From java-technology-stack with MIT License | 4 votes |
/** * 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 @Nullable public final Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer, NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception { Assert.state(mavContainer != null, "ModelAttributeMethodProcessor requires ModelAndViewContainer"); Assert.state(binderFactory != null, "ModelAttributeMethodProcessor requires WebDataBinderFactory"); String name = ModelFactory.getNameForParameter(parameter); ModelAttribute ann = parameter.getParameterAnnotation(ModelAttribute.class); if (ann != null) { mavContainer.setBinding(name, ann.binding()); } Object attribute = null; BindingResult bindingResult = null; if (mavContainer.containsAttribute(name)) { attribute = mavContainer.getModel().get(name); } else { // Create attribute instance try { attribute = createAttribute(name, parameter, binderFactory, webRequest); } catch (BindException ex) { if (isBindExceptionRequired(parameter)) { // No BindingResult parameter -> fail with BindException throw ex; } // Otherwise, expose null/empty value and associated BindingResult if (parameter.getParameterType() == Optional.class) { attribute = Optional.empty(); } bindingResult = ex.getBindingResult(); } } if (bindingResult == null) { // Bean property binding and validation; // skipped in case of binding failure on construction. WebDataBinder binder = binderFactory.createBinder(webRequest, attribute, name); if (binder.getTarget() != null) { if (!mavContainer.isBindingDisabled(name)) { bindRequestParameters(binder, webRequest); } validateIfApplicable(binder, parameter); if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) { throw new BindException(binder.getBindingResult()); } } // Value type adaptation, also covering java.util.Optional if (!parameter.getParameterType().isInstance(attribute)) { attribute = binder.convertIfNecessary(binder.getTarget(), parameter.getParameterType(), parameter); } bindingResult = binder.getBindingResult(); } // Add resolved attribute and BindingResult at the end of the model Map<String, Object> bindingResultModel = bindingResult.getModel(); mavContainer.removeAttributes(bindingResultModel); mavContainer.addAllAttributes(bindingResultModel); return attribute; }