Java 类org.springframework.validation.FieldError 实例源码

项目:meparty    文件:TestValidationHandler.java   
/**
 * 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);
}
项目:spring-rest-sample    文件:ValidationExceptionUtils.java   
/**
 * 只将第一个错误抛出异常
 * @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);
}
项目:meparty    文件:ValidationErrorHandler.java   
/**
 * 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);
}
项目:jhipster-microservices-example    文件:ExceptionTranslator.java   
@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;
}
项目:jhipster-microservices-example    文件:ExceptionTranslator.java   
@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;
}
项目:spring-security-oauth2-boot    文件:ResourceServerPropertiesTests.java   
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);
        }

    };
}
项目:Smart-Shopping    文件:MvcController.java   
/**
 * 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";
}
项目:lams    文件:EscapedErrors.java   
@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()));
    }
}
项目:gamesboard    文件:RegistrationController.java   
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);
}
项目:SSM_Employee    文件:EmployeeController.java   
/**
 * 员工保存
 * @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();
    }

}
项目:Webstore    文件:UserController.java   
@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";
}
项目:Webstore    文件:UserController.java   
@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";
}
项目:OpenLRW    文件:XAPIExceptionHandlerAdvice.java   
@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;
}
项目:SSM-    文件:EmployeeController.java   
/**
 * 员工保存
 * @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();
    }

}
项目:Towan    文件:ForumController.java   
@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";
}
项目:Towan    文件:ForumController.java   
@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";
}
项目:spring4-understanding    文件:ValidatorFactoryTests.java   
@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"));
}
项目:spring4-understanding    文件:ValidatorFactoryTests.java   
@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());
}
项目:spring4-understanding    文件:EscapedErrors.java   
@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()));
    }
}
项目:spring4-understanding    文件:ValidatorFactoryTests.java   
@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());
}
项目:pollistics    文件:AccountController.java   
@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:/";
    }
}
项目:backstopper    文件:ConventionBasedSpringValidationErrorToApiErrorHandlerListenerTest.java   
@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();
}
项目:cango    文件:ServerAction.java   
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;
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:BindFailureAnalyzer.java   
@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);
}
项目:rabbit    文件:RabbitSinkInvalidConfigTests.java   
@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"));
    }
}
项目:jhipster-microservices-example    文件:ExceptionTranslator.java   
@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;
}
项目:MTC_Labrat    文件:ExceptionTranslator.java   
@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;
}
项目:REST-Web-Services    文件:ErrorFieldsExceptionHandler.java   
/**
 * @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);
}
项目:REST-Web-Services    文件:ErrorFieldsExceptionHandler.java   
/**
 * @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;
}
项目:buenojo    文件:ExceptionTranslator.java   
@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);
}
项目:buenojo    文件:ExceptionTranslator.java   
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;
}
项目:xm-commons    文件:ExceptionTranslator.java   
@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;
}
项目:WeatherSystem    文件:BaseRestException.java   
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;
}
项目:Smart-Shopping    文件:MvcController.java   
/**
 * 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";
}
项目:TITAN    文件:ValidatorUtil.java   
/**
 * @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());
    }
   }
项目:Armory    文件:ExceptionTranslator.java   
@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);
}
项目:Armory    文件:ExceptionTranslator.java   
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;
}
项目:Armory    文件:ExceptionTranslator.java   
@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;
}
项目:FeedbackCollectionAndMgmtSystem    文件:AppController.java   
/**
  * 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";
 }
项目:FeedbackCollectionAndMgmtSystem    文件:AppController.java   
/**
  * 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";
 }