2012-01-30 55 views
1

我已經爲我的JSP表單實現了自定義驗證,並且當出現錯誤時,返回表單並將我的錯誤綁定到BindingResult。我的形式看起來像:我怎樣才能讓我的錯誤(在BindingResult)綁定到我的領域?

<form:form name="createCustomer" action="/practicemvc/customers/create/" method="POST" modelAttribute="customerBean"> 

    <form:errors /> 

    <label for="customerName">Name</label> 
    <input type="text" name="name" id="customerName" value="${customerBean.name}" /> 
    <form:errors path="name" /> 

顯示在錯誤:

<form:errors /> 

但是,他們沒有被顯示通過:

<form:errors path="name" /> 

我的錯誤被合併到BindingResult有:

for(ErrorType errorType: validationResult.getErrors()) { 
    bindingResult.addError(new ObjectError(errorType.getProperty(), 
      new String[]{errorType.getErrorCode()}, null, null)); 
} 

getPro perty()將返回「name」,getErrorCode()返回「INVALID_EMAIL」。 「INVALID_EMAIL」通過我的messageSource bean轉換爲「您的電子郵件無效」。如果我在BindingResult中查看錯誤的內容,一切似乎都沒問題,但它們在我的JSP中沒有按預期輸出。有任何想法嗎?

感謝,B

回答

3

至於我記得,出錯消息,你需要一個FieldError場,其中objectNamecustomerBeanfield關聯的字段名。

+0

要小心,讓objectName像表單中的commandName一樣,並且像className一樣。請參閱:http://ansaurus.com/question/1363753-spring-mvc-tag-doesnt-find-error-messages – 2013-03-08 14:31:40

+0

但*字段*沒有吸氣劑 – gstackoverflow 2017-05-23 09:26:07

0

它似乎我可以得到這與以下工作,但似乎不太neet。

for(ErrorType errorType: validationResult.getErrors()) { 
    fieldErrorCodes = new String[]{ 
     errorType.getErrorCode() 
    }; 

    bindingResult.addError(new ObjectError(errorType.getProperty(), fieldErrorCodes , null, null)); 

    if(errorType.getProperty().length() > 0) { 
     bindingResult.addError(new FieldError(bindingResult.getObjectName(), errorType.getProperty(), null, 
       false, fieldErrorCodes, null, null)); 
    } 
}