事實上,我有一個相當普通的任務:有一個頁面具有搜索功能。
在沒有錯誤的搜索成功的情況下,應顯示結果,但如果發生驗證錯誤(在下一次搜索期間),則不應顯示以前的結果(但它是可見的,這是一個問題)。
我的計劃如下:以檢查初始化驗證失敗()使用facesContext.isValidationFailed(),如果這是真的,那麼隱藏(刪除)方法以前的搜索結果:
public void initialize() {
FacesContext context = FacesContext.getCurrentInstance();
boolean validationFailed = context.isValidationFailed();
if(validationFailed) {
clearPreviousSearchResult();
}
}
但隨後我發現使用bean註釋進行驗證(如@AssertTrue)不會設置facesContext.validationFailed();! 也就是說這
@AssertTrue(message = "Some error message")
public boolean isValidateSomeField() {
return validate(getSomeFieldValue());
}
後,你會得到context.isValidationFailed()== false,如果失敗,會出現(雖然我預料真)
(XHTML驗證或驗證或f:驗證不設置FacesContext中。validationFailed()如預期)
因此,有必要設置情境手動失敗:
@AssertTrue(message = "Some error message")
public boolean isValidateSomeField() {
if(!validate(getSomeFieldValue())) {
FacesContext.getCurrentInstance().validationFailed();
return false;
}
return true;
}
但由於How to check in after phase of Validations phase if validation has failed?我意識到,這個問題就可以解決更容易!只需用幾行包:
<h:panelGroup rendered="#{!facesContext.validationFailed}">
...block not to show if validation errors occur...
</h:panelGroup>
而且無需使用註釋Bean驗證和一些initialize()方法!