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:com.biblio.web.rest.UserResource.java

/**
 * POST /account : update user information by his id.
 *
 * @param userDTO the user information/*from www . jav  a 2 s  .c o  m*/
 * @param id id of account to update
 * @param bindingResult
 * @return the ResponseEntity with status 200 (OK), or status 400 (Bad
 * Request) or 500 (Internal Server Error) if the user couldn't be updated
 */
@RequestMapping(value = "/account/{id}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public Object saveAccount(@Valid @RequestBody UserDTO userDTO, @PathVariable("id") Long id,
        BindingResult bindingResult) {
    Map<String, Object> modele = new HashMap<>();
    if (bindingResult.hasErrors()) {

        modele.put(Constants.ERROR, true);
        modele.put(Constants.MESSAGE, "Enregistrement chou");
        bindingResult.getFieldErrors().stream().forEach((f) -> {
            modele.put(f.getField(), f.getDefaultMessage());
        });

        return modele;
    }

    Optional<User> existingUser = userRepository.findOneByEmail(userDTO.getEmail());
    if (existingUser.isPresent() && (!existingUser.get().getLogin().equalsIgnoreCase(userDTO.getLogin()))) {
        modele.put(Constants.ERROR, "true");
        modele.put(Constants.MESSAGE, "Email existe");
        modele.put(Constants.RESULTAT, "Opration echoue");

        return modele;
    }
    Optional<User> user = userRepository.findOneById(id);
    if (user.isPresent()) {
        userService.updateUser(id, userDTO.getLogin(), userDTO.getNom(), userDTO.getPrenom(),
                userDTO.getDateNaissance(), userDTO.getEmail(), userDTO.isActivated(), userDTO.getTel());

        modele.put(Constants.RESULTAT, "Opration russi");
        return modele;

    }
    modele.put(Constants.ERROR, "true");
    modele.put(Constants.MESSAGE, "Cet utilisateur n'existe pas");
    modele.put(Constants.RESULTAT, "Opration echoue");
    return modele;

}

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

/**
 * Creates a new Steward/*  ww w .  j  ava 2  s  .c o  m*/
 *
 * @param model display data
 * @return jsp page
 */
@RequestMapping(method = RequestMethod.POST, value = "/create")
public String create(@Valid @ModelAttribute("stewardCreate") StewardCreationalDTO formBean,
        BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes,
        UriComponentsBuilder uriBuilder, HttpServletRequest request) {
    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 "steward/new";
    }
    Long id = 0L;
    try {
        //            if (stewardFacade.getRelevantStewards(formBean.getPersonalIdentificator()) != null) {
        //                bindingResult.addError(new FieldError("stewardCreate", "personalIdentificator",
        //                        formBean.getPersonalIdentificator(), false, 
        //                        new String[]{"StewardCreationalDTOValidator.invalid.personalIdetificator"}, 
        //                        null, "Personal identificator already exists."));
        //                model.addAttribute("personalIdentificator_error", true);
        //                return "steward/new";
        //            }
        id = stewardFacade.createSteward(formBean);
        redirectAttributes.addFlashAttribute("alert_info", "Steward with id: " + id + " was created");
    } catch (Exception ex) {
        model.addAttribute("alert_danger", "Steward was not created because of some unexpected error");
        redirectAttributes.addFlashAttribute("alert_danger",
                "Steward was not created because of some unexpected error");
    }
    request.getSession().setAttribute("authenticated",
            stewardFacade.getStewardWithPersonalIdentificator(formBean.getPersonalIdentificator()));
    return "redirect:" + uriBuilder.path("/steward").toUriString();
}

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

@RequestMapping(value = "/edit", method = RequestMethod.POST)
public String edit(@Valid @ModelAttribute("teamEdit") TeamDTO formBean, BindingResult bindingResult,
        Model model, RedirectAttributes redirectAttributes, UriComponentsBuilder uriBuilder) {
    log.debug("edit(teamEdit={})", formBean);
    if (bindingResult.hasErrors()) {
        log.debug("some errror");
        for (ObjectError ge : bindingResult.getGlobalErrors()) {
            log.trace("ObjectError: {}", ge);

        }//from  w w  w. j  a  v  a  2 s .  com
        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
            log.trace("FieldError: {}", fe);
        }
        return "team/edit";

    }
    try {
        teamFacade.updateTeam(formBean);
        redirectAttributes.addFlashAttribute("alert_success", "Team was edited");
    } catch (Exception ex) {
        log.warn("cannot edit this team {}");
        redirectAttributes.addFlashAttribute("alert_danger",
                "Team's name has already exited or any errors happen, please check again!");
    }
    return "redirect:" + uriBuilder.path("/team/list").toUriString();

}

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

