2010-11-02 19 views
12

模型之前....JSR-303類型檢查綁定

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

豆文件....

<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); 
    } 

我如何限制「價值」只是數字?如果我輸入比一些其他的東西,我得到這個錯誤:

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,但我不知道如何使用它,或者如果它甚至會幫助我。這必須在之前解決。有沒有辦法確保它是一個數字,然後它被綁定?

或者,如果有人可以張貼正確messages.properties項覆蓋此錯誤,這可能會爲我工作了。

我試圖@Pattern但正如你所說,它不是整數

回答

24

工作,你需要在messages.properties一個用戶友好的消息。您可以使用下面的消息代碼之一(有不同程度的選擇性):

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

此外,當你不知道消息代碼,您可以簡單地打印BindingResult - 其toString()返回綁定器的完整描述RORS。

+0

你能不能解釋更詳細? – 2011-11-01 09:17:10

+0

對messages.properties的正確位置的更多細節,並宣佈其位於.xml配置文件中這樣的回答:http://stackoverflow.com/questions/6540300/spring-3-0-mvc-seems-to-be-忽略的消息的屬性 – 2012-04-19 18:13:36

+4

似乎這裏是一個循環引用,這個答案指向指向回到這個答案的答案(更多解釋)! – gresdiplitude 2012-06-25 09:56:09