C
C
click_f2016-09-15 16:22:22
Java
click_f, 2016-09-15 16:22:22

What is BindingResult used for in java?

Although I got acquainted with the official documentation of Spring, I did not understand the motivation and purpose of this interface.
What is it used for and in what cases can it be useful?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evhen, 2016-09-15
@click_f

From it, we can find out whether there were validation errors and what kind of http request for an object in the controller was when bidenging.
For example, this is our controller

@Controller
public class SearchCommentController {

  ...................

  @RequestMapping(method = RequestMethod.POST)
  public String displayCommentAlert(@Validated FormParams params, BindingResult bindingResult, Model model) {
    if (bindingResult.hasErrors() == false) {
      List<CommentWithPeopleDetail> foundComments = commentDao.find(params);
      model.addAttribute("foundComments", foundComments);
    }
    return "commentAlert";
  }

  ...................
}

bindingResult is injected by sprig into the controller method
here is the validator
public class SearchCommentParamValidator implements Validator {

  @Override
  public boolean supports(Class<?> clazz) {
    return FormParams.class.isAssignableFrom(clazz);
  }

  @Override
  public void validate(Object target, Errors errors) {

    FormParams params = (FormParams) target;

    if (StringUtils.isBlank(params.getRuleId()) && StringUtils.isBlank(params.getRef())) {
      errors.reject(null, "Необходимо указать или 'ID правила', и/или 'Объект алерта'!");
    } else if (params.getDateFrom() == null || params.getDateTo() == null) {
      errors.reject(null, "Необходимо указать период поиска!");
    }
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question