我使用Spring窗體標記來填充表單的值。彈簧窗體標籤。允許表單中的空值:select(enum)
我有表單支持對象:
public class FormInfo {
public enum Status {ON, OFF}
private Satus status;
//getter setter
...
}
而且在JSP Status
枚舉提出這樣的:
<form:form commandObject="formInfo " ...>
<form:select path="status">
<form:option value="null" label="Please select"/>
<form:options/>
</form:select>
</form:form>
一切工作正常,即默認消息和枚舉值在<select>
呈現。
但狀態字段不是必需的,所以我想允許用戶離開狀態字段未選中。但是,如果沒有形式選擇狀態字段提交,然後我得到錯誤:
error in object 'formInfo' on field 'status': rejected value [null];
如何在沒有選擇值我可以設置枚舉空?
請注意我正在使用JSR 303驗證。上述錯誤不會自動發生,我從以下方法BindingResult#getFieldErrors()
手動獲取此錯誤消息。
這是我的控制器代碼:
public void myMethod(@Valid @ModelAttribute("formInfo") FormInfo sourcingDetail, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
log.error("Error during validation is occurred." + bindingResult.getFieldErrors().toString()); // <-- this is error message
}
...
}
另請注意,我並沒有對status
字段設置任何JSR-303的註釋(如@NotNull)。
UPDATE:
幾乎完整的錯誤消息,這是我從調用此方法BindingResult#getFieldErrors()
得到(如上所述):
Error during validation is occurred.[Field error in object 'formInfo' on field 'status': rejected value [null];
...
[Failed to convert property value of type 'java.lang.String' to required type 'com.my.project.model.Status' for property 'status'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.my.project.model.Status] for property 'status': no matching editors or conversion strategy found],
這是完整的錯誤嗎?它看起來不像Bean驗證錯誤。你有堆棧跟蹤嗎? – Hardy
@Hardy我更新了問題(將完整的錯誤消息和附加代碼添加到控制器方法中)。請檢查它。謝謝。 – MyTitle
看起來像這是一個轉換錯誤。前端給你一個字符串作爲狀態,但你期望一個emum類型。至於我可以告訴任何關於Bean Validation的事情。我不確定JSF如何以及如何爲您轉換。 – Hardy