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.github.lynxdb.server.api.http.handlers.EpPut.java

@RequestMapping(path = "", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity put(Authentication _authentication, @RequestBody @Valid List<Metric> _request,
        BindingResult _bindingResult) {

    User user = (User) _authentication.getPrincipal();

    if (_bindingResult.hasErrors()) {
        ArrayList<String> errors = new ArrayList();
        _bindingResult.getFieldErrors().forEach((FieldError t) -> {
            errors.add(t.getField() + ": " + t.getDefaultMessage());
        });/*  ww  w  .  ja v  a  2  s .c o  m*/
        return new ErrorResponse(mapper, HttpStatus.BAD_REQUEST, errors.toString(), null).response();
    }

    List<com.github.lynxdb.server.core.Metric> metricList = new ArrayList<>();
    _request.stream().forEach((m) -> {
        metricList.add(new com.github.lynxdb.server.core.Metric(m));
    });

    try {
        entries.insertBulk(vhosts.byId(user.getVhost()), metricList);
    } catch (Exception ex) {
        throw ex;
    }
    return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
}

From source file:org.jasig.portlet.blackboardvcportlet.mvc.sessionmngr.ManageMediaFilesController.java

protected Map<String, String> getFieldErrors(BindingResult bindingResult) {
    final Map<String, String> fieldErrors = new LinkedHashMap<String, String>();
    for (FieldError error : bindingResult.getFieldErrors()) {
        fieldErrors.put(error.getField(), error.getDefaultMessage());
    }//w w  w .  j  a v  a2 s .  c  o  m
    return fieldErrors;
}

From source file:com.greenline.guahao.web.module.home.controllers.sitesmanage.CorrectController.java

/**
 * ???//from w ww. j a  va2s  .c om
 * 
 * @param model
 * @param request
 * @param po
 * @return
 */
@RequestMapping(value = "/submit", method = RequestMethod.POST)
@MethodRemark("remark=???")
@ResponseBody
public Map<String, Object> submit(@ModelAttribute() CorrectPO po, HttpServletRequest request,
        BindingResult result) {
    Map<String, Object> resp = new HashMap<String, Object>();
    List<FieldError> errors = null;
    correctValidator.validate(po, result);
    if (result.hasErrors()) {
        errors = result.getFieldErrors();
    } else {
        try {
            po.setDesc(po.getDesc().trim());
            CorrectDO o = correctConvertor.convertToCorrectDO(po);
            o.setSubmitPerson(UserCookieUtil.getLoginId(request));
            o.setType(po.getType());
            correctManager.addCorrect(o);
        } catch (Exception e) {
            log.error("?", e);
            errors = new ArrayList<FieldError>();
            errors.add(new FieldError("correct-add", "correct-add.error", "???"));
        }
    }
    resp.put("errors", errors);
    return resp;
}

From source file:org.frat.common.exception.BindingResultExceptionHandler.java

/**
 * // w  w w.ja  v  a  2s .co m
 * Description: set the result dto.
 * 
 * @param locale
 * 
 * @param constraintViolation
 * @throws NoSuchFieldException
 */
private void setResultDto(BindingResult bindingResult, List<ValidationResultDto> errorData, String formId,
        boolean notManually) {
    List<FieldError> fieldErros = bindingResult.getFieldErrors();
    String beanName = bindingResult.getObjectName();
    Object rootObject = bindingResult.getTarget();
    Class<?> rootClass = rootObject.getClass();
    if (fieldErros != null && fieldErros.size() > 0) {
        for (FieldError fieldError : fieldErros) {
            final String fieldName = fieldError.getField();
            String message = fieldError.getDefaultMessage();
            final String errorCode = fieldError.getCode();
            if (StringUtils.isEmpty(message)) {
                message = MessageUtil.getMessage(StringUtils.isNotEmpty(errorCode) ? errorCode : message);
            }
            setFieldErrorMap(fieldName, beanName, rootClass, errorData, message, formId, notManually);
        }
    }
}

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

@RequestMapping(value = "/create", method = RequestMethod.POST)
@RolesAllowed("ADMIN")
public String createDog(Model model, @Valid @ModelAttribute("dog") DogDTO dogDTO, BindingResult bindingResult,
        UriComponentsBuilder uriBuilder, RedirectAttributes redirectAttributes) {
    if (bindingResult.hasErrors()) {
        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
        }//from w  ww .  ja va2  s. c  o m
        return "dogs/create";
    }
    try {
        dogDTO = facade.createDog(dogDTO);
        Long id = dogDTO.getId();

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

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

@RequestMapping(value = "/update", method = RequestMethod.POST)
@RolesAllowed("ADMIN")
public String updateDog(Model model, @Valid @ModelAttribute("dog") DogDTO dogDTO, BindingResult bindingResult,
        UriComponentsBuilder uriBuilder, RedirectAttributes redirectAttributes) {
    if (bindingResult.hasErrors()) {
        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
        }/*from   www  . j  ava 2s.co  m*/
        return "/dogs/edit";
    }

    Long id = dogDTO.getId();
    try {
        facade.updateDog(dogDTO);
        redirectAttributes.addFlashAttribute("alert_success", "Dog #" + id + " was updated.");
        return "redirect:" + uriBuilder.path("/dogs/view/{id}").buildAndExpand(id).encode().toUriString();
    } catch (Exception e) {
        log.warn("Exception wile updating: " + e.getMessage());
        redirectAttributes.addFlashAttribute("alert_danger", "Dog #" + id + " was not edited.");
        return "redirect:/";
    }

}

From source file:org.ng200.openolympus.controller.contest.ContestCreationController.java

@RequestMapping(method = RequestMethod.POST)
public String createContest(final Model model, final HttpServletRequest request,
        @Valid final ContestDto contestDto, final BindingResult bindingResult)
        throws IllegalStateException, IOException, ArchiveException {

    this.contestDtoValidator.validate(contestDto, bindingResult);

    if (bindingResult.hasErrors()) {
        ContestCreationController.logger.info(bindingResult.getFieldErrors().toString());
        model.addAttribute("mode", "add");

        return "contest/add";
    }/*from w  w  w  .  java  2 s. com*/
    Contest contest = new Contest(contestDto.getStartTime(), contestDto.getDuration() * 60 * 1000,
            contestDto.getName(), new HashSet<>());
    contest = this.contestRepository.save(contest);
    return "redirect:/contests";
}

From source file:cz.muni.fi.editor.webapp.controllers.ajax.AjaxUserController.java

@RequestMapping(value = "/", method = RequestMethod.POST)
public @ResponseBody ValidationResponse processUpdateuser(Model model,
        @RequestBody @Valid UserFormProfile userFormProfile, BindingResult bindingResult) {
    ValidationResponse response = new ValidationResponse();
    if (bindingResult.hasErrors()) {
        response.setStatus("FAIL");

        List<ErrorMessage> messages = new ArrayList<>();

        for (FieldError error : bindingResult.getFieldErrors()) {
            ErrorMessage em = new ErrorMessage();
            em.setField(error.getField());
            em.setMessage(error.getDefaultMessage());

            messages.add(em);// w w w .jav a 2 s . co m
        }

        response.setMessages(messages);
    } else {
        try {
            userService.update(mapper.map(userFormProfile, UserDTO.class));
            response.setStatus("SUCCESS");
        } catch (FieldException ex) {
            log.warn(ex);
            response.setStatus("FAIL");
        }

    }

    return response;
}

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

/**
 * Creates a new Destination/*ww  w .j a  v  a2 s .  c om*/
 * @param model display data
 * @return jsp page
 */
@RequestMapping(method = RequestMethod.POST, value = "/create")
public String create(@Valid @ModelAttribute("destinationCreate") DestinationCreationalDTO formBean,
        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/new";
    }
    try {
        if (destinationFacade.getDestinationWithLocation(formBean.getLocation()) == null) {
            bindingResult.addError(new FieldError("destinationCreate", "location",
                    "Destination was not created because it already exists."));
            model.addAttribute("location_error", true);
            return "destination/new";
        }

        Long id = destinationFacade.createDestination(formBean);
        redirectAttributes.addFlashAttribute("alert_info", "Destination with id: " + id + " was created");
    } catch (Exception ex) {
        model.addAttribute("alert_danger", "Destination was not created because of some unexpected error");
        redirectAttributes.addFlashAttribute("alert_danger",
                "Destination was not created because it already exists.");
    }
    return "redirect:" + uriBuilder.path("/destination").toUriString();
}

From source file:com.nicodewet.web.SubscribeController.java

@RequestMapping(value = "/subscribeth.json", method = RequestMethod.POST)
public @ResponseBody ValidationResponse processForm(@Valid final Subscription subscription,
        final BindingResult bindingResult, final ModelMap model) {
    logger.info("Validation");
    ValidationResponse res = new ValidationResponse();
    if (!bindingResult.hasErrors()) {
        res.setStatus("SUCCESS");
    } else {//from w w w  .j  a va2 s. c om
        res.setStatus("FAIL");
        List<FieldError> allErrors = bindingResult.getFieldErrors();
        List<ErrorMessage> errorMesages = new ArrayList<ErrorMessage>();
        for (FieldError objectError : allErrors) {
            errorMesages.add(new ErrorMessage(objectError.getField(),
                    objectError.getField() + "  " + objectError.getDefaultMessage()));
        }
        res.setErrorMessageList(errorMesages);
    }
    return res;
}