/** * Rest handler for validation errors. * @param ex handled exception * @return rest result */ @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public ResponseEntity<?> processHandler(MethodArgumentNotValidException ex) { BindingResult bindingResult = ex.getBindingResult(); List<FieldError> fieldErrors = bindingResult.getFieldErrors(); List<FieldErrorDto> fieldErrorDtos = fieldErrors.stream() .map(FieldErrorDto::new) .collect(Collectors.toList()); ValidationResultDto validationResultDto = new ValidationResultDto(); validationResultDto.setFieldErrors(fieldErrorDtos); return ResponseEntity.badRequest().body(validationResultDto); }
/** * 只将第一个错误抛出异常 * @param errResult * @return */ public static ValidationException build(BindingResult errResult) { FieldError fieldError = errResult.getFieldError(); String code = fieldError.getCode(); String field = fieldError.getField(); String message = fieldError.getDefaultMessage(); message = "`" + field + "` " + message; ErrorCode errorCode = ErrorCodeConfig.PARAM_INVAILD; switch (code) { case "NotNull": errorCode = ErrorCodeConfig.PARAM_NOTFOUND; break; case "Length": errorCode = ErrorCodeConfig.PARAM_INVAILD_LENGTH; break; default: break; } return new ValidationException(errorCode, message); }
/** * Rest handler for validation errors. * @param ex handled exception * @return rest result */ @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public ResponseEntity<?> processHandler(MethodArgumentNotValidException ex) { BindingResult bindingResult = ex.getBindingResult(); List<FieldError> fieldErrors = bindingResult.getFieldErrors(); List<FieldErrorDto> fieldErrorDtos = fieldErrors.stream() .map(FieldErrorDto::new) .collect(Collectors.toList()); ValidationResultDto validationResultDto = new ValidationResultDto(); validationResultDto.setFieldErrors(fieldErrorDtos); LOGGER.error("VALIDATION ERROR: " + ex.getMessage()); return ResponseEntity.badRequest().body(validationResultDto); }
@ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ErrorVM processValidationError(MethodArgumentNotValidException ex) { BindingResult result = ex.getBindingResult(); List<FieldError> fieldErrors = result.getFieldErrors(); ErrorVM dto = new ErrorVM(ErrorConstants.ERR_VALIDATION); for (FieldError fieldError : fieldErrors) { dto.add(fieldError.getObjectName(), fieldError.getField(), fieldError.getCode()); } return dto; }
private BaseMatcher<BindException> getMatcher(String message, String field) { return new BaseMatcher<BindException>() { @Override public void describeTo(Description description) { } @Override public boolean matches(Object item) { BindException ex = (BindException) ((Exception) item).getCause(); ObjectError error = ex.getAllErrors().get(0); boolean messageMatches = message.equals(error.getDefaultMessage()); if (field == null) { return messageMatches; } String fieldErrors = ((FieldError) error).getField(); return messageMatches && fieldErrors.equals(field); } }; }
/** * adds new shopping list for the current user * * @param newList * ShoppingListDTO with basic information about new list (must * include list name) */ @RequestMapping(value = "/list", method = RequestMethod.POST) public String addList(Principal principal, @Valid @ModelAttribute("newList") ShoppingListDTO newList, BindingResult binding, RedirectAttributes attr, HttpSession session) { LOGGER.debug("addList() method of MvcController called for user: {}", principal.getName()); if(!binding.hasErrors()) repositoryService.addShoppingListToUserByName(principal.getName(), newList.getListName()); else { attr.addFlashAttribute("org.springframework.validation.BindingResult.newList", binding); attr.addFlashAttribute("newList", newList); for(FieldError ferr:binding.getFieldErrors()) { LOGGER.info("addList(): field error: " + ferr.getDefaultMessage()); } } return "redirect:/list"; }
@SuppressWarnings("unchecked") private <T extends ObjectError> T escapeObjectError(T source) { if (source == null) { return null; } if (source instanceof FieldError) { FieldError fieldError = (FieldError) source; Object value = fieldError.getRejectedValue(); if (value instanceof String) { value = HtmlUtils.htmlEscape((String) value); } return (T) new FieldError( fieldError.getObjectName(), fieldError.getField(), value, fieldError.isBindingFailure(), fieldError.getCodes(), fieldError.getArguments(), HtmlUtils.htmlEscape(fieldError.getDefaultMessage())); } else { return (T) new ObjectError( source.getObjectName(), source.getCodes(), source.getArguments(), HtmlUtils.htmlEscape(source.getDefaultMessage())); } }
private void addFieldError(String objectName, String fieldName, String fieldValue, String errorCode, BindingResult result) { LOGGER.debug( "Adding field error object's: {} field: {} with error code: {}", objectName, fieldName, errorCode ); FieldError error = new FieldError( objectName, fieldName, fieldValue, false, new String[]{errorCode}, new Object[]{}, errorCode ); result.addError(error); LOGGER.debug("Added field error: {} to binding result: {}", error, result); }
/** * 员工保存 * @param employee * @return * 1.支持JSR303校验 * 2.导入Hibernate-Validator */ @RequestMapping(value="emp",method=RequestMethod.POST) //定义为POST请求 @ResponseBody public Msg saveEmp(@Valid Employee employee,BindingResult result){ if(result.hasErrors()){ Map<String,Object> map= new HashMap<>(); //校验失败,应该返回失败,在模态框中显示校验失败的信息 List<FieldError> errors = result.getFieldErrors(); //提取出错误信息 for(FieldError fieldError : errors){ System.out.println("错误的字段名:"+ fieldError.getField()); System.out.println("错误信息:"+fieldError.getDefaultMessage()); map.put(fieldError.getField(), fieldError.getDefaultMessage()); } return Msg.fail().add("errorFields", map); }else{ employeeService.saveEmp(employee); return Msg.success(); } }
@RequestMapping(value = { "/newuser" }, method = RequestMethod.POST) public String saveUser(@Valid User user, BindingResult result, ModelMap model) { if (result.hasErrors()) { return "registration"; } if(!userService.isUserSSOUnique(user.getId(), user.getSsoId())){ FieldError ssoError =new FieldError("user","ssoId",messageSource.getMessage("non.unique.ssoId", new String[]{user.getSsoId()}, Locale.getDefault())); result.addError(ssoError); return "registration"; } userService.saveUser(user); model.addAttribute("success", "Użytkownik " + user.getFirstName() + " "+ user.getLastName() + " został zarejestrowany."); model.addAttribute("loggedinuser", getPrincipal()); return "registrationsuccess"; }
@RequestMapping(value = { "/register" }, method = RequestMethod.POST) public String saveUserAccount(@Valid User user, BindingResult result, ModelMap model) { if (result.hasErrors() || result==null) { return "register"; } if(!userService.isUserSSOUnique(user.getId(), user.getSsoId())){ FieldError ssoError =new FieldError("user","ssoId",messageSource.getMessage("non.unique.ssoId", new String[]{user.getSsoId()}, Locale.getDefault())); result.addError(ssoError); return "register"; } userService.saveCustomerAccount(user); model.addAttribute("success", "Użytkownik " + user.getFirstName() + " "+ user.getLastName() + " został zarejestrowany."); model.addAttribute("loggedinuser", getPrincipal()); return "registrationsuccess"; }
@ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(value = HttpStatus.BAD_REQUEST) @ResponseBody public XAPIErrorInfo handleMethodArgumentNotValidException(final HttpServletRequest request, MethodArgumentNotValidException e) { final List<String> errorMessages = new ArrayList<String>(); for (ObjectError oe : e.getBindingResult().getAllErrors()) { if (oe instanceof FieldError) { final FieldError fe = (FieldError)oe; final String msg = String.format( "Field error in object '%s' on field '%s': rejected value [%s].", fe.getObjectName(), fe.getField(), fe.getRejectedValue()); errorMessages.add(msg); } else { errorMessages.add(oe.toString()); } } final XAPIErrorInfo result = new XAPIErrorInfo(HttpStatus.BAD_REQUEST, request, errorMessages); this.logException(e); this.logError(result); return result; }
@RequestMapping(value = "/addEntry", method = RequestMethod.POST) public String addEntry(@Valid @ModelAttribute EntryModel newEntryModel, BindingResult bindingResult, Model model) { if (bindingResult.hasErrors()) { String errorMessage = ""; for (FieldError fieldError : bindingResult.getFieldErrors()) { errorMessage += fieldError.getField() + " is invalid<br>"; } model.addAttribute("errorMessage", errorMessage); return "forward:/entry"; } //if (newEntryModel != null) { //model.addAttribute("errorMessage", "Entry already exists!<br>"); //} else { newEntryModel.setDate(new Timestamp(System.currentTimeMillis())); UserModel user = null; Authentication auth = SecurityContextHolder.getContext().getAuthentication(); List<UserModel> userList = userRepository.findByUsername(auth.getName()); user = userList.get(0); newEntryModel.setUser(user); newEntryModel.setSubforum(null); entryRepository.save(newEntryModel); return "forum/entry"; }
@RequestMapping(value = "/addTopic", method = RequestMethod.POST) public String addTopic(@Valid @ModelAttribute ForumModel newForumModel, BindingResult bindingResult, Model model) { if (bindingResult.hasErrors()) { String errorMessage = ""; for (FieldError fieldError : bindingResult.getFieldErrors()) { errorMessage += fieldError.getField() + " is invalid<br>"; } model.addAttribute("errorMessage", errorMessage); return "/forum"; } forumRepository.save(newForumModel); return "/forum"; }
@Test public void testSpringValidation() throws Exception { LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.afterPropertiesSet(); ValidPerson person = new ValidPerson(); BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person"); validator.validate(person, result); assertEquals(2, result.getErrorCount()); FieldError fieldError = result.getFieldError("name"); assertEquals("name", fieldError.getField()); List<String> errorCodes = Arrays.asList(fieldError.getCodes()); assertEquals(4, errorCodes.size()); assertTrue(errorCodes.contains("NotNull.person.name")); assertTrue(errorCodes.contains("NotNull.name")); assertTrue(errorCodes.contains("NotNull.java.lang.String")); assertTrue(errorCodes.contains("NotNull")); fieldError = result.getFieldError("address.street"); assertEquals("address.street", fieldError.getField()); errorCodes = Arrays.asList(fieldError.getCodes()); assertEquals(5, errorCodes.size()); assertTrue(errorCodes.contains("NotNull.person.address.street")); assertTrue(errorCodes.contains("NotNull.address.street")); assertTrue(errorCodes.contains("NotNull.street")); assertTrue(errorCodes.contains("NotNull.java.lang.String")); assertTrue(errorCodes.contains("NotNull")); }
@Test public void testSpringValidationWithErrorInSetElement() throws Exception { LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.afterPropertiesSet(); ValidPerson person = new ValidPerson(); person.getAddressSet().add(new ValidAddress()); BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person"); validator.validate(person, result); assertEquals(3, result.getErrorCount()); FieldError fieldError = result.getFieldError("name"); assertEquals("name", fieldError.getField()); fieldError = result.getFieldError("address.street"); assertEquals("address.street", fieldError.getField()); fieldError = result.getFieldError("addressSet[].street"); assertEquals("addressSet[].street", fieldError.getField()); }
@PostMapping(value = "/register") public String postRegister(HttpServletRequest request, @Valid @ModelAttribute("user") User user, BindingResult result, Model model) { if(!request.getParameter("password1").equals(request.getParameter("password"))) { result.addError(new FieldError("user", "password1", "Passwords don't match")); } if(userService.userExists(user.getUsername())) { result.addError(new FieldError("user", "username", "Username is already taken")); } UserValidator userValidator = new UserValidator(); userValidator.validate(user, result); if(result.hasErrors()) { model.addAttribute("errors", result); return "account/register"; } else { userService.createUser(user); return "redirect:/"; } }
@Test public void shouldCreateValidationErrorsForBindException() { BindingResult bindingResult = mock(BindingResult.class); ApiError someFieldError = testProjectApiErrors.getMissingExpectedContentApiError(); ApiError otherFieldError = testProjectApiErrors.getTypeConversionApiError(); List<ObjectError> errorsList = Arrays.<ObjectError>asList( new FieldError("someObj", "someField", someFieldError.getName()), new FieldError("otherObj", "otherField", otherFieldError.getName())); when(bindingResult.getAllErrors()).thenReturn(errorsList); BindException ex = new BindException(bindingResult); ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex); validateResponse(result, true, Arrays.asList( new ApiErrorWithMetadata(someFieldError, Pair.of("field", (Object)"someField")), new ApiErrorWithMetadata(otherFieldError, Pair.of("field", (Object)"otherField")) )); verify(bindingResult).getAllErrors(); }
private CangoResponseDto buildFailedResponse(BindingResult result) { StringBuilder stringBuilder = new StringBuilder(); List<FieldError> list = result.getFieldErrors(); for (FieldError fieldError : list) { stringBuilder.append(fieldError.getField()) .append(" : ") .append(fieldError.getRejectedValue()) .append("(") .append(fieldError.getDefaultMessage()) .append(")") .append(", "); } String failMessage = stringBuilder.deleteCharAt(stringBuilder.length() - 2).toString(); CangoResponseDto cangoResponseDto = new CangoResponseDto(); cangoResponseDto.setStatus(CangoRspStatus.FAILURE) .setFailMsg(failMessage); return cangoResponseDto; }
@Override protected FailureAnalysis analyze(Throwable rootFailure, BindException cause) { if (CollectionUtils.isEmpty(cause.getFieldErrors())) { return null; } StringBuilder description = new StringBuilder( String.format("Binding to target %s failed:%n", cause.getTarget())); for (FieldError fieldError : cause.getFieldErrors()) { description.append(String.format("%n Property: %s", cause.getObjectName() + "." + fieldError.getField())); description.append( String.format("%n Value: %s", fieldError.getRejectedValue())); description.append( String.format("%n Reason: %s%n", fieldError.getDefaultMessage())); } return new FailureAnalysis(description.toString(), "Update your application's configuration", cause); }
@Test public void testNoRoutingKey() { try { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.register(Config.class); context.refresh(); context.close(); fail("BeanCreationException expected"); } catch (Exception e) { assertThat(e, instanceOf(BeanCreationException.class)); BindValidationException bindValidationException = (BindValidationException) e.getCause().getCause(); ValidationErrors validationErrors = bindValidationException.getValidationErrors(); FieldError fieldError = (FieldError) validationErrors.getAllErrors().get(0); assertThat(fieldError.getDefaultMessage(), containsString("routingKey or routingKeyExpression is required")); } }
/** * @param ex {@link MethodArgumentNotValidException} * @return Returns an object with a list of error fields */ @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public ValidationErrorDTO processValidationError(final MethodArgumentNotValidException ex) { final BindingResult result = ex.getBindingResult(); final List<FieldError> fieldErrors = result.getFieldErrors(); return processFieldErrors(fieldErrors); }
/** * @param fieldErrors List with fields containing errors. {@link FieldError} * @return Returns an object containing a list of error fields */ private ValidationErrorDTO processFieldErrors(final List<FieldError> fieldErrors) { final ValidationErrorDTO dto = new ValidationErrorDTO(); for (final FieldError fieldError: fieldErrors) { final String localizedErrorMessage = resolveLocalizedErrorMessage(fieldError); dto.addFieldError(fieldError.getField(), localizedErrorMessage); } return dto; }
@ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ErrorDTO processValidationError(MethodArgumentNotValidException ex) { BindingResult result = ex.getBindingResult(); List<FieldError> fieldErrors = result.getFieldErrors(); return processFieldErrors(fieldErrors); }
private ErrorDTO processFieldErrors(List<FieldError> fieldErrors) { ErrorDTO dto = new ErrorDTO(ErrorConstants.ERR_VALIDATION); for (FieldError fieldError : fieldErrors) { dto.add(fieldError.getObjectName(), fieldError.getField(), fieldError.getCode()); } return dto; }
@ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ErrorVM processValidationError(MethodArgumentNotValidException ex) { BindingResult result = ex.getBindingResult(); FieldErrorVM dto = new FieldErrorVM(ErrorConstants.ERR_VALIDATION, translate(ErrorConstants.ERR_VALIDATION)); for (FieldError fieldError : result.getFieldErrors()) { dto.add(fieldError.getObjectName(), fieldError.getField(), fieldError.getCode()); } for (ObjectError globalError : result.getGlobalErrors()) { dto.add(globalError.getObjectName(), globalError.getObjectName(), globalError.getCode()); } return dto; }
public static List<RestFieldError> toRestFieldErrorList(List<FieldError> errors) { List<RestFieldError> fieldErrors = new ArrayList<>(errors.size()); for (FieldError error : errors) { fieldErrors.add(new RestFieldError(error)); } return fieldErrors; }
/** * Registers given user if there is no user with this username and all data is valid * @param newUser AppUserDTO with details of the new user */ @RequestMapping(value="/register", method = RequestMethod.POST) public String register(@Valid @ModelAttribute AppUserDTO newUser, BindingResult binding, RedirectAttributes attr, HttpSession session) { LOGGER.debug("register(): registering user: {}", newUser.getUserName()); if(!binding.hasErrors()) { try{ repositoryService.addUser(newUser); attr.addFlashAttribute("registered", true); }catch(DuplicateUserException de) { LOGGER.debug("register(): duplicate user {}", newUser.getUserName()); String[] codes = new String[1]; codes[0] = "DuplicateUser"; binding.addError(new FieldError("newUser", "userName", newUser.getUserName(), false, codes, null, "*There is already an user with this name")); attr.addFlashAttribute("org.springframework.validation.BindingResult.newUser", binding); attr.addFlashAttribute("newUser", newUser); } } else { LOGGER.debug("register(): binding errors occured in the form: {}", newUser); attr.addFlashAttribute("org.springframework.validation.BindingResult.newUser", binding); attr.addFlashAttribute("newUser", newUser); for(FieldError ferr:binding.getFieldErrors()) { LOGGER.info("register(): field error: " + ferr.getDefaultMessage()); } } return "redirect:/register"; }
/** * @desc 根据BindingResult获取数据校验信息 * * @author liuliang * * @param br * @return */ public static Result getValidResult(BindingResult br){ if(!br.hasErrors()){ return ResultUtil.success(new Result()); }else{ List<FieldError> list = br.getFieldErrors(); StringBuilder sb = new StringBuilder(); for (FieldError e: list) { sb.append(e.getField()).append(":").append(e.getDefaultMessage()).append(";"); } String errorMessage = StringUtils.removeEnd(sb.toString(),";"); logger.error("参数异常,errorMessage:{}",errorMessage); return ResultUtil.fail(ErrorCode.REQUEST_PARA_ERROR,errorMessage,new Result()); } }
@ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ErrorVM processValidationError(MethodArgumentNotValidException ex) { BindingResult result = ex.getBindingResult(); List<FieldError> fieldErrors = result.getFieldErrors(); return processFieldErrors(fieldErrors); }
private ErrorVM processFieldErrors(List<FieldError> fieldErrors) { ErrorVM dto = new ErrorVM(ErrorConstants.ERR_VALIDATION); for (FieldError fieldError : fieldErrors) { dto.add(fieldError.getObjectName(), fieldError.getField(), fieldError.getCode()); } return dto; }
/** * This method will be called on form submission, handling POST request for * saving user in database. It also validates the user input */ @RequestMapping(value = {"/newuser"}, method = RequestMethod.POST) public String saveUser(@Valid AdmUser user, BindingResult result, ModelMap model) { if (result.hasErrors()) { return "registration"; } /* * Preferred way to achieve uniqueness of field [sso] should be implementing custom @Unique annotation * and applying it on field [sso] of Model class [User]. * * Below mentioned peace of code [if block] is to demonstrate that you can fill custom errors outside the validation * framework as well while still using internationalized messages. * */ if (!userService.isUserSSOUnique(user.getUserId(), user.getEmail())) { FieldError ssoError = new FieldError("user", "userId", messageSource.getMessage("non.unique.ssoId", new String[]{user.getEmail()}, Locale.getDefault())); result.addError(ssoError); return "registration"; } userService.saveUser(user); model.addAttribute("success", "User " + user.getFirstName() + " " + user.getLastName() + " registered successfully"); model.addAttribute("loggedinuser", getPrincipal()); //return "success"; return "registrationsuccess"; }
/** * This method will be called on form submission, handling POST request for * saving user in database. It also validates the user input */ @RequestMapping(value = {"/studentregistration"}, method = RequestMethod.POST) public String saveStudentUser(@Valid StudentUser user, BindingResult result, ModelMap model) { if (result.hasErrors()) { return "studentregistration"; } /* * Preferred way to achieve uniqueness of field [sso] should be implementing custom @Unique annotation * and applying it on field [sso] of Model class [User]. * * Below mentioned peace of code [if block] is to demonstrate that you can fill custom errors outside the validation * framework as well while still using internationalized messages. * */ if (!userService.isStudentUnique(user.getStudentUserId(), user.getEmail())) { FieldError ssoError = new FieldError("studentuser", "email", messageSource.getMessage("non.unique.ssoId", new String[]{user.getEmail()}, Locale.getDefault())); result.addError(ssoError); model.addAttribute("loggedinuser", getPrincipal()); return "studentregistration"; } userService.saveUser(user); model.addAttribute("success", "User " + user.getFirstName() + " " + user.getLastName() + " registered successfully"); model.addAttribute("loggedinuser", getPrincipal()); //return "success"; return "registrationsuccess"; }