@RequestMapping(value = "/driver-create", method = RequestMethod.POST)
@ResponseBody/*w w  w  .ja va2  s  .co  m*/
public AdminResponseModel<String> addDriver(@Valid CreateDriverModel driverModel, BindingResult bindingResult) {
    System.out.println(driverModel);
    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.createDriverAccount(driverModel.toDriver());
    response.setResultSuccess().setContent(env.getRequiredProperty(MESSAGE_DRIVER_SUCCESS_CREATE));
    return response;
}

From source file:org.codeqinvest.web.project.CreateProjectController.java

/**
 * This methods handles the submitted form for creating a new project.
 *//*  w w  w. j  ava2  s .co m*/
@RequestMapping(value = "/create", method = RequestMethod.POST)
ModelAndView create(@ModelAttribute Project project, BindingResult bindingResult,
        @ModelAttribute("retrievedSonarProjectsAsJson") String sonarProjects, Model model) {

    projectConnectionsValidator.validate(project, bindingResult);
    if (bindingResult.hasErrors()) {
        log.info("Rejected creation of project due {} validation errors", bindingResult.getErrorCount());
        if (log.isDebugEnabled()) {
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                log.debug("Field {} has following error: {}", fieldError.getField(), fieldError.getCode());
            }
        }
        addDeserializedSonarProjectsToModel(sonarProjects, model);
        model.addAttribute("fieldErrors", bindingResult.getFieldErrors());
        return new ModelAndView("createProject");
    }

    // this little hack is necessary until a better way for binding the value from the form is found
    CodeChangeSettings codeChangeSettings = project.getCodeChangeSettings();
    if (codeChangeSettings.getMethod() == SupportedCodeChangeProbabilityMethod.COMMIT_BASED.getId()) {
        codeChangeSettings.setNumberOfCommits(codeChangeSettings.getDays());
        codeChangeSettings.setDays(null);
    }

    Project addedProject = projectRepository.save(project);
    analyzerScheduler.scheduleAnalyzer(addedProject);
    log.info("Created project {} and scheduled its quality analysis", project.getName());

    RedirectView redirect = new RedirectView("/projects/" + addedProject.getId());
    redirect.setExposeModelAttributes(false);
    return new ModelAndView(redirect);
}

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

/**
 *
 * @param member/*from   w w w  . j  a v  a2  s . c  o  m*/
 * @param result
 * @param model
 * @param request
 * @return
 */
@RequestMapping(value = "/updateuser", method = RequestMethod.POST)
public ModelAndView validateandUpdateUser(@Valid @ModelAttribute("UpdateMemberForm") ValidateMember member,
        BindingResult result, Model model, HttpServletRequest request) {

    String id = request.getParameter("id");

    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());
                sFormStatus.setsUsernameInput("has-error");
            }

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

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

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

    } else {

        String sUsername = request.getParameter("username");
        String sPassword = request.getParameter("password");
        String sEmail = request.getParameter("email");
        Long lUser_id = Long.parseLong(id);

        //try to save the form
        try {
            System.out.println(sUsername + " username" + sPassword + sEmail + lUser_id);
            Object update_result = userDao.updateUserInfo(lUser_id, sUsername, sPassword, sEmail);

            return new ModelAndView("redirect:/registeredmember.html?classerror=has-success&response="
                    + update_result + "&id=" + id + "");

        } catch (Exception e) {
            System.out.println(e.getMessage() + " Error updating form");
            return new ModelAndView(
                    "redirect:/registeredmember.html?response=The Data you have typed is already exist, try another one.&classerror=has-error&id="
                            + id + "");
        }

    }

}

From source file:cs544.wamp_blog_engine.controller.UserController.java

@RequestMapping(value = "/users/{id}", method = RequestMethod.POST)
public String updateUser(@Valid User user, BindingResult result, @PathVariable int id, HttpSession session) {
    //System.out.println("Update");
    if (!result.hasErrors()) {
        //System.out.println("done");
        session.setAttribute("user", user);
        userService.updateUserInfo(id, user);
        return "redirect:/users";
    } else {//  ww  w.ja va2 s .  com
        for (FieldError err : result.getFieldErrors()) {
            System.out.println(err.getField() + ": " + err.getDefaultMessage());
        }
        System.out.println("err");
        return "userDetail";
    }
}

From source file:com.biblio.web.rest.UserResource.java

@RequestMapping(value = "/register", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE,
        MediaType.TEXT_PLAIN_VALUE })//www .  ja  v  a  2  s .co  m

public Object createUser(@RequestBody @Valid ManagedUserVM managedUserVM, BindingResult bindingResult)
        throws MessagingException {
    Map<String, Object> modele = new HashMap<>();

    if (bindingResult.hasErrors()) {

        modele.put(Constants.ERROR, true);
        modele.put(Constants.MESSAGE, "Enregistrement chou");
        bindingResult.getFieldErrors().stream().forEach((f) -> {
            System.out.println("Field " + f.getField());
            System.out.println("error" + f.getDefaultMessage());
            modele.put(f.getField(), f.getDefaultMessage());
        });

        return modele;
    }

    if (userRepository.findOneByLogin(managedUserVM.getLogin()).isPresent()) {

        modele.put(Constants.ERROR, "true");
        modele.put(Constants.MESSAGE, "Enregistrement chou");
        modele.put("login", "Ce nom d'utilisateur existe deja");
        return modele;
    }

    if (userRepository.findOneByEmail(managedUserVM.getEmail()).isPresent()) {
        modele.put(Constants.ERROR, "true");
        modele.put(Constants.MESSAGE, "Enregistrement chou");
        modele.put("email", "Ce email est deja utilis");

        return modele;
    }

    managedUserVM.setPassword("123456");

    if (managedUserVM.getType() != null && managedUserVM.getType() == 2) {
        managedUserVM.getRoles().add(ConstantRole.ADMIN_ROLE);
    } else {
        managedUserVM.getRoles().add(ConstantRole.USER_ROLE);
    }

    managedUserVM.setPassword(RandomUtil.generateAlphaNumerique(8));
    User u = userService.createUser(managedUserVM);
    modele.put(Constants.MESSAGE, "Enregistrement russi");
    try {
        mailService.sendEmail(u.getEmail(), "Mot de passe", " Les parametre de compte\n Username : "
                + u.getLogin() + " \n password " + managedUserVM.getPassword(), true, true);
    } catch (Exception e) {
        System.out.println("ex");
        return modele;
    }
    return modele;
}

From source file:com.oak_yoga_studio.controller.ProductController.java

@RequestMapping(value = "/productEdit", method = RequestMethod.POST)
public String updateProduct(@Valid Product product, BindingResult result,
        @RequestParam("file") MultipartFile file) {

    if (!result.hasErrors()) {
        try {//from   w w w .j a va2 s .com
            product.setImage(file.getBytes());
            product.setStatus("ACTIVE");
            productService.updateProduct(product);
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        return "redirect:/products";
    } else {
        for (FieldError err : result.getFieldErrors()) {
            System.out.println(err.getField() + ": " + err.getDefaultMessage());

        }
        return "editProduct";
    }

}

From source file:com.redhat.rhtracking.web.controller.OpportunityController.java

@RequestMapping(value = "/opportunity/add", method = RequestMethod.POST)
public String save(@Valid @ModelAttribute("opportunityInfo") OpportunityInfo opportunityInfo,
        BindingResult result, RedirectAttributes redirectAttributes, Model model, Principal principal) {
    List<String> messages = Utils.getFlashMessagesList(model, redirectAttributes);

    if (result.hasErrors()) {
        messages.add("warning::Los datos introducidos contienen errores.");
        messages.add("info::errors found " + result.getFieldErrors());
        redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.register", result);
        redirectAttributes.addFlashAttribute("opportunityInfo", opportunityInfo);
        return "redirect:/opportunity/add";
    }/*ww  w .j  av  a2 s .c o m*/

    Map<String, Object> request = new HashMap<>();
    request.put("identifier", opportunityInfo.getId());
    request.put("project", opportunityInfo.getProject());
    request.put("opportunityType", opportunityInfo.getOpportunityType());
    request.put("customer", opportunityInfo.getCustomer());
    request.put("customerBilling", opportunityInfo.getCustomerBilling());
    //        request.put("startDate", opportunityInfo.getStartDate());
    //        request.put("endDate", opportunityInfo.getEndDate());
    request.put("currency", opportunityInfo.getCurrency());
    request.put("exchangeRate", opportunityInfo.getExchangeRate());

    request.put("platformHours", opportunityInfo.getPlatformHours());
    request.put("platformPrice", opportunityInfo.getPlatformPrice());
    request.put("middlewareHours", opportunityInfo.getMiddlewareHours());
    request.put("middlewarePrice", opportunityInfo.getMiddlewarePrice());
    request.put("workshopHours", opportunityInfo.getWorkshopHours());
    request.put("workshopPrice", opportunityInfo.getWorkshopPrice());

    Map<String, Object> response = deliveryMatrixService.saveOpportunity(request);
    switch ((EventStatus) response.get("status")) {
    case SUCCESS:
        messages.add("success::Oportunidad registrada.");
        return "redirect:/opportunity/show?id=" + opportunityInfo.getId();
    case DUPLICATED_KEY:
        messages.add("warning::Existe una oportinidad registrada con el id proporcionado");
        redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.register", result);
        redirectAttributes.addFlashAttribute("opportunityInfo", opportunityInfo);
        return "redirect:/opportunity/add";
    default:
        messages.add("error::Ocurrio una excepcion al registrar la oportunidad");
    }
    return "redirect:/opportunity/";
}