JSR-303绑定前的类型检查 [英] JSR-303 Type Checking Before Binding

查看:59
本文介绍了JSR-303绑定前的类型检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模型....

@Digits(integer=5, fraction=0, message="The value must be numeric and less than five digits")
private int value;

beans文件....

beans file....

<mvc:annotation-driven />

控制器....

@RequestMapping(value = "/admin/save.htm", method = { RequestMethod.POST })
public ModelAndView saveSection(@Valid @ModelAttribute Section section, BindingResult result) {
     if(result.hasErrors())   {
         return new ModelAndView("admin/editSection", "section", section);
     }

如何将值"限制为仅数字?如果我输入的不是数字,则会出现此错误:

How do I restrict "value" to just numerics? If I enter something other than a number, I get this error:

无法转换的属性值 将java.lang.String键入所需的类型 属性的java.lang.Integer 价值;嵌套的异常是 org.springframework.core.convert.ConversionFailedException: 无法从类型转换值"A" 要键入的java.lang.String java.lang.Integer;嵌套的异常是 java.lang.IllegalArgumentException: 无法解析A

Failed to convert property value of type java.lang.String to required type java.lang.Integer for property value; nested exception is org.springframework.core.convert.ConversionFailedException: Unable to convert value "A" from type java.lang.String to type java.lang.Integer; nested exception is java.lang.IllegalArgumentException: Unable to parse A

我看到一些帖子提到了initBinding,但是我不确定如何使用它,或者它是否可以帮助我.这必须已经解决过.有什么方法可以确保它在绑定之前是一个数字?

I have seen a few posts mention initBinding but I'm not sure how to use it or if it will even help me out. This has to have been solved before. Is there any way to ensure that it is a number before it gets binded?

或者,如果有人可以发布正确的messages.properties条目来覆盖此错误,那么这对我也可以工作.

Or, if someone could post the correct messages.properties entry to override this error, that could work for me too.

我尝试了@Pattern,但不适用于int

I tried @Pattern but that doesn't work on ints

推荐答案

如前所述,您需要在messages.properties中提供一条用户友好的消息.您可以使用以下消息代码之一(具有不同的选择性级别):

As you mentioned, you need a user-friendly message in messages.properties. You can use one of the following message codes (with different levels of selectivity):

  • typeMismatch.section.value
  • typeMismatch.value
  • typeMismatch.int
  • typeMismatch
  • typeMismatch.section.value
  • typeMismatch.value
  • typeMismatch.int
  • typeMismatch

此外,当您不知道消息代码时,只需打印BindingResult-其toString()返回绑定错误的完整说明.

Also, when you don't know message code, you can simply print the BindingResult - its toString() returns the full description of the binding errors.

这篇关于JSR-303绑定前的类型检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