Java Code Examples for org.springframework.validation.BindingResult#hasFieldErrors()

The following examples show how to use org.springframework.validation.BindingResult#hasFieldErrors() . 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: PostBackManager.java    From sinavi-jfw with Apache License 2.0 6 votes vote down vote up
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 2
Source File: UserRegistrationController.java    From maven-framework-project with MIT License 6 votes vote down vote up
@RequestMapping(value = "/userRegistration.htm", method = RequestMethod.POST)
public String post(@Valid @ModelAttribute UserForm userForm,
                   BindingResult result,
                   final RedirectAttributes redirectAttributes,
                   HttpServletRequest request) {
    log.debug("userRegistration: " + userForm);
    if (request.getRemoteUser() != null) {
        return "redirect:j_spring_security_logout";
    }
    if (result.hasFieldErrors()) {
        redirectAttributes.addFlashAttribute("error", true);
        redirectAttributes.addFlashAttribute("errors", result.getFieldErrors());
        return "redirect:userRegistration.htm";
    }
    try {
        userService.submitForApproval(userForm);
    } catch (Exception e) {
        redirectAttributes.addFlashAttribute("error", true);
        result.rejectValue("userName", null, e.getMessage());
        redirectAttributes.addFlashAttribute("errors", result.getFieldErrors());
        return "redirect:userRegistration.htm";
    }

    redirectAttributes.addFlashAttribute("msg", "A request has been made to the admin to approve your account");
    return "redirect:login.htm";
}
 
Example 3
Source File: ModelResultMatchers.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Assert a field error code for a model attribute using a {@link org.hamcrest.Matcher}.
 * @since 4.1
 */
public <T> ResultMatcher attributeHasFieldErrorCode(final String name, final String fieldName,
		final Matcher<? super String> matcher) {

	return new ResultMatcher() {
		@Override
		public void match(MvcResult mvcResult) throws Exception {
			ModelAndView mav = getModelAndView(mvcResult);
			BindingResult result = getBindingResult(mav, name);
			assertTrue("No errors for attribute: [" + name + "]", result.hasErrors());

			boolean hasFieldErrors = result.hasFieldErrors(fieldName);
			assertTrue("No errors for field: [" + fieldName + "] of attribute [" + name + "]", hasFieldErrors);

			String code = result.getFieldError(fieldName).getCode();
			assertThat("Field name '" + fieldName + "' of attribute '" + name + "'", code, matcher);
		}
	};
}
 
Example 4
Source File: ModelResultMatchers.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Assert a field error code for a model attribute using exact String match.
 * @since 4.1
 */
public ResultMatcher attributeHasFieldErrorCode(final String name, final String fieldName, final String error) {
	return new ResultMatcher() {
		public void match(MvcResult mvcResult) throws Exception {
			ModelAndView mav = getModelAndView(mvcResult);
			BindingResult result = getBindingResult(mav, name);
			assertTrue("No errors for attribute: [" + name + "]", result.hasErrors());

			boolean hasFieldErrors = result.hasFieldErrors(fieldName);
			assertTrue("No errors for field: [" + fieldName + "] of attribute [" + name + "]", hasFieldErrors);

			String code = result.getFieldError(fieldName).getCode();
			assertTrue("Expected error code '" + error + "' but got '" + code + "'", code.equals(error));
		}
	};
}
 
Example 5
Source File: ServletAnnotationControllerHandlerMethodTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
@RequestMapping("/myPath.do")
public String myHandle(@ModelAttribute("myCommand") @Valid TestBean tb, BindingResult errors, ModelMap model) {
	if (!errors.hasFieldErrors("validCountry")) {
		throw new IllegalStateException("Declarative validation not applied");
	}
	return super.myHandle(tb, errors, model);
}
 
Example 6
Source File: PasswordResetController.java    From wallride with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/{token}", method = RequestMethod.PUT)
public String reset(
		@PathVariable String token,
		@Validated @ModelAttribute(FORM_MODEL_KEY) PasswordResetForm form,
		BindingResult errors,
		BlogLanguage blogLanguage,
		RedirectAttributes redirectAttributes) {
	redirectAttributes.addFlashAttribute(FORM_MODEL_KEY, form);
	redirectAttributes.addFlashAttribute(ERRORS_MODEL_KEY, errors);

	PasswordResetToken passwordResetToken = userService.getPasswordResetToken(token);
	if (passwordResetToken == null) {
		redirectAttributes.addFlashAttribute(INVALID_PASSOWRD_RESET_LINK_ATTR_NAME, true);
		return "redirect:/password-reset";
	}
	LocalDateTime now = LocalDateTime.now();
	if (now.isAfter(passwordResetToken.getExpiredAt())) {
		redirectAttributes.addFlashAttribute(INVALID_PASSOWRD_RESET_LINK_ATTR_NAME, true);
		return "redirect:/password-reset";
	}

	if (!errors.hasFieldErrors("newPassword")) {
		if (!ObjectUtils.nullSafeEquals(form.getNewPassword(), form.getNewPasswordRetype())) {
			errors.rejectValue("newPasswordRetype", "MatchRetype");
		}
	}
	if (errors.hasFieldErrors("newPassword*")) {
		return "redirect:/password-reset/{token}";
	}

	PasswordUpdateRequest request = new PasswordUpdateRequest()
			.withUserId(passwordResetToken.getUser().getId())
			.withPassword(form.getNewPassword())
			.withLanguage(blogLanguage.getLanguage());
	userService.updatePassword(request, passwordResetToken);

	redirectAttributes.getFlashAttributes().clear();
	return "redirect:/login";
}
 
Example 7
Source File: CommentRestController.java    From wallride with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public CommentSavedModel update(
		@PathVariable long id,
		@Validated CommentForm form,
		BindingResult result,
		AuthorizedUser authorizedUser) throws BindException {
	if (result.hasFieldErrors("content")) {
		throw new BindException(result);
	}
	CommentUpdateRequest request = form.toCommentUpdateRequest(id);
	Comment comment = commentService.updateComment(request, authorizedUser);
	return new CommentSavedModel(comment);
}
 
Example 8
Source File: ValidatorUtil.java    From cloudstreetmarket.com with GNU General Public License v3.0 5 votes vote down vote up
public static void raiseFirstError(BindingResult result) {
if (result.hasFieldErrors()) {
          throw new IllegalArgumentException(result.getFieldError().getDefaultMessage());
      }
else if (result.hasGlobalErrors()) {
          throw new IllegalArgumentException(result.getGlobalError().getDefaultMessage());
      }
else if (result.hasErrors()) {
          throw new IllegalArgumentException(result.getAllErrors().get(0).getCode());
      }
}
 
Example 9
Source File: IndexPicController.java    From wetech-cms with MIT License 5 votes vote down vote up
@ResponseBody
@RequestMapping(value = "/indexPic/add", method = RequestMethod.POST)
public ResponseData add(@Validated IndexPic indexPic, HttpSession session, BindingResult br, MultipartFile image) {
	if (br.hasFieldErrors()) {
		return ResponseData.FAILED_NO_DATA;
	}
	// 处理图片流数据
	String realPath = session.getServletContext().getRealPath("");
	String oldName = image.getOriginalFilename();
	String newName = new Date().getTime() + "." + FilenameUtils.getExtension(oldName);

	try {
		// 对图片流进行压缩,生成文件和缩略图保存到指定文件夹
		writeIndexPic(realPath, newName, image.getInputStream());
	} catch (IOException e) {
		e.printStackTrace();
		return new ResponseData(false, e.getMessage());
	}

	indexPic.setOldName(oldName);
	indexPic.setNewName(newName);
	indexPicService.add(indexPic);
	if (indexPic.getStatus() != 0) {
		indexService.generateBody();
	}
	return ResponseData.SUCCESS_NO_DATA;
}
 
Example 10
Source File: ModelResultMatchers.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Assert the given model attribute field(s) have errors.
 */
public ResultMatcher attributeHasFieldErrors(final String name, final String... fieldNames) {
	return new ResultMatcher() {
		@Override
		public void match(MvcResult mvcResult) throws Exception {
			ModelAndView mav = getModelAndView(mvcResult);
			BindingResult result = getBindingResult(mav, name);
			assertTrue("No errors for attribute: [" + name + "]", result.hasErrors());
			for (final String fieldName : fieldNames) {
				boolean hasFieldErrors = result.hasFieldErrors(fieldName);
				assertTrue("No errors for field: [" + fieldName + "] of attribute [" + name + "]", hasFieldErrors);
			}
		}
	};
}
 
Example 11
Source File: ServletAnnotationControllerHandlerMethodTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
@RequestMapping("/myPath.do")
public String myHandle(@ModelAttribute("myCommand") @Valid TestBean tb, BindingResult errors, ModelMap model) {
	if (!errors.hasFieldErrors("sex")) {
		throw new IllegalStateException("requiredFields not applied");
	}
	return super.myHandle(tb, errors, model);
}
 
Example 12
Source File: ServletAnnotationControllerHandlerMethodTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@RequestMapping("/myPath.do")
public String myHandle(@ModelAttribute("myCommand") @Valid TestBean tb, BindingResult errors, ModelMap model) {
	if (!errors.hasFieldErrors("validCountry")) {
		throw new IllegalStateException("Declarative validation not applied");
	}
	return super.myHandle(tb, errors, model);
}
 
Example 13
Source File: ServletAnnotationControllerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
@RequestMapping("/myPath.do")
public String myHandle(@ModelAttribute("myCommand") @MyValid TestBean tb, BindingResult errors, ModelMap model) {
	if (!errors.hasFieldErrors("sex")) {
		throw new IllegalStateException("requiredFields not applied");
	}
	return super.myHandle(tb, errors, model);
}
 
Example 14
Source File: ServletAnnotationControllerTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
@RequestMapping("/myPath.do")
public String myHandle(@ModelAttribute("myCommand") @Validated(MyGroup.class) TestBean tb, BindingResult errors, ModelMap model) {
	if (!errors.hasFieldErrors("validCountry")) {
		throw new IllegalStateException("Declarative validation not applied");
	}
	return super.myHandle(tb, errors, model);
}
 
Example 15
Source File: BaseController.java    From softservice with MIT License 5 votes vote down vote up
/**
 * 参数的合法性校验
 * @param result
 */
protected void validate(BindingResult result){
    if(result.hasFieldErrors()){
        List<FieldError> errorList = result.getFieldErrors();
        errorList.stream().forEach(item -> Assert.isTrue(false,item.getDefaultMessage()));
    }
}
 
Example 16
Source File: BaseController.java    From wingcloud with Apache License 2.0 5 votes vote down vote up
/**
 * 接口输入参数合法性校验
 *
 * @param result
 */
protected void validate(BindingResult result){
    if(result.hasFieldErrors()){
        List<FieldError> errorList = result.getFieldErrors();
        errorList.stream().forEach(item -> Assert.isTrue(false,item.getDefaultMessage()));
    }
}
 
Example 17
Source File: ModelResultMatchers.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Assert the given model attribute field(s) have errors.
 */
public ResultMatcher attributeHasFieldErrors(final String name, final String... fieldNames) {
	return mvcResult -> {
		ModelAndView mav = getModelAndView(mvcResult);
		BindingResult result = getBindingResult(mav, name);
		assertTrue("No errors for attribute '" + name + "'", result.hasErrors());
		for (final String fieldName : fieldNames) {
			boolean hasFieldErrors = result.hasFieldErrors(fieldName);
			assertTrue("No errors for field '" + fieldName + "' of attribute '" + name + "'", hasFieldErrors);
		}
	};
}
 
Example 18
Source File: ServletAnnotationControllerHandlerMethodTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@RequestMapping("/myPath.do")
public String myHandle(@ModelAttribute("myCommand") @Valid TestBean tb, BindingResult errors, ModelMap model) {
	if (!errors.hasFieldErrors("sex")) {
		throw new IllegalStateException("requiredFields not applied");
	}
	return super.myHandle(tb, errors, model);
}
 
Example 19
Source File: ServletAnnotationControllerHandlerMethodTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@RequestMapping("/myPath.do")
public String myHandle(@ModelAttribute("myCommand") @Valid TestBean tb, BindingResult errors, ModelMap model) {
	if (!errors.hasFieldErrors("validCountry")) {
		throw new IllegalStateException("Declarative validation not applied");
	}
	return super.myHandle(tb, errors, model);
}
 
Example 20
Source File: ServletAnnotationControllerHandlerMethodTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@RequestMapping("/myPath.do")
public String myHandle(@ModelAttribute("myCommand") @Valid TestBean tb, BindingResult errors, ModelMap model) {
	if (!errors.hasFieldErrors("sex")) {
		throw new IllegalStateException("requiredFields not applied");
	}
	return super.myHandle(tb, errors, model);
}