javascript
在JSF 2中对定制验证器进行参数化
您需要自定義日期驗證器,比方說檢查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);} }如果我們在屬性文件中提供鍵值,我們將看到類似以下內(nèi)容:
因此,看來我們已經(jīng)可以使用生產(chǎn)就緒的自定義驗證器。
問題
但是,當(dāng)我們的表格變得越來越復(fù)雜時,我們可能會遇到以下屏幕上描述的問題:
因此,問題在于用戶如何確定哪個日期有效和哪個日期無效? 我們的驗證器使用相同的屬性鍵來顯示兩個錯誤消息。
解決方案
我們需要以某種方式向我們的自定義驗證器提供已驗證字段的標(biāo)簽。 而且,對于JSF而言,令人驚訝的是,它可以很容易地實現(xiàn)。 唯一的問題是您必須知道如何做
因此,在Java Server Faces中,我們可以對具有屬性( f:attribute標(biāo)簽)的組件進(jìn)行參數(shù)化。 因此,我們將屬性添加到rich:calendar,然后在分配給此日歷字段的驗證器中讀取此傳遞的值。 因此,現(xiàn)在我們的日歷組件應(yīng)如下所示:
<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;}我們錯誤的屬性值應(yīng)為過去的值,因為日期或字段標(biāo)簽將添加到錯誤消息的開頭。
工作示例應(yīng)顯示與此屏幕類似的內(nèi)容:
參考:來自Code Hard Go Pro博客的JCG合作伙伴 Tomasz Dziurko 在JSF 2中對定制驗證器進(jìn)行參數(shù)化
相關(guān)文章 :
- Java EE過去,現(xiàn)在和云7
- JBoss AS 7.0.2“ Arc”發(fā)布–使用綁定選項
- 那些邪惡的框架及其復(fù)雜性
- 真正的模塊化Web應(yīng)用程序:為什么沒有開發(fā)標(biāo)準(zhǔn)?
- 編程反模式
- Java教程和Android教程列表
翻譯自: https://www.javacodegeeks.com/2011/10/parametrizing-custom-validator-in-jsf-2.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結(jié)
以上是生活随笔為你收集整理的在JSF 2中对定制验证器进行参数化的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux查看服务状态(linux 查看
- 下一篇: 珠海房产备案价格查询官网(珠海房产备案价