jsf验证器创建

创建一个验证器,验证两个日期的前后关系:有两个输入框:FormTo。输入To的时间不能比Form的时间晚/

步骤一:

创建验证类:com.expense.valcus.LaterThanValidator

 

package com.expense.valcus;

 

import java.text.MessageFormat;

import java.io.Serializable;

import java.util.Date;

import java.util.Locale;

import java.util.ResourceBundle;

import javax.faces.application.Application;

import javax.faces.application.FacesMessage;

import javax.faces.component.UIComponent;

import javax.faces.component.EditableValueHolder;

import javax.faces.component.ValueHolder;

import javax.faces.context.FacesContext;

import javax.faces.convert.Converter;

import javax.faces.validator.Validator;

import javax.faces.validator.ValidatorException;

 

/**

* This class is a JSF Validator that validates that the java.util.Date

* value of the component it's attached to is later than the

* java.util.Date value of another component.

*

* @author Hans Bergsten, Gefion Software <hans@gefionsoftware.com>

* @version 1.0

*/

public class LaterThanValidator implements Validator, Serializable {

   /**

        *

        */

       private static final long serialVersionUID = 1170859790387692325L;

       private String peerId;

 

   /**

    * Sets the ID for the peer component the main component's

    * value is compared to. It must be a format that can be

    * used with the javax.faces.component.UIComponent findComponent()

    * method.

    */

   public void setPeerId(String peerId) {

       this.peerId = peerId;

   }

 

   /**

    * Compares the provided value to the value of the peer component,

    * and throws a ValidatorException with an appropriate FacesMessage

    * if the provided value doesn't represent a later date or if

    * there are problems accessing the peer component value.

    */

   public void validate(FacesContext context, UIComponent component,

                      Object value) throws ValidatorException {

 

       Application application = context.getApplication();

 

       /* Note! This validator requires an application bundle

        * that holds the messages. For validators, or other

        * components, that should be usable in any application,

        * bundling a default bundle and use it if the message

        * isn't available in the application bundle is a nicer

        * approach.

        */

       String messageBundleName = application.getMessageBundle();

       Locale locale = context.getViewRoot().getLocale();

       ResourceBundle rb =

           ResourceBundle.getBundle(messageBundleName, locale);

 

       UIComponent peerComponent = component.findComponent(peerId);

       if (peerComponent == null) {

           String msg = rb.getString("peer_not_found");

           FacesMessage facesMsg =

              new FacesMessage(FacesMessage.SEVERITY_FATAL, msg, msg);

           throw new ValidatorException(facesMsg);

       }

     

       ValueHolder peer = null;

       try {

           peer = (ValueHolder) peerComponent;

       }

       catch (ClassCastException e) {

           String msg = rb.getString("invalid_component");

           FacesMessage facesMsg =

              new FacesMessage(FacesMessage.SEVERITY_FATAL, msg, msg);

           throw new ValidatorException(facesMsg);

       }

       if (peer instanceof EditableValueHolder &&amp;

           !((EditableValueHolder) peer).isValid()) {

           // No point in validating against an invalid value

           return;

       }

      

       Object peerValue = peer.getValue();

       if (!(peerValue instanceof Date)) {

           String msg = rb.getString("invalid_peer");

           FacesMessage facesMsg =

              new FacesMessage(FacesMessage.SEVERITY_FATAL, msg, msg);

           throw new ValidatorException(facesMsg);

       }

     

       if (!(value instanceof Date) ||

           !((Date) value).after((Date) peerValue)) {

           String msg = rb.getString("not_later");

           String detailMsgPattern = rb.getString("not_later_detail");

           Object[] params =

               {formatDate((Date) peerValue, context, component)};

           String detailMsg =

              MessageFormat.format(detailMsgPattern, params);

           FacesMessage facesMsg =

              new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, detailMsg);

           throw new ValidatorException(facesMsg);

       }

   }

 

   /**

    * Returns the provided Date formatted with the converter attached

    * to the component, if any, or with toString() otherwise.

    */

   private String formatDate(Date date, FacesContext context,

       UIComponent component) {

       Converter converter = ((ValueHolder) component).getConverter();

       if (converter != null) {

           return converter.getAsString(context, component, date);

       }

       return date.toString();

   }

}

 

 

步骤二:在WEB-INF/faces-config.xml文件里面注册自定义验证器

 

<face-config>

   ......

 

       <validator>

              <validator-id>

                     com.expense.validator.ID

              </validator-id>

              <validator-class>

                     com.expense.valcus.LaterThanValidator

              </validator-class>

              <property>

                     <property-name>peerId</property-name>

                     <property-class>java.lang.String</property-class>

              </property>

       </validator>

 

......

</face-config>

 

步骤三:开发自定义的动作组件:

1>首先创建WEB-INF/tagc.tld

 

 

 

 

<taglib>

 

 <tlib-version>1.0</tlib-version>

 <jsp-version>1.2</jsp-version>

 <short-name>my</short-name>

 <uri>http://expense.com/myjsftag</uri>

 <description>

   The core JavaServer Faces custom actions that are independent of

   any particular RenderKit.

 </description>

 

 <tag>

      <name>validatelater</name>

      <tag-class>com.expense.valcus.ValidateLaterThanTag</tag-class>

      <body-content>empty</body-content>

      <attribute>

             <name>than</name>

             <required>true</required>

             <rtexprvalue>false</rtexprvalue>

      </attribute>

 </tag>

</taglib>

2>创建动作标记类:com.expense.valcus.ValidateLaterThanTag

package com.expense.valcus;

 

import javax.faces.application.Application;

import javax.faces.context.FacesContext;

import javax.faces.validator.Validator;

import javax.faces.webapp.ValidatorTag;

 

/**

* This class is a tag handler that creates and configures a

* "com.mycompany.jsf.validator.LATER_THAN" validator.

*

* @author Hans Bergsten, Gefion Software <hans@gefionsoftware.com>

* @version 1.0

*/

public class ValidateLaterThanTag extends ValidatorTag {

   /**

        *

        */

       private static final long serialVersionUID = 910680118767808902L;

       private String than;

 

   /**

    * Sets the client ID for the component holding the value to

    * compare the value of the component with this validator to.

    */

   public void setThan(String peerId) {

       this.than = peerId;

   }

 

   /**

    * Returns a new instance of the validator registered under the name

    * "com.mycompany.jsf.validator.LATER_THAN", configured with the

    * "than" property value.

    */

   protected Validator createValidator() {

       Application application =

           FacesContext.getCurrentInstance().getApplication();

       LaterThanValidator validator = (LaterThanValidator)

           application.createValidator("com.expense.validator.ID");

       validator.setPeerId(than);

       return validator;

   }

}

 

 

步骤四:在jsp网页里面使用:

1>

创建jsp网页:

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>

<%@ include file="tags.jsp"%>

<% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>

 

 

 

 

   <base href="% 3C %=basePath%%3E">

 

<title>My JSP 'filterArea.jsp' starting page</title>  

 

       <meta equiv="pragma" content="no-cache">

       <meta equiv="cache-control" content="no-cache">

       <meta equiv="expires" content="0">  

       <meta equiv="keywords" content="keyword1,keyword2,keyword3">

       <meta equiv="description" content="This is my page">

       <!--        <link rel="stylesheet" type="text/css" href="styles.css"><br />   -->

 

 

 

 

 <f:view>

      <h:form>

             From:

 

             <h:inputtext id="from" size="8" required="true" value="#{valCus.from }">

             <f:convertdatetime datestyle="short">

             </f:convertdatetime>

             <h:message for="from"></h:message>

            

To:

 

             <h:inputtext id="to" size="8" required="true" value="#{valCus.to }">

             <f:convertdatetime datestyle="short">

             <my:validatelater than="from">

             </my:validatelater>

             <h:message for="to">

            

 

             <h:commandbutton value="Filter"></h:commandbutton>

      </h:message>

 </f:convertdatetime>

 

 

 

其中<%@ include file="tags.jsp"%>中的tags.jsp如下:

<%@ page language="java" pageEncoding="GB18030"%>

<%@ page contentType="text/html" %>

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>

<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>

<%@ taglib uri="http://expense.com/myjsftag" prefix="my" %>

 

2>创建实体类:com.expense.valcusValCus

package com.expense.valcus;

 

import java.util.Date;

 

public class ValCus {

 

       private Date from;

       private Date to;

       public Date getFrom() {

              if(from == null)

                     return new Date();

              return from;

       }

       public void setFrom(Date from) {

              this.from = from;

       }

       public Date getTo() {

              if(to == null)

                     return new Date();

              return to;

       }

       public void setTo(Date to) {

              this.to = to;

       }

}

 

 

最后:完整的faces-config.xml文件如下:

<faces-config>

       <validator>

              <validator-id>

                     com.expense.validator.ID

              </validator-id>

              <validator-class>

                     com.expense.valcus.LaterThanValidator

              </validator-class>

              <property>

                     <property-name>peerId</property-name>

                     <property-class>java.lang.String</property-class>

              </property>

       </validator>

       <managed-bean>

              <managed-bean-name>valCus</managed-bean-name>

              <managed-bean-class>

                     com.expense.valcus.ValCus

              </managed-bean-class>

              <managed-bean-scope>session</managed-bean-scope>

 

       </managed-bean>

</faces-config>

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值