Example usage for org.springframework.validation FieldError getField

List of usage examples for org.springframework.validation FieldError getField

Introduction

In this page you can find the example usage for org.springframework.validation FieldError getField.

Prototype

public String getField() 

Source Link

Document

Return the affected field of the object.

Usage

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

@RequestMapping(value = "/edit", method = RequestMethod.POST)
public String edit(@Valid @ModelAttribute("playerEdit") PlayerCreateDTO formBean, BindingResult bindingResult,
        Model model, RedirectAttributes redirectAttributes, UriComponentsBuilder uriBuilder) {
    log.debug("edit(playerEdit={})", formBean);
    //in case of validation error forward back to the the form
    if (bindingResult.hasErrors()) {
        log.debug("some errror");
        for (ObjectError ge : bindingResult.getGlobalErrors()) {
            log.trace("ObjectError: {}", ge);

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

    }

    if (formBean.getName().equals("")) {
        redirectAttributes.addFlashAttribute("alert_warning",
                "Player updating failed - Player name cannot be emty string!");
        return "redirect:" + uriBuilder.path("/player/edit").build().encode().toUriString();
    }

    if (formBean.getDateOfBirth().compareTo(new Date()) > 0) {
        redirectAttributes.addFlashAttribute("alert_warning",
                "Player updaeting failed - Player datee cannot be bigger than actuall date!");
        return "redirect:" + uriBuilder.path("/player/edit").build().encode().toUriString();
    }
    playerFacade.updatePlayer(convertPlayerCreateDTO(formBean));

    //report success
    redirectAttributes.addFlashAttribute("alert_success", "Player was edited");
    return "redirect:" + uriBuilder.path("/player/list").toUriString();

}

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

@RequestMapping(value = "/create", method = RequestMethod.POST)
public String create(@Valid @ModelAttribute("playerCreate") PlayerCreateDTO formBean,
        BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes,
        UriComponentsBuilder uriBuilder) {
    log.debug("create(playerCreate={})", formBean);
    //in case of validation error forward back to the the form
    if (bindingResult.hasErrors()) {
        log.debug("some errror");
        for (ObjectError ge : bindingResult.getGlobalErrors()) {
            log.trace("ObjectError: {}", ge);

        }/*from www.  jav  a2  s. co  m*/
        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
            log.trace("FieldError: {}", fe);
        }
        return "player/new";

    }

    //create player
    if (formBean.getName().equals("")) {
        redirectAttributes.addFlashAttribute("alert_warning",
                "Player creation failed - Player name cannot be emty string!");
        return "redirect:" + uriBuilder.path("/player/new").build().encode().toUriString();
    }

    if (formBean.getDateOfBirth().compareTo(new Date()) > 0) {
        redirectAttributes.addFlashAttribute("alert_warning",
                "Player creation failed - Player date cannot be bigger than actuall date!");
        return "redirect:" + uriBuilder.path("/player/new").build().encode().toUriString();
    }

    Long id = playerFacade.createPlayer(convertPlayerCreateDTO(formBean));

    //report success
    redirectAttributes.addFlashAttribute("alert_success",
            "Player " + playerFacade.findById(id).toString() + " was created");
    return "redirect:" + uriBuilder.path("/player/list").buildAndExpand(id).encode().toUriString();
}

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

/**
 * Iterate over object errors and load it on allErrorsMessages map.
 * <p/>//from w w  w. ja va2 s  .c om
 * Delegates on {@link #loadObjectError(FieldError, String, Map)}
 * 
 * @param fieldErrors
 * @param allErrorsMessages
 */
private void loadObjectErrors(List<FieldError> fieldErrors, Map<String, Object> allErrorsMessages) {

    for (FieldError error : fieldErrors) {
        loadObjectError(error, error.getField(), allErrorsMessages);
    }

}

From source file:org.mifos.loan.service.StandardLoanServiceTest.java

private void assertExpectedError(MifosServiceException mifosServiceException, String fieldName,
        String defaultErrorMessage) {
    Assert.assertEquals(1, mifosServiceException.getErrors().getErrorCount());
    FieldError error = (FieldError) mifosServiceException.getErrors().getFieldErrors().get(0);
    Assert.assertEquals(error.getField(), fieldName);
    Assert.assertEquals(error.getDefaultMessage(), defaultErrorMessage);
}

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

@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String add(@Valid User user, BindingResult result, HttpSession session, RedirectAttributes flashAttr,
        @RequestParam("file") MultipartFile file) {
    String view = "redirect:/";
    System.out.println("userController Add");

    if (!result.hasErrors()) {
        try {//  w ww. ja va2 s.co m
            user.setProfilepic(file.getBytes());
        } catch (IOException ex) {
            Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
        }
        userService.addUser(user);
        session.removeAttribute("credential");
        flashAttr.addFlashAttribute("successfulSignup",
                "User signed up succesfully. please  log in to proceed");
        User u = (User) session.getAttribute("loggedUser");
        if (u != null && u.getUserCredential().isAdmin()) {
            view = "redirect:/settings";
        }
    } else {
        for (FieldError err : result.getFieldErrors()) {
            System.out.println("Error:" + err.getField() + ":" + err.getDefaultMessage());
        }
        view = "addUser";
    }
    return view;
}

From source file:org.apigw.authserver.web.admin.DefaultAdminExceptionHandler.java

private ValidationErrorDTO processFieldErrors(List<FieldError> fieldErrors) {
    ValidationErrorDTO dto = new ValidationErrorDTO();

    for (FieldError fieldError : fieldErrors) {

        String localizedErrorMessage = null; //resolveLocalizedErrorMessage(fieldError);
        log.debug("Adding error message: {} to field: {}", localizedErrorMessage, fieldError.getField());
        dto.addFieldError(fieldError.getField(), fieldError.getCode(), localizedErrorMessage);
    }/*from  www.j a v a2  s .c  o m*/

    return dto;
}

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

/**
 *
 * @param member//from  w  w w  . j a va 2 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:cz.muni.fi.dndtroopsweb.controllers.HeroController.java

/**
 * Creates hero based on filled form/*from  w ww  .j  a va2s. c om*/
 *
 * @param formBean hero to be created
 * @return Details of created hero
 */
@RequestMapping(value = "/create", method = RequestMethod.POST)
public String create(@Valid @ModelAttribute("heroCreate") HeroCreateDTO formBean, BindingResult bindingResult,
        Model model, RedirectAttributes redirectAttributes, UriComponentsBuilder uriBuilder) {
    log.debug("create(heroCreate={})", formBean);
    //in case of validation error forward back to the the form
    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 "hero/new";
    }
    Long id = heroFacade.createHero(formBean);
    redirectAttributes.addFlashAttribute("alert_success", "Hero " + id + " was created");
    return "redirect:" + uriBuilder.path("/hero/details/{id}").buildAndExpand(id).encode().toUriString();
}

From source file:cz.muni.fi.dndtroopsweb.controllers.HeroController.java

/**
 * Changes hero's role/* www . j  av  a  2s .co  m*/
 *
 * @param formBean hero whose role will be changed
 * @return Details of hero whose role has been changed
 */
@RequestMapping(value = "/change/{id}", method = RequestMethod.POST)
public String change(@PathVariable long id, @Valid @ModelAttribute("hero") HeroDTO formBean,
        BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes,
        UriComponentsBuilder uriBuilder) {
    log.debug("change role(hero={})", formBean);
    //in case of validation error forward back to the the form
    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 "hero/role";
    }
    heroFacade.changeRole(id, formBean.getRole());
    redirectAttributes.addFlashAttribute("alert_success", "Role was changed");
    return "redirect:" + uriBuilder.path("/hero/details/{id}").buildAndExpand(id).encode().toUriString();
}

From source file:cz.muni.fi.dndtroopsweb.controllers.HeroController.java

/**
 * Insert hero into troop/*from w w  w  .  ja  v  a  2 s  .  c  om*/
 *
 * @param formBean hero to be added into troop
 * @return Details of hero who has been inserted
 */
@RequestMapping(value = "/add/{id}", method = RequestMethod.POST)
public String add(@PathVariable long id, @Valid @ModelAttribute("hero") HeroDTO formBean,
        BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes,
        UriComponentsBuilder uriBuilder) {
    log.debug("add troop(hero={})", formBean);
    //in case of validation error forward back to the the form
    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 "hero/troop";
    }
    if (heroFacade.getHeroWithId(id).getTroop() != null) {
        redirectAttributes.addFlashAttribute("alert_warning",
                "Hero \"" + heroFacade.getHeroWithId(id).getName() + "\" is already in troop");
        return "redirect:" + uriBuilder.path("/hero/details/" + id).toUriString();
    }
    heroFacade.addTroop(id, formBean.getId());
    redirectAttributes.addFlashAttribute("alert_success", "Hero added into Troop");
    return "redirect:" + uriBuilder.path("/hero/details/{id}").buildAndExpand(id).encode().toUriString();
}