org.springframework.validation.BindException类的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(12.3k)|赞(0)|评价(0)|浏览(143)

本文整理了Java中org.springframework.validation.BindException类的一些代码示例,展示了BindException类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。BindException类的具体详情如下:
包路径:org.springframework.validation.BindException
类名称:BindException

BindException介绍

[英]Thrown when binding errors are considered fatal. Implements the BindingResult interface (and its super-interface Errors) to allow for the direct analysis of binding errors.

As of Spring 2.0, this is a special-purpose class. Normally, application code will work with the BindingResult interface, or with a DataBinder that in turn exposes a BindingResult via org.springframework.validation.DataBinder#getBindingResult().
[中]当绑定错误被认为是致命错误时引发。实现BindingResult接口(及其超级接口错误),以允许直接分析绑定错误。
从Spring2.0开始,这是一个特殊用途的类。通常,应用程序代码将与BindingResult接口一起工作,或者与DataBinder一起工作,后者反过来通过org公开BindingResult。springframework。验证。DataBinder#getBindingResult()。

代码示例

代码示例来源:origin: spring-projects/spring-framework

tb.setName("empty &");
Errors errors = new EscapedErrors(new BindException(tb, "tb"));
errors.rejectValue("name", "NAME_EMPTY &", null, "message: &");
errors.rejectValue("age", "AGE_NOT_SET <tag>", null, "message: <tag>");
errors.rejectValue("age", "AGE_NOT_32 <tag>", null, "message: <tag>");
errors.reject("GENERAL_ERROR \" '", null, "message: \" '");
assertTrue("Correct number of field errors in list", errors.getFieldErrors().size() == 3);
FieldError fieldError = errors.getFieldError();
assertTrue("Field error code not escaped", "NAME_EMPTY &".equals(fieldError.getCode()));
assertTrue("Field value escaped", "empty &amp;".equals(errors.getFieldValue("name")));
FieldError fieldErrorInList = errors.getFieldErrors().get(0);
assertTrue("Same field error in list", fieldError.getDefaultMessage().equals(fieldErrorInList.getDefaultMessage()));
assertTrue("Correct name errors flag", errors.hasFieldErrors("name"));

代码示例来源:origin: hs-web/hsweb-framework

@ExceptionHandler(BindException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
ResponseMessage handleException(BindException e) {
  SimpleValidateResults results = new SimpleValidateResults();
  e.getBindingResult().getAllErrors()
      .stream()
      .filter(FieldError.class::isInstance)
      .map(FieldError.class::cast)
      .forEach(fieldError -> results.addResult(fieldError.getField(), fieldError.getDefaultMessage()));
  return ResponseMessage.error(400, results.getResults().isEmpty() ? e.getMessage() : results.getResults().get(0).getMessage()).result(results.getResults());
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void modelAndView() throws Exception {
  BindException bindException = new BindException(new Object(), "target");
  bindException.reject("errorCode");
  ModelAndView mav = new ModelAndView("viewName");
  mav.addObject("attrName", "attrValue");
  mav.addObject(BindingResult.MODEL_KEY_PREFIX + "attrName", bindException);
  this.mvcResult.setMav(mav);
  this.handler.handle(this.mvcResult);
  assertValue("ModelAndView", "View name", "viewName");
  assertValue("ModelAndView", "View", null);
  assertValue("ModelAndView", "Attribute", "attrName");
  assertValue("ModelAndView", "value", "attrValue");
  assertValue("ModelAndView", "errors", bindException.getAllErrors());
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void testBindExceptionSerializable() throws Exception {
  SerializablePerson tb = new SerializablePerson();
  tb.setName("myName");
  tb.setAge(99);
  BindException ex = new BindException(tb, "tb");
  ex.reject("invalid", "someMessage");
  ex.rejectValue("age", "invalidField", "someMessage");
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  ObjectOutputStream oos = new ObjectOutputStream(baos);
  oos.writeObject(ex);
  ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
  ObjectInputStream ois = new ObjectInputStream(bais);
  BindException ex2 = (BindException) ois.readObject();
  assertTrue(ex2.hasGlobalErrors());
  assertEquals("invalid", ex2.getGlobalError().getCode());
  assertTrue(ex2.hasFieldErrors("age"));
  assertEquals("invalidField", ex2.getFieldError("age").getCode());
  assertEquals(new Integer(99), ex2.getFieldValue("age"));
  ex2.rejectValue("name", "invalidField", "someMessage");
  assertTrue(ex2.hasFieldErrors("name"));
  assertEquals("invalidField", ex2.getFieldError("name").getCode());
  assertEquals("myName", ex2.getFieldValue("name"));
}

代码示例来源:origin: openmrs/openmrs-core

/**
 * @see PersonValidator#validate(Object,Errors)
 */

@Test
public void validate_shouldFailValidationIfDeathDateIsAFutureDate() {
  Patient pa = new Patient(1);
  Calendar death = Calendar.getInstance();
  death.setTime(new Date());
  death.add(Calendar.YEAR, 20);
  pa.setDeathDate(death.getTime());
  Errors errors = new BindException(pa, "patient");
  validator.validate(pa, errors);
  
  Assert.assertTrue(errors.hasFieldErrors("deathDate"));
}

代码示例来源:origin: openmrs/openmrs-core

/**
 * @see PersonAddressValidator#validate(Object,Errors)
 */
@Test
public void validate_shouldFailIfTheStartDateIsInTheFuture() {
  PersonAddress personAddress = new PersonAddress();
  Calendar c = Calendar.getInstance();
  // put the time into the future by a minute
  c.add(Calendar.MINUTE, 1);
  personAddress.setStartDate(c.getTime());
  Errors errors = new BindException(personAddress, "personAddress");
  validator.validate(personAddress, errors);
  Assert.assertEquals(true, errors.hasFieldErrors());
}

代码示例来源:origin: openmrs/openmrs-core

/**
 * @see VisitValidator#validate(Object,Errors)
 */
@Test
public void validate_shouldFailIfVisitTypeIsNotSet() {
  Visit visit = new Visit();
  visit.setPatient(Context.getPatientService().getPatient(2));
  visit.setStartDatetime(new Date());
  Errors errors = new BindException(visit, "visit");
  new VisitValidator().validate(visit, errors);
  assertTrue(errors.hasFieldErrors("visitType"));
}

代码示例来源:origin: openmrs/openmrs-core

/**
 * @see ObsValidator#validate(java.lang.Object, org.springframework.validation.Errors)
 */
@Test
public void validate_shouldPassValidationIfAllValuesPresent() {
  Obs obs = new Obs();
  obs.setPerson(Context.getPersonService().getPerson(2));
  obs.setConcept(Context.getConceptService().getConcept(5089));
  obs.setObsDatetime(new Date());
  obs.setValueNumeric(1.0);
  
  Errors errors = new BindException(obs, "obs");
  obsValidator.validate(obs, errors);
  
  assertFalse(errors.hasErrors());
}

代码示例来源:origin: openmrs/openmrs-core

/**
 * @see PatientProgramValidator#validate(Object,Errors)
 */
@Test
public void validate_shouldFailIfPatientProgramEndDateIsInFuture() {
  PatientProgram program = Context.getProgramWorkflowService().getPatientProgram(1);
  Date date10DaysAfterSystemCurrentDate = new Date(System.currentTimeMillis() + 10 * 24 * 60 * 60 * 1000);
  program.setDateCompleted(date10DaysAfterSystemCurrentDate);
  
  BindException errors = new BindException(program, "");
  new PatientProgramValidator().validate(program, errors);
  Assert.assertTrue(errors.hasFieldErrors("dateCompleted"));
}

代码示例来源:origin: openmrs/openmrs-core

/**
 * @see ObsValidator#validate(java.lang.Object, org.springframework.validation.Errors)
 */
@Test
public void validate_shouldFailIfObsHasNoValuesAndNotParent() {
  
  Obs obs = new Obs();
  obs.setPerson(Context.getPersonService().getPerson(2));
  obs.setConcept(Context.getConceptService().getConcept(18));
  obs.setObsDatetime(new Date());
  
  Errors errors = new BindException(obs, "obs");
  obsValidator.validate(obs, errors);
  
  assertTrue(errors.getGlobalErrorCount() > 0);
}

代码示例来源:origin: openmrs/openmrs-core

/**
 * @see PatientProgramValidator#validate(Object,Errors)
 */
@Test
public void validate_shouldPassValidationIfFieldLengthsAreCorrect() {
  ProgramWorkflowService pws = Context.getProgramWorkflowService();
  Patient patient = Context.getPatientService().getPatient(6);
  
  PatientProgram pp = new PatientProgram();
  pp.setPatient(patient);
  pp.setProgram(pws.getProgram(1));
  pp.setDateEnrolled(new Date());
  
  pp.setVoidReason("voidReason");
  
  BindException errors = new BindException(pp, "program");
  new PatientProgramValidator().validate(pp, errors);
  Assert.assertEquals(false, errors.hasErrors());
}

代码示例来源:origin: openmrs/openmrs-core

/**
 * @see PersonValidator#validate(Object,Errors)
 */
@Test
public void validate_shouldFailValidationIfCauseOfDeathIsBlankWhenPatientIsDead() {
  Patient pa = new Patient(1);
  pa.setDead(true);
  
  Errors errors = new BindException(pa, "patient");
  validator.validate(pa, errors);
  
  Assert.assertTrue(errors.hasFieldErrors("causeOfDeath"));
  Assert.assertEquals("Person.dead.causeOfDeathAndCauseOfDeathNonCodedNull", errors.getFieldError("causeOfDeath").getCode());
  
}

代码示例来源:origin: xie19900123/spring-boot-learning

@ExceptionHandler(BindException.class)
@ResponseBody
public Map<String,Object> handleBindException(BindException ex) {
  //校验 除了 requestbody 注解方式的参数校验 对应的 bindingresult 为 BeanPropertyBindingResult
  FieldError fieldError = ex.getBindingResult().getFieldError();
  log.info("必填校验异常:{}({})", fieldError.getDefaultMessage(),fieldError.getField());
  Map<String,Object> result = new HashMap<String,Object>();
  result.put("respCode", "01002");
  result.put("respMsg", fieldError.getDefaultMessage());
  return result;
}

代码示例来源:origin: leecho/cola-cloud

@ResponseBody
@ExceptionHandler(BindException.class)
@ResponseStatus(HttpStatus.OK)
public Result handleBindException(BindException e) {
  log.error(ErrorStatus.ILLEGAL_DATA.getMessage() + ":" + e.getMessage());
  List<Map<String, Object>> fields = new ArrayList<>();
  for (FieldError error : e.getFieldErrors()) {
    Map<String, Object> field = new HashMap<>();
    field.put("field", error.getField());
    field.put("message", error.getDefaultMessage());
    fields.add(field);
  }
  return failure(ErrorStatus.ILLEGAL_DATA, fields);
}

代码示例来源:origin: br.org.sesc/sesc-commons-rest

@Override
public void convert(final BindException exception) {
  final BindingResult bind = exception.getBindingResult();
  for (final FieldError o : bind.getFieldErrors()) {
    fields.add(new FieldErrorMessageError(o.getField(), getMessageSource().getMessage(o.getCode(),
        o.getArguments())));
  }
  setMessage(getMessageSource().getMessage(getCode()));
}

代码示例来源:origin: openmrs/openmrs-core

/**
 * @see org.openmrs.validator.PatientValidator#validate(Object,Errors)
 */
@Test
public void validate_shouldFailValidationIfGenderIsBlank() {
  Patient pa = new Patient(1);
  Errors errors = new BindException(pa, "patient");
  validator.validate(pa, errors);
  
  Assert.assertTrue(errors.hasFieldErrors("gender"));
}

代码示例来源:origin: spring-projects/spring-security-oauth2-boot

@Override
public boolean matches(Object item) {
  BindException ex = (BindException) ((Exception) item).getCause();
  ObjectError error = ex.getAllErrors().get(0);
  boolean messageMatches = message.equals(error.getDefaultMessage());
  if (field == null) {
    return messageMatches;
  }
  String fieldErrors = ((FieldError) error).getField();
  return messageMatches && fieldErrors.equals(field);
}

代码示例来源:origin: openmrs/openmrs-core

/**
 * @see ProgramValidator#validate(Object,Errors)
 */
@Test
public void validate_shouldPassValidationIfFieldLengthsAreCorrect() {
  Program prog = new Program();
  prog.setName("Hypochondriasis program");
  prog.setConcept(Context.getConceptService().getConcept(3));
  
  Errors errors = new BindException(prog, "prog");
  programValidator.validate(prog, errors);
  
  Assert.assertFalse(errors.hasErrors());
}

代码示例来源:origin: openmrs/openmrs-core

@Test
public void validate_shouldRequireDatatypeClassname() {
  
  validator.validate(attributeType, errors);
  
  Assert.assertTrue(errors.hasFieldErrors("datatypeClassname"));
  assertThat(errors.getFieldErrors("datatypeClassname").get(0).getCode(), is("error.null"));
}

代码示例来源:origin: spring-projects/spring-batch

/**
 * @see Validator#validate(Object)
 */
@Override
public void validate(T item) throws ValidationException {
  if (!validator.supports(item.getClass())) {
    throw new ValidationException("Validation failed for " + item + ": " + item.getClass().getName()
        + " class is not supported by validator.");
  }
  BeanPropertyBindingResult errors = new BeanPropertyBindingResult(item, "item");
  validator.validate(item, errors);
  if (errors.hasErrors()) {
    throw new ValidationException("Validation failed for " + item + ": " + errorsToString(errors), new BindException(errors));
  }
}

相关文章