javascript
jsf 传参数_在JSF 2中对定制验证器进行参数化
jsf 傳參數
在JSF 2中編寫自定義驗證器并不是一項復雜的任務。 您實現Validator接口,添加@FacesValidator批注,并在faces-config.xml中插入validator聲明, 僅此而已 。 一塊蛋糕。 但是,讓我們考慮以下情形:您需要自定義日期驗證器,比方說檢查rich:calendar中的日期是否不是過去的日期。 因此,我們在日歷組件中放置了驗證器。
<rich:calendar value="#{fieldValue}" id="dateField" datePattern="yyyy/MM/dd"><f:validator validatorId="dateNotInThePast"/></rich:calendar>我們的驗證器可能如下所示:
@FacesValidator("dateNotInThePast") public class DateNotInThePastValidator implements Validator {@Overridepublic void validate(FacesContext facesContext, UIComponent uiComponent, Object value)throws ValidatorException {if (ObjectUtil.isNotEmpty(value)) {checkDate((Date)value, uiComponent, facesContext.getViewRoot().getLocale());}}private void checkDate(Date date, UIComponent uiComponent, Locale locale) {if(isDateInRange(date) == false) {ResourceBundle rb = ResourceBundle.getBundle("messages", locale);String messageText = rb.getString("date.not.in.the.past");throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,messageText, messageText));}}private boolean isDateInRange(Date date) {Date today = new DateTime().withTime(0, 0, 0, 0).toDate();return date.after(today) || date.equals(today);} }如果我們在屬性文件中提供鍵值,我們將看到類似以下內容:
因此,看來我們已經可以使用生產就緒的自定義驗證器。
問題
但是,當我們的表格變得越來越復雜時,我們可能會遇到以下屏幕上描述的問題:
因此,問題在于用戶如何確定哪個日期有效和哪個日期無效? 我們的驗證器使用相同的屬性鍵來顯示兩個錯誤消息。
解決方案
我們需要以某種方式向我們的自定義驗證器提供已驗證字段的標簽。 而且,對于JSF而言,令人驚訝的是,它可以很容易地實現。 唯一的問題是您必須知道如何做
因此,在Java Server Faces中,我們可以對具有屬性( f:attribute標簽)的組件進行參數化。 因此,我們將屬性添加到rich:calendar,然后在分配給此日歷字段的驗證器中讀取此傳遞的值。 因此,現在我們的日歷組件應如下所示:
<rich:calendar value="#{fieldValue}" id="dateField" datePattern="yyyy/MM/dd"><f:validator validatorId="dateNotInThePast"/><f:attribute name="fieldLabel" value="Date field 2" /></rich:calendar>在我們的驗證器Java類中,我們可以使用uiComponent.getAttributes()。get(“ fieldLabel”);獲得此值。
private void checkDate(Date date, UIComponent uiComponent, Locale locale) {if(isDateInRange(date) == false) {ResourceBundle rb = ResourceBundle.getBundle("messages", locale);String messageText = getFieldLabel(uiComponent) +" " + rb.getString(getErrorKey());throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,messageText, messageText));}}protected String getFieldLabel(UIComponent uiComponent) {String fieldLabel = (String) uiComponent.getAttributes().get("fieldLabel");if(fieldLabel == null) {fieldLabel = "Date" ;}return fieldLabel;}錯誤的屬性值應為過去的值,因為錯誤消息的開頭將添加日期或字段標簽。
工作示例應顯示與此屏幕類似的內容:
參考:來自Code Hard Go Pro博客的JCG合作伙伴 Tomasz Dziurko 在JSF 2中參數化定制驗證器
相關文章 :
- Java EE過去,現在和云7
- JBoss AS 7.0.2“ Arc”發布–使用綁定選項
- 那些邪惡的框架及其復雜性
- 真正的模塊化Web應用程序:為什么沒有開發標準?
- 編程反模式
- Java教程和Android教程列表
翻譯自: https://www.javacodegeeks.com/2011/10/parametrizing-custom-validator-in-jsf-2.html
jsf 傳參數
總結
以上是生活随笔為你收集整理的jsf 传参数_在JSF 2中对定制验证器进行参数化的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LongAccumulator和Doub
- 下一篇: JUnit:使用Java 8和Asser