网站认证值不值得做,网站建设专用图形库,渠道网络股份有限公司,唐山网站建设最好的jsf 传参数在JSF 2中编写自定义验证器并不是一项复杂的任务。 您实现Validator接口#xff0c;添加FacesValidator批注#xff0c;并在faces-config.xml中插入validator声明#xff0c; 仅此而已 。 一块蛋糕。 但是#xff0c;让我们考虑以下情形#xff1a; 您需要自定义… jsf 传参数 在JSF 2中编写自定义验证器并不是一项复杂的任务。 您实现Validator接口添加FacesValidator批注并在faces-config.xml中插入validator声明 仅此而已 。 一块蛋糕。 但是让我们考虑以下情形 您需要自定义日期验证器比方说检查richcalendar中的日期是否不是过去的日期。 因此我们在日历组件中放置了验证器。 rich:calendar value#{fieldValue} iddateField datePatternyyyy/MM/ddf:validator validatorIddateNotInThePast//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中我们可以对具有属性 fattribute标签的组件进行参数化。 因此我们将属性添加到richcalendar然后在分配给此日历字段的验证器中读取此传递的值。 因此现在我们的日历组件应如下所示 rich:calendar value#{fieldValue} iddateField datePatternyyyy/MM/ddf:validator validatorIddateNotInThePast/f:attribute namefieldLabel valueDate 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.htmljsf 传参数