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:org.woofenterprise.dogs.web.controllers.AppointmentsController.java

@RequestMapping(value = "/edit", method = RequestMethod.POST)
@RolesAllowed("ADMIN")
public String update(Model model, @Valid @ModelAttribute("appointment") AppointmentDTO appointmentDTO,
        BindingResult bindingResult, UriComponentsBuilder uriBuilder, RedirectAttributes redirectAttributes) {
    if (bindingResult.hasErrors()) {
        model.addAttribute("proceduresOptions", Procedure.values());
        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
            log.trace("FieldError: {}", fe);
        }/*from  w  w  w  .  j a va  2s .c o m*/

        if (bindingResult.hasGlobalErrors()) {
            StringBuilder sb = new StringBuilder();
            for (ObjectError er : bindingResult.getGlobalErrors()) {
                sb.append(er.getDefaultMessage());
                sb.append('\n');
            }

            model.addAttribute("globalError", sb);
        }

        return "appointments/edit";
    }
    Long id = appointmentDTO.getId();
    try {
        facade.updateAppointment(appointmentDTO);

        redirectAttributes.addFlashAttribute("alert_success", "Appointment #" + id + " was edited.");
        return "redirect:"
                + uriBuilder.path("/appointments/view/{id}").buildAndExpand(id).encode().toUriString();
    } catch (Exception e) {
        log.warn("Exception wile editing: " + e.getMessage());
        redirectAttributes.addFlashAttribute("alert_danger", "Appointment #" + id + " was not edited.");
        return "redirect:/";
    }
}

From source file:cz.swi2.mendeluis.app.web.controllers.RegistrationController.java

/**
 * Handles registration form submission. 
 *//*from w  ww  .  j  a v  a2s . co  m*/
@RequestMapping(method = RequestMethod.POST)
public String create(@ModelAttribute("user") @Validated UserRegistrationDTO user, BindingResult bindingResult,
        Model model, RedirectAttributes redirectAttributes, UriComponentsBuilder uriBuilder) {

    log.info("submitted registration: {}", user);
    if (bindingResult.hasErrors()) {
        for (ObjectError ge : bindingResult.getGlobalErrors()) {
            log.info("ObjectError: {}", ge);
        }
        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
            log.info("FieldError: {}", fe);
        }
        model.addAttribute("alert_failure", "There are some errors with submitted data.");
        return "user/registration";
    } else {
        try {
            userFacade.createNewUser(user.getName(), user.getUsername(), user.getPassword());
            redirectAttributes.addFlashAttribute("alert_success", "You sign up. You can log in now!");
            return "redirect:/login";
        } catch (UniqueViolationException e) {
            model.addAttribute("alert_failure", "The username already exists!");
            return "user/registration";
        }
    }
}

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

@RequestMapping(value = "/new", method = RequestMethod.POST)
@RolesAllowed("ADMIN")
public String createAppointment(Model model,
        @Valid @ModelAttribute("appointment") AppointmentDTO appointmentDTO, BindingResult bindingResult,
        UriComponentsBuilder uriBuilder, RedirectAttributes redirectAttributes) {
    if (bindingResult.hasErrors()) {
        model.addAttribute("proceduresOptions", Procedure.values());

        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
            log.trace("FieldError: {}", fe);
        }//w  w w .  ja  va2 s. c  o m

        if (bindingResult.hasGlobalErrors()) {
            StringBuilder sb = new StringBuilder();
            for (ObjectError er : bindingResult.getGlobalErrors()) {
                sb.append(er.getDefaultMessage());
                sb.append('\n');
            }

            model.addAttribute("globalError", sb);
        }

        return "appointments/create";
    }
    try {
        appointmentDTO = facade.createAppointment(appointmentDTO);
        Long id = appointmentDTO.getId();

        redirectAttributes.addFlashAttribute("alert_success", "Appointment #" + id + " was created.");
        return "redirect:"
                + uriBuilder.path("/appointments/view/{id}").buildAndExpand(id).encode().toUriString();
    } catch (Exception e) {
        log.warn("Exception wile creating: " + e.getMessage());
        redirectAttributes.addFlashAttribute("alert_danger", "Appointment was not created.");
        return "redirect:/";
    }
}

From source file:web.EventLogController.java

/**
 * Saves the new event to the database before redirecting to the general
 *  Event Log list; Redirects to the form and displays error messages in
 *  case of an error/* w w  w.j  a va  2 s . co m*/
 * @param el
 * @param result
 * @param request
 * @return
 */
@RequestMapping(value = "/eventlog/save", method = RequestMethod.POST)
public ModelAndView save(@ModelAttribute("eventlog") @Valid EventLog el, BindingResult result,
        HttpServletRequest request) {
    //returns error message if editing page fails
    if (result.hasErrors()) {
        el.setClients(dao.getClientsMap());
        el.setUsers(dao.getUsersMap());
        logger.info(result.getFieldErrors().toString());
        return new ModelAndView("addevent", "eventlog", el);
    }

    int x = dao.addEvent(el);
    //returns either a successful message or failure message
    Messages msg = null;
    if (x == 1) {
        msg = new Messages(Messages.Level.SUCCESS, "Event successfullly added.");
    } else {
        msg = new Messages(Messages.Level.ERROR, "Error adding event to database.");
    }
    //displays appropriate message and redirects to general Event Logs list
    request.getSession().setAttribute("message", msg);
    return new ModelAndView("redirect:/eventlog/vieweventlog");
}

From source file:org.cloudfoundry.identity.uaa.config.YamlBindingTests.java

@Test
public void testRequiredFieldsValidation() {
    TargetWithValidatedMap target = new TargetWithValidatedMap();
    BindingResult result = bind(target, "info:\n  foo: bar");
    assertEquals(2, result.getErrorCount());
    for (FieldError error : result.getFieldErrors()) {
        System.err.println(new StaticMessageSource().getMessage(error, Locale.getDefault()));
    }//from w  ww .ja  va  2  s  .c  o m
}

From source file:org.gvnix.web.json.BindingResultSerializer.java

/**
 * {@inheritDoc}//from  w  w w .j a v  a  2  s .c  o m
 */
@Override
public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonProcessingException {

    try {
        // Cast to BindingResult
        BindingResult result = (BindingResult) value;

        // Create the result map
        Map<String, Object> allErrorsMessages = new HashMap<String, Object>();

        // Get field errors
        List<FieldError> fieldErrors = result.getFieldErrors();
        if (fieldErrors.isEmpty()) {
            // Nothing to do
            jgen.writeNull();
            return;
        }

        // Check if target type is an array or a bean
        @SuppressWarnings("rawtypes")
        Class targetClass = result.getTarget().getClass();
        if (targetClass.isArray() || Collection.class.isAssignableFrom(targetClass)) {
            loadListErrors(result.getFieldErrors(), allErrorsMessages);
        } else {
            loadObjectErrors(result.getFieldErrors(), allErrorsMessages);
        }

        jgen.writeObject(allErrorsMessages);
    } catch (JsonProcessingException e) {
        LOGGER.warn(ERROR_WRITTING_BINDING, e);
        throw e;
    } catch (IOException e) {
        LOGGER.warn(ERROR_WRITTING_BINDING, e);
        throw e;
    } catch (Exception e) {
        LOGGER.warn(ERROR_WRITTING_BINDING, e);
        throw new IOException(ERROR_WRITTING_BINDING, e);
    }

}

From source file:com.teamd.taxi.controllers.admin.DriverAdminController.java

@RequestMapping(value = "/driver-update", method = RequestMethod.POST)
@ResponseBody//from www  .ja  v  a2  s  .  c o  m
public AdminResponseModel<String> updateDriver(@Valid UpdateDriverModel driverModel,
        BindingResult bindingResult) {
    AdminResponseModel<String> response = new AdminResponseModel<>();
    if (bindingResult.hasErrors()) {
        StringBuilder errors = new StringBuilder();
        for (FieldError fieldError : validateUtil.filterErrors(bindingResult.getFieldErrors())) {
            errors.append("<p>");
            errors.append(fieldError.getDefaultMessage());
            errors.append("</p>");
        }
        return response.setContent(errors.toString());
    }
    driverService.updateDriverAccount(driverModel);
    response.setResultSuccess().setContent(env.getRequiredProperty(MESSAGE_DRIVER_SUCCESS_UPDATE));
    return response;
}

From source file:cz.muni.pa165.carparkapp.web.PersonalInfoController.java

@RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(@Valid @ModelAttribute EmployeeDTO employee, BindingResult bindingResult,
        RedirectAttributes redirectAttributes, UriComponentsBuilder uriBuilder, Locale locale) {
    log.debug("update(locale={}, customer={})", locale, employee);
    if (bindingResult.hasErrors()) {
        log.debug("binding errors");
        for (ObjectError ge : bindingResult.getGlobalErrors()) {
            log.debug("ObjectError: {}", ge);
        }//from   w  w  w.  ja  v a  2  s.c o  m
        for (FieldError fe : bindingResult.getFieldErrors()) {
            log.debug("FieldError: {}", fe);
        }
        return employee.getId() < 1 ? "employee" : "employee/update";
    }
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String name = auth.getName();
    EmployeeDTO emp = null;

    for (EmployeeDTO employee1 : employeeService.getAllEmployees()) {
        if (employee1.getUserName().equals(name))
            emp = employee1;
    }
    employee.setUserName(name);
    employee.setPassword(emp.getPassword());
    employeeService.updateEmployee(employee);
    redirectAttributes.addFlashAttribute("message", messageSource.getMessage("employee.updated",
            new Object[] { employee.getFirstName(), employee.getLastName(), employee.getId() }, locale));
    return "redirect:" + uriBuilder.path("/employee").build();
}

From source file:cz.muni.fi.pa165.mvc.controllers.TeamController.java

@RequestMapping(value = "/create", method = RequestMethod.POST)
public String create(@Valid @ModelAttribute("teamCreate") TeamDTO formBean, BindingResult bindingResult,
        Model model, RedirectAttributes redirectAttributes, UriComponentsBuilder uriBuilder) {
    Long id = null;/*from   ww w  .j a va2s  .  c o m*/
    log.debug("create(teamCreate={})", formBean);
    if (bindingResult.hasErrors()) {
        for (ObjectError ge : bindingResult.getGlobalErrors()) {
            log.trace("ObjectError: {}", ge);
        }
        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
            log.trace("FieldError: {}", fe);
        }
        return "team/new";
    }
    try {
        id = teamFacade.createTeam(formBean);
        redirectAttributes.addFlashAttribute("alert_success",
                "Team: " + teamFacade.getTeamById(id) + " was created");
    } catch (Exception ex) {
        log.warn("cannot Create a team {}");
        redirectAttributes.addFlashAttribute("alert_danger",
                "This team cannot be created because it has already exited in La Liga now.");
    }
    return "redirect:" + uriBuilder.path("/team/list").buildAndExpand(id).encode().toUriString();
}

From source file:org.centralperf.controller.RunController.java

/**
 * Create a new Run//from www.j  a  v a2 s. c  o  m
 * @param projectId ID of the project (from URI)
 * @param run   The Run to create
 * @param result   BindingResult to check if binding raised some errors
 * @param model   Model prepared for the new project form view in case of errors
 * @return Redirection to the run detail page once the run has been created 
 */
@RequestMapping(value = "/project/{projectId}/run/new", method = RequestMethod.POST)
public String addRun(@PathVariable("projectId") Long projectId, @ModelAttribute("run") @Valid Run run,
        BindingResult result, Model model, RedirectAttributes redirectAttrs) {
    if (result.hasErrors()) {
        String errorMessage = "Error creating Run : ";
        for (FieldError error : result.getFieldErrors()) {
            errorMessage += "Field " + error.getField() + ",  " + error.getDefaultMessage() + " ( "
                    + error.getRejectedValue() + ")";
        }
        redirectAttrs.addFlashAttribute("error", errorMessage);
        return "redirect:/project/" + projectId + "/detail";
    }
    ScriptVersion scriptVersion = scriptVersionRepository.findOne(run.getScriptVersion().getId());
    run.setScriptVersion(scriptVersion);
    runRepository.save(run);
    return "redirect:/project/" + projectId + "/run/" + run.getId() + "/detail";
}