Example usage for org.springframework.validation BindingResult getFieldErrors

List of usage examples for org.springframework.validation BindingResult getFieldErrors

Introduction

In this page you can find the example usage for org.springframework.validation BindingResult getFieldErrors.

Prototype

List<FieldError> getFieldErrors();

Source Link

Document

Get all errors associated with a field.

Usage

From source file:cz.muni.fi.mvc.controllers.DestinationController.java

/**
 * Updates destination//from   ww w . ja  v a  2 s . c o  m
 *
 * @param id, modelAttribute, bindingResult, model, redirectAttributes, uriBuilder
 * @return JSP page
 */
@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
public String updateDestination(@PathVariable("id") long id,
        @Valid @ModelAttribute("destination") UpdateDestinationLocationDTO updatedDestination,
        BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes,
        UriComponentsBuilder uriBuilder) {

    if (bindingResult.hasErrors()) {
        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
            log.trace("FieldError: {}", fe);
        }
        for (ObjectError ge : bindingResult.getGlobalErrors()) {
            log.trace("ObjectError: {}", ge);
        }
        return "destination/edit";
    }

    if ((updatedDestination.getLocation()).equals("")) {
        redirectAttributes.addFlashAttribute("alert_danger", "Location of destination is empty");
        return "redirect:"
                + uriBuilder.path("/destination/edit/{id}").buildAndExpand(id).encode().toUriString();
    }

    try {
        destinationFacade.updateDestinationLocation(updatedDestination);
    } catch (Exception ex) {
        redirectAttributes.addFlashAttribute("alert_danger",
                "Destination " + id + " wasn't updated because location already exists");
        return "redirect:"
                + uriBuilder.path("/destination/edit/{id}").buildAndExpand(id).encode().toUriString();
    }
    redirectAttributes.addFlashAttribute("alert_success", "Destination " + id + " was updated");
    return "redirect:" + uriBuilder.path("/destination").toUriString();
}

From source file:com.hadoopvietnam.controller.member.ChangePasswordController.java

@PreAuthorize("isAuthenticated()")
@RequestMapping(value = { "/json" }, method = { org.springframework.web.bind.annotation.RequestMethod.POST })
@ResponseBody/*from w  ww  .  j a  v a2s. c o  m*/
public ValidationResponse changePasswordAjaxJson(Model model,
        @ModelAttribute("changePasswordForm") ChangePasswordForm form, HttpServletRequest request,
        BindingResult bindingResult) {
    ValidationResponse res = new ValidationResponse();
    this.validator.validate(form, bindingResult);
    if (!bindingResult.hasErrors()) {
        res.setStatus("SUCCESS");
    } else {
        res.setStatus("FAIL");
        List<FieldError> allErrors = bindingResult.getFieldErrors();
        List<ErrorMessage> errorMesages = new ArrayList<ErrorMessage>();
        for (FieldError objectError : allErrors) {
            errorMesages.add(new ErrorMessage(objectError.getField(),
                    this.resourceMessage.getMessage(objectError.getCode(), request)));
        }
        res.setErrorMessageList(errorMesages);
    }
    return res;
}

From source file:com.tapas.evidence.fe.form.EvidenceForm.java

public boolean validate(final MetaModel metaModel, final Validator validator, final Model model,
        final IUiMessageSource messageSource, final Locale locale) {
    boolean result = false;
    final BindingResult validationResult = new BeanPropertyBindingResult(model, model.getClass().getName());
    clearFields(metaModel);/*from w  w  w  .  j  a v  a  2 s  . c om*/
    validator.validate(model, validationResult);
    if (validationResult.hasErrors()) {
        for (FieldError error : validationResult.getFieldErrors()) {
            final String field = error.getField();
            final String message = getMessage(error.getCodes(), messageSource, locale);
            final Field fieldComponent = this.getField(field);
            if (fieldComponent instanceof AbstractField) {
                ((AbstractField) fieldComponent).setComponentError(new UserError(message));
            }
        }
        result = false;
    } else {
        result = true;
    }
    return result;
}

From source file:com.mmj.app.web.controller.BaseController.java

/**
 * ??/*from w w  w .  j  a v a 2  s  . c  o m*/
 * 
 * @param result
 * @return
 */
public Result showErrors(BindingResult result) {
    StringBuffer errorsb = new StringBuffer();
    if (result.hasErrors()) {
        for (FieldError error : result.getFieldErrors()) {
            errorsb.append(error.getField());
            errorsb.append(error.getDefaultMessage());
            errorsb.append("|");
        }
        String errorsr = errorsb.toString().substring(0, errorsb.toString().length() - 1);
        Result.failed(errorsr.replaceAll("null", StringUtils.EMPTY));
    }
    return Result.success();
}

From source file:com.athena.peacock.controller.web.alm.crowd.AlmUserController.java

@RequestMapping(value = "/usermanagement", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody DtoJsonResponse addUser(@Valid @RequestBody AlmUserAddDto userData, BindingResult result) {

    if (result.hasErrors()) {
        DtoJsonResponse response = new DtoJsonResponse();
        response.setSuccess(false);/*from  www . ja va  2 s .c  om*/

        StringBuilder sb = new StringBuilder();

        Iterator<FieldError> iter = result.getFieldErrors().iterator();
        FieldError error = null;

        while (iter.hasNext()) {
            error = iter.next();
            sb.append(",").append(error.getField());
        }

        if (StringUtils.isEmpty(sb.toString())) {
            response.setMsg(" ? ? ?.");
        } else {
            response.setMsg(sb.toString().substring(1)
                    + "?  ? ? ?.");
        }

        response.setData(result.getAllErrors());
        return response;
    }

    return service.addUser(userData);
}

From source file:com.athena.peacock.controller.web.alm.crowd.AlmUserController.java

@RequestMapping(value = "/usermanagement", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody DtoJsonResponse modifyUser(@RequestBody AlmUserAddDto userData, BindingResult result) {

    if (result.hasErrors()) {
        DtoJsonResponse response = new DtoJsonResponse();
        response.setSuccess(false);//from w ww .  j  a  v  a 2 s.c o m

        StringBuilder sb = new StringBuilder();

        Iterator<FieldError> iter = result.getFieldErrors().iterator();
        FieldError error = null;

        while (iter.hasNext()) {
            error = iter.next();
            sb.append(",").append(error.getField());
        }

        if (StringUtils.isEmpty(sb.toString())) {
            response.setMsg(" ? ? ?.");
        } else {
            response.setMsg(sb.toString().substring(1)
                    + "?  ? ? ?.");
        }

        response.setData(result.getAllErrors());
        return response;
    }

    return service.modifyUser(userData);
}

From source file:com.simplecrud.controller.RegistrationController.java

/**
 * Process Registration Data/* ww  w  .j  ava2  s . com*/
 *
 * @param member
 * @param result
 * @param model
 * @param request
 * @return view
 */
@RequestMapping(value = "/register", method = RequestMethod.POST)
public ModelAndView validateUser(@Valid @ModelAttribute("newMemberForm") ValidateMember member,
        BindingResult result, Model model, HttpServletRequest request) {

    FormStatus sFormStatus = new FormStatus();

    //if validated form has errors
    if (result.hasErrors()) {

        //handle errors in the inputs
        List<FieldError> errors = result.getFieldErrors();
        for (FieldError error : errors) {
            System.out.println(error.getField() + " - " + error.getDefaultMessage());

            if ("username".equals(error.getField())) {
                //set error message in username input
                sFormStatus.setsUsername(error.getDefaultMessage());

            }

            if ("password".equals(error.getField())) {
                //set error message in password input
                sFormStatus.setsPassword(error.getDefaultMessage());
            }

            if ("email".equals(error.getField())) {
                //set error message in email input
                sFormStatus.setsEmail(error.getDefaultMessage());
            }

        }
        System.out.println(result.getFieldErrors());
        return new ModelAndView("redirect:/registration.html?" + "&ErrorUsername=" + sFormStatus.getsUsername()
                + "" + "&ErrorPassword=" + sFormStatus.getsPassword() + "" + "&ErrorEmail="
                + sFormStatus.getsEmail() + "" + "&response=error");

    } else {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");

        //try to save the form
        try {
            newMemberDao.persist(new NewMember(username, password, email));
            System.out.println(result + "Form Results - Valid and Saved");

            return new ModelAndView("redirect:/registration.html?response=success");

        } catch (Exception e) {
            System.out.println(e.getMessage() + "  User Already Exist");
        }
        return new ModelAndView("redirect:/registration.html?response=UserAlreadyExist");
    }

}

From source file:org.woofenterprise.dogs.web.controllers.AppointmentsController.java

@RequestMapping(value = "/calculate", method = RequestMethod.POST)
@RolesAllowed("ADMIN")
public String calculateDuration(Model model,
        @Valid @ModelAttribute("appointment") AppointmentDurationDTO appointmentDurationDTO,
        BindingResult bindingResult, UriComponentsBuilder uriBuilder, RedirectAttributes redirectAttributes) {
    model.addAttribute("proceduresOptions", Procedure.values());

    if (bindingResult.hasErrors()) {
        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
            log.trace("FieldError: {}", fe);
        }//from   www  .j a va  2s  .c  o m
        return "appointments/calculate";
    }

    AppointmentDTO appointmentDTO = createFromDurationDTO(appointmentDurationDTO);

    Long duration = facade.calculateAppointmentDuration(appointmentDTO) * 60 * 1000; // in miliseconds
    Date endTime = new Date(appointmentDTO.getStartTime().getTime() + duration);
    appointmentDTO.setEndTime(endTime);

    model.addAttribute("appointment", appointmentDTO);

    return "appointments/create";
}

From source file:ch.ralscha.extdirectspring.bean.ExtDirectResponseBuilder.java

/**
 * Adds an "errors" property in the response if there are any errors in the
 * bindingResult. Sets the success flag to false if there are errors.
 *
 * @param locale//from   ww  w  . ja  va 2 s  . c o m
 * @param messageSource
 * @param bindingResult
 * @return this instance
 */
public ExtDirectResponseBuilder addErrors(Locale locale, MessageSource messageSource,
        final BindingResult bindingResult) {
    if (bindingResult != null && bindingResult.hasFieldErrors()) {
        Map<String, List<String>> errorMap = new HashMap<String, List<String>>();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            String message = fieldError.getDefaultMessage();
            if (messageSource != null) {
                Locale loc = locale != null ? locale : Locale.getDefault();
                message = messageSource.getMessage(fieldError.getCode(), fieldError.getArguments(), loc);
            }
            List<String> fieldErrors = errorMap.get(fieldError.getField());

            if (fieldErrors == null) {
                fieldErrors = new ArrayList<String>();
                errorMap.put(fieldError.getField(), fieldErrors);
            }

            fieldErrors.add(message);
        }
        if (errorMap.isEmpty()) {
            addResultProperty("success", Boolean.TRUE);
        } else {
            addResultProperty("errors", errorMap);
            addResultProperty("success", Boolean.FALSE);
        }
    }
    return this;
}