Java Code Examples for org.springframework.validation.BindingResult#addError()
The following examples show how to use
org.springframework.validation.BindingResult#addError() .
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: CheckoutController.java From market with MIT License | 6 votes |
@RequestMapping(value = "/payment", method = RequestMethod.POST) public String postPayment( Principal principal, Model model, @Valid CreditCardDTO creditCard, BindingResult bindingResult ) { if (bindingResult.hasErrors()) return CHECKOUT_PAYMENT; String login = principal.getName(); try { Order order = orderService.createUserOrder(login, marketProperties.getDeliveryCost(), creditCard.getNumber()); model.addAttribute("createdOrder", orderDtoAssembler.toModel(order)); return "redirect:/" + CHECKOUT_CONFIRMATION; } catch (EmptyCartException ex) { bindingResult.addError(ex.getFieldError()); return CHECKOUT_PAYMENT; } }
Example 2
Source File: ProblemExceptionResponseGeneratorTest.java From molgenis with GNU Lesser General Public License v3.0 | 6 votes |
@Test void testCreateExceptionResponseInputInvalidObjectErrorCoded() { String errorCode = "MYERR01"; String errorMessage = "My error message"; CodedRuntimeException wrappedException = mock(CodedRuntimeException.class); when(wrappedException.getErrorCode()).thenReturn(errorCode); when(wrappedException.getLocalizedMessage()).thenReturn(errorMessage); ObjectError objectError = new ObjectError("MyChildObject0", "MyDefaultMessage0"); objectError.wrap(wrappedException); BindingResult bindingResult = new MapBindingResult(emptyMap(), "MyObject"); bindingResult.addError(objectError); BindException bindException = new BindException(bindingResult); HttpStatus httpStatus = HttpStatus.BAD_REQUEST; ResponseEntity<Problem> problemResponse = problemExceptionResponseGenerator.createExceptionResponse(bindException, httpStatus, false); assertEquals(httpStatus, problemResponse.getStatusCode()); Problem problem = problemResponse.getBody(); assertTrue(problem.getType().toString().endsWith("/input-invalid")); assertEquals( singletonList(builder().setErrorCode(errorCode).setDetail(errorMessage).build()), problem.getErrors()); }
Example 3
Source File: CartController.java From market with MIT License | 6 votes |
@RequestMapping(method = RequestMethod.POST) public String updateCartByForm( Model model, Principal principal, @Valid @ModelAttribute("cartItem") CartItemDTO cartItemDto, BindingResult bindingResult, @ModelAttribute(value = "cart") CartDTO cartDto ) { if (bindingResult.hasErrors()) return CART_BASE; if (!isAuthorized(principal)) { CartDTO handledCartDto = updateGuestCart(cartDto, cartItemDto); model.addAttribute("cart", handledCartDto); model.addAttribute("deliveryCost", marketProperties.getDeliveryCost()); return CART_BASE; } try { Cart updatedCart = updateCart(principal, cartItemDto); model.addAttribute("cart", cartDtoAssembler.toModel(updatedCart)); } catch (UnknownEntityException ex) { bindingResult.addError(ex.getFieldError()); return CART_BASE; } return "redirect:/" + CART_BASE; }
Example 4
Source File: UserController.java From java-platform with Apache License 2.0 | 6 votes |
@RequestMapping(value = "/saveBy", method = RequestMethod.POST) @ResponseBody public Result saveBy(@ModelAttribute @Valid User user, BindingResult bindingResult, String password) { if (user.isNew() && Strings.isNullOrEmpty(password)) { bindingResult.addError(new ObjectError("password", "密码不能为空")); } if (bindingResult.hasErrors()) { return Result.validateError(bindingResult.getAllErrors()); } if (user.isNew()) { userService.changePassword(user, null, password); } userService.save(user); return Result.success(); }
Example 5
Source File: FuncionarioController.java From ponto-inteligente-api with MIT License | 6 votes |
/** * Atualiza os dados de um funcionário. * * @param id * @param funcionarioDto * @param result * @return ResponseEntity<Response<FuncionarioDto>> * @throws NoSuchAlgorithmException */ @PutMapping(value = "/{id}") public ResponseEntity<Response<FuncionarioDto>> atualizar(@PathVariable("id") Long id, @Valid @RequestBody FuncionarioDto funcionarioDto, BindingResult result) throws NoSuchAlgorithmException { log.info("Atualizando funcionário: {}", funcionarioDto.toString()); Response<FuncionarioDto> response = new Response<FuncionarioDto>(); Optional<Funcionario> funcionario = this.funcionarioService.buscarPorId(id); if (!funcionario.isPresent()) { result.addError(new ObjectError("funcionario", "Funcionário não encontrado.")); } this.atualizarDadosFuncionario(funcionario.get(), funcionarioDto, result); if (result.hasErrors()) { log.error("Erro validando funcionário: {}", result.getAllErrors()); result.getAllErrors().forEach(error -> response.getErrors().add(error.getDefaultMessage())); return ResponseEntity.badRequest().body(response); } this.funcionarioService.persistir(funcionario.get()); response.setData(this.converterFuncionarioDto(funcionario.get())); return ResponseEntity.ok(response); }
Example 6
Source File: LancamentoController.java From ponto-inteligente-api with MIT License | 5 votes |
/** * Converte um LancamentoDto para uma entidade Lancamento. * * @param lancamentoDto * @param result * @return Lancamento * @throws ParseException */ private Lancamento converterDtoParaLancamento(LancamentoDto lancamentoDto, BindingResult result) throws ParseException { Lancamento lancamento = new Lancamento(); if (lancamentoDto.getId().isPresent()) { Optional<Lancamento> lanc = this.lancamentoService.buscarPorId(lancamentoDto.getId().get()); if (lanc.isPresent()) { lancamento = lanc.get(); } else { result.addError(new ObjectError("lancamento", "Lançamento não encontrado.")); } } else { lancamento.setFuncionario(new Funcionario()); lancamento.getFuncionario().setId(lancamentoDto.getFuncionarioId()); } lancamento.setDescricao(lancamentoDto.getDescricao()); lancamento.setLocalizacao(lancamentoDto.getLocalizacao()); lancamento.setData(this.dateFormat.parse(lancamentoDto.getData())); if (EnumUtils.isValidEnum(TipoEnum.class, lancamentoDto.getTipo())) { lancamento.setTipo(TipoEnum.valueOf(lancamentoDto.getTipo())); } else { result.addError(new ObjectError("tipo", "Tipo inválido.")); } return lancamento; }
Example 7
Source File: RegistrationController.java From user-registration-V2 with Apache License 2.0 | 5 votes |
@RequestMapping(value = "/user", method = RequestMethod.POST) public ModelAndView create(@ModelAttribute User user, BindingResult bindingResult, RedirectAttributes redirect) { if (!registrationService.validEMailAdress(user.getEmail())) { log.info(String.format("email=%s nicht valide", user.getEmail())); bindingResult.addError(new FieldError("user", "email", "EMail Adresse nicht valide")); } else { boolean registrationResult = registrationService.register(user); if (!registrationResult) { log.info(String .format("email=%s konnte nicht registriert werden - EMail Adresse schon verwendet?", user.getEmail())); bindingResult .addError(new FieldError("user", "email", "User konnte nicht registriert werden - EMail Adresse schon verwendet?")); } } if (bindingResult.hasErrors()) { log.info(String.format( "email=%s hatte Fehler - Formular neu anzeigen", user.getEmail())); return new ModelAndView("user/form", "user", user); } else { return new ModelAndView("user/display", "user", user); } }
Example 8
Source File: EnglishRegistrationController.java From user-registration-V2 with Apache License 2.0 | 5 votes |
@RequestMapping(value = "/user_en", method = RequestMethod.POST) public ModelAndView create(@ModelAttribute User user, BindingResult bindingResult, RedirectAttributes redirect) { if (!registrationService.validEMailAdress(user.getEmail())) { log.info(String.format("email=%s not valid", user.getEmail())); bindingResult.addError(new FieldError("user", "email", "email adress not valid")); } else { boolean registrationResult = registrationService.register(user); if (!registrationResult) { log.info(String .format("email=%s could not be registered - email adress already in use?", user.getEmail())); bindingResult .addError(new FieldError("user", "email", "User could not be registered - email adress already in use?")); } } if (bindingResult.hasErrors()) { log.info(String.format( "email=%s had errors - display form again", user.getEmail())); return new ModelAndView("user/form_en", "user", user); } else { return new ModelAndView("user/display_en", "user", user); } }
Example 9
Source File: ControlBindingErrorProcessor.java From jdal with Apache License 2.0 | 5 votes |
/** * Add a ControlError instead FieldError to hold component that has failed. * @param control * @param ex * @param bindingResult */ public void processPropertyAccessException(Object control, PropertyAccessException ex, BindingResult bindingResult ) { // Create field error with the exceptions's code, e.g. "typeMismatch". String field = ex.getPropertyName(); String[] codes = bindingResult.resolveMessageCodes(ex.getErrorCode(), field); Object[] arguments = getArgumentsForBindError(bindingResult.getObjectName(), field); Object rejectedValue = ex.getValue(); if (rejectedValue != null && rejectedValue.getClass().isArray()) { rejectedValue = StringUtils.arrayToCommaDelimitedString(ObjectUtils.toObjectArray(rejectedValue)); } bindingResult.addError(new ControlError(control, bindingResult.getObjectName(), field, rejectedValue, true, codes, arguments, ex.getLocalizedMessage())); }
Example 10
Source File: EnglishRegistrationController.java From user-registration-V2 with Apache License 2.0 | 5 votes |
@RequestMapping(value = "/user_en", method = RequestMethod.POST) public ModelAndView create(@ModelAttribute User user, BindingResult bindingResult, RedirectAttributes redirect) { if (!registrationService.validEMailAdress(user.getEmail())) { log.info(String.format("email=%s not valid", user.getEmail())); bindingResult.addError(new FieldError("user", "email", "email adress not valid")); } else { boolean registrationResult = registrationService.register(user); if (!registrationResult) { log.info(String .format("email=%s could not be registered - email adress already in use?", user.getEmail())); bindingResult .addError(new FieldError("user", "email", "User could not be registered - email adress already in use?")); } } if (bindingResult.hasErrors()) { log.info(String.format( "email=%s had errors - display form again", user.getEmail())); return new ModelAndView("user/form_en", "user", user); } else { return new ModelAndView("user/display_en", "user", user); } }
Example 11
Source File: PayloadArgumentResolver.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception { Payload ann = parameter.getParameterAnnotation(Payload.class); if (ann != null && StringUtils.hasText(ann.expression())) { throw new IllegalStateException("@Payload SpEL expressions not supported by this resolver"); } Object payload = message.getPayload(); if (isEmptyPayload(payload)) { if (ann == null || ann.required()) { String paramName = getParameterName(parameter); BindingResult bindingResult = new BeanPropertyBindingResult(payload, paramName); bindingResult.addError(new ObjectError(paramName, "Payload value must not be empty")); throw new MethodArgumentNotValidException(message, parameter, bindingResult); } else { return null; } } Class<?> targetClass = parameter.getParameterType(); if (ClassUtils.isAssignable(targetClass, payload.getClass())) { validate(message, parameter, payload); return payload; } else { payload = (this.converter instanceof SmartMessageConverter ? ((SmartMessageConverter) this.converter).fromMessage(message, targetClass, parameter) : this.converter.fromMessage(message, targetClass)); if (payload == null) { throw new MessageConversionException(message, "No converter found to convert to " + targetClass + ", message=" + message); } validate(message, parameter, payload); return payload; } }
Example 12
Source File: CadastroPFController.java From ponto-inteligente-api with MIT License | 5 votes |
/** * Verifica se a empresa está cadastrada e se o funcionário não existe na base de dados. * * @param cadastroPFDto * @param result */ private void validarDadosExistentes(CadastroPFDto cadastroPFDto, BindingResult result) { Optional<Empresa> empresa = this.empresaService.buscarPorCnpj(cadastroPFDto.getCnpj()); if (!empresa.isPresent()) { result.addError(new ObjectError("empresa", "Empresa não cadastrada.")); } this.funcionarioService.buscarPorCpf(cadastroPFDto.getCpf()) .ifPresent(func -> result.addError(new ObjectError("funcionario", "CPF já existente."))); this.funcionarioService.buscarPorEmail(cadastroPFDto.getEmail()) .ifPresent(func -> result.addError(new ObjectError("funcionario", "Email já existente."))); }
Example 13
Source File: UploadWizardPage.java From molgenis with GNU Lesser General Public License v3.0 | 5 votes |
@Override public String handleRequest(HttpServletRequest request, BindingResult result, Wizard wizard) { ImportWizardUtil.validateImportWizard(wizard); ImportWizard importWizard = (ImportWizard) wizard; String dataImportOption = request.getParameter("data-option"); try { File file = null; Part part = request.getPart("upload"); if (part != null) { file = FileUploadUtils.saveToTempFolder(part); } if (file == null) { result.addError(new ObjectError("wizard", "No file selected")); } else { importWizard.setFile(file); RepositoryCollection repositoryCollection = getFileRepositoryCollectionFactory().createFileRepositoryCollection(file); ImportService importService = getImportServiceFactory().getImportService(file, repositoryCollection); importWizard.setSupportedMetadataActions(importService.getSupportedMetadataActions()); importWizard.setSupportedDataActions(importService.getSupportedDataActions()); importWizard.setMustChangeEntityName(importService.getMustChangeEntityName()); } } catch (Exception e) { ImportWizardUtil.handleException(e, importWizard, result, LOG, dataImportOption); } return null; }
Example 14
Source File: LancamentoController.java From ponto-inteligente-api with MIT License | 5 votes |
/** * Valida um funcionário, verificando se ele é existente e válido no * sistema. * * @param lancamentoDto * @param result */ private void validarFuncionario(LancamentoDto lancamentoDto, BindingResult result) { if (lancamentoDto.getFuncionarioId() == null) { result.addError(new ObjectError("funcionario", "Funcionário não informado.")); return; } log.info("Validando funcionário id {}: ", lancamentoDto.getFuncionarioId()); Optional<Funcionario> funcionario = this.funcionarioService.buscarPorId(lancamentoDto.getFuncionarioId()); if (!funcionario.isPresent()) { result.addError(new ObjectError("funcionario", "Funcionário não encontrado. ID inexistente.")); } }
Example 15
Source File: UserController.java From springboot-vue.js-bbs with Apache License 2.0 | 5 votes |
@PostMapping("/signup") public String signup(@Valid UserDto userDto, BindingResult binding) { if (binding.hasErrors()) { return "user/signup"; } try { sessionUserService.applyAuthToCtxHolder(userService.save(userDto)); } catch (CustomValidationException e) { binding.addError(e.getError()); return "user/signup"; } return "redirect:/"; }
Example 16
Source File: ErrorMessagesTest.java From sinavi-jfw with Apache License 2.0 | 5 votes |
@Test public void BindingResultでバリデーションメッセージが設定される() { class TargetBean { } TargetBean t = new TargetBean(); BindingResult bind = new BeanPropertyBindingResult(t, "bean"); bind.addError(new FieldError("bean", "id", "必須です。")); ErrorMessage error = ErrorMessages.create().bind(bind).get(); assertThat(error, CoreMatchers.notNullValue()); assertThat(error.getValidationMessages(), CoreMatchers.notNullValue()); assertThat(error.getValidationMessages().size(), CoreMatchers.is(1)); assertThat(error.getValidationMessages().get(0).getPath(), CoreMatchers.is("bean.id")); assertThat(error.getValidationMessages().get(0).getMessage(), CoreMatchers.is("必須です。")); }
Example 17
Source File: UserController.java From angular-spring-api with MIT License | 5 votes |
private void validateUpdate(User user, BindingResult result) { if (user.getId() == null) { result.addError(new ObjectError("User", "Id no information")); return; } if (user.getEmail() == null) { result.addError(new ObjectError("User", "Email no information")); return; } }
Example 18
Source File: CustomerController.java From market with MIT License | 5 votes |
@RequestMapping(value = "/new", method = RequestMethod.POST) public String postRegistrationForm( Model model, @Valid UserDTO user, BindingResult bindingResult, @ModelAttribute(value = "cart") CartDTO cartDto ) { model.addAttribute("userAccount", user); // place user data back to redirect him back to pre-filled registration form if (bindingResult.hasErrors()) return CUSTOMER_NEW; UserAccount account = userAccountDtoAssembler.toDomain(user); UserAccount newAccount; try { newAccount = userAccountService.create(account); } catch (EmailExistsException e) { bindingResult.addError(e.getFieldError()); return CUSTOMER_NEW; } boolean authenticated = authenticationService.authenticate(account.getEmail(), user.getPassword()); if (!authenticated) return CUSTOMER_NEW; model.addAttribute("userAccount", userAccountDtoAssembler.toModel(newAccount)); // now add the authorized data Cart unauthorisedCart = cartDtoAssembler.toDomain(cartDto, productService); Cart updatedCart = cartService.addAllToCart(newAccount.getEmail(), unauthorisedCart.getCartItems()); model.addAttribute("cart", cartDtoAssembler.toModel(updatedCart)); return "redirect:" + ROOT; }
Example 19
Source File: UserController.java From angular-spring-api with MIT License | 4 votes |
private void validateCreateUser(User user, BindingResult result) { if (user.getEmail() == null) { result.addError(new ObjectError("User", "Email no information")); return; } }
Example 20
Source File: PayloadArgumentResolver.java From java-technology-stack with MIT License | 4 votes |
@Override @Nullable public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception { Payload ann = parameter.getParameterAnnotation(Payload.class); if (ann != null && StringUtils.hasText(ann.expression())) { throw new IllegalStateException("@Payload SpEL expressions not supported by this resolver"); } Object payload = message.getPayload(); if (isEmptyPayload(payload)) { if (ann == null || ann.required()) { String paramName = getParameterName(parameter); BindingResult bindingResult = new BeanPropertyBindingResult(payload, paramName); bindingResult.addError(new ObjectError(paramName, "Payload value must not be empty")); throw new MethodArgumentNotValidException(message, parameter, bindingResult); } else { return null; } } Class<?> targetClass = parameter.getParameterType(); Class<?> payloadClass = payload.getClass(); if (ClassUtils.isAssignable(targetClass, payloadClass)) { validate(message, parameter, payload); return payload; } else { if (this.converter instanceof SmartMessageConverter) { SmartMessageConverter smartConverter = (SmartMessageConverter) this.converter; payload = smartConverter.fromMessage(message, targetClass, parameter); } else { payload = this.converter.fromMessage(message, targetClass); } if (payload == null) { throw new MessageConversionException(message, "Cannot convert from [" + payloadClass.getName() + "] to [" + targetClass.getName() + "] for " + message); } validate(message, parameter, payload); return payload; } }