2013-11-01 54 views
2

我使用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],

+0

這是完整的錯誤嗎?它看起來不像Bean驗證錯誤。你有堆棧跟蹤嗎? – Hardy

+0

@Hardy我更新了問題(將完整的錯誤消息和附加代碼添加到控制器方法中)。請檢查它。謝謝。 – MyTitle

+0

看起來像這是一個轉換錯誤。前端給你一個字符串作爲狀態,但你期望一個emum類型。至於我可以告訴任何關於Bean Validation的事情。我不確定JSF如何以及如何爲您轉換。 – Hardy

回答

3

看起來你有同樣的問題,因爲我!

控制器中有一個方法可以作爲一個鉤子,您可以指定如何將來自HTTP請求的字符串值轉換爲具體對象! 該方法被稱爲initBinder,並在那裏附加正確的行爲以正確執行轉換。我仍在研究,但迄今爲止,看起來不錯。

看看這個:

希望它有助於找到解決方案!

Greetings

Victor。

+0

也剛剛發現,枚舉的默認綁定器將「」變爲null,至少對於Spring 2.5來說! – Victor