JSF 自定义标签验证器的实现

1. 继承Validator编写新的validator, (此例是继承LengthValidator). 此validator用于中英文长度验证。 因为1个中文在oracle中占3个字符。
package com.cs.web.validator;

import java.io.UnsupportedEncodingException;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.validator.LengthValidator;
import javax.faces.validator.ValidatorException;

import com.sun.faces.util.MessageFactory;

public class UnicodeLengthValidator extends LengthValidator {

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {

int maximum = getMaximum();
int minimum = getMinimum();
if ((context == null) || (component == null)) {
    throw new NullPointerException();
}
if (value != null) {
    String converted = stringValue(value);
    if (maximum > 0 && (strLengthInOracle(converted) > maximum)) {
throw new ValidatorException(MessageFactory.getMessage(context, MAXIMUM_MESSAGE_ID,
integerToString(component, maximum, context), MessageFactory.getLabel(context, component)));
    }
    if (minimum > 0 && (strLengthInOracle(converted) < minimum)) {
throw new ValidatorException(MessageFactory.getMessage(context, MINIMUM_MESSAGE_ID,
integerToString(component, minimum, context), MessageFactory.getLabel(context, component)));
    }
}

    }

    private static String integerToString(UIComponent component, Integer toConvert, FacesContext context) {

Converter converter = context.getApplication().createConverter("javax.faces.Number");
return converter.getAsString(context, component, toConvert);

    }

    public static int strLengthInOracle(String str) {
if (str == null || str.length() <= 0) {
    return 0;
}
int len = 0;
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
    byte[] bytes;
    try {
bytes = ("" + chars[i]).getBytes("UTF-8");
if (bytes.length == 1) {
    len++;
} else {
    len += 3;
}
    } catch (UnsupportedEncodingException e) {

    }
}
return len;
    }

    /**
     * <p>
     * Return the specified attribute value, converted to a. copy from
     * javax.faces.validator.LengthValidator <code>String</code>.
     * </p>
     *
     * @param attributeValue
     *            The attribute value to be converted
     */
    private static String stringValue(Object attributeValue) {

if (attributeValue == null) {
    return (null);
} else if (attributeValue instanceof String) {
    return ((String) attributeValue);
} else {
    return (attributeValue.toString());
}

    }

}

2. 在faces-config.xml中定义validator id.
    <validator> 
    <validator-id>com.cs.web.validator.UnicodeLengthValidator</validator-id> 
    <validator-class>com.cs.web.validator.UnicodeLengthValidator</validator-class> 
    </validator>

3. 在cs.taglib.xml中定义tag name.
<?xml version="1.0"?>
<!DOCTYPE facelet-taglib PUBLIC
  "-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN"
  "http://java.sun.com/dtd/facelet-taglib_1_0.dtd">
<facelet-taglib>
<namespace>http://www.test.com/validator/tags</namespace>


<tag>
       <tag-name>validateLength</tag-name>

       <validator>
           <validator-id>com.cs.web.validator.UnicodeLengthValidator</validator-id>
           <handler-class>javax.faces.view.facelets.ValidatorHandler</handler-class>
       </validator>
        <attribute>
            <name>maximum</name>
            <type>java.lang.Integer</type>
        </attribute>
        <attribute>
            <name>minimum</name>
            <type>java.lang.Integer</type>
        </attribute>
    </tag>
</facelet-taglib>

4. 在web.xml中引入cs.taglib.xml
   <context-param>
  <param-name>javax.faces.FACELETS_LIBRARIES</param-name>
  <param-value>/WEB-INF/cs.taglib.xml</param-value>
  </context-param>

5. 在xhtml中使用标签:
首先引入:
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:vd="http://www.test.com/validator/tags"
xmlns:p="http://primefaces.org/ui"
template="/WEB-INF/layouts/Layout.xhtml">
再调用:
<gs:inputText id="name" value="#{bean.name}" required="true" requiredMessage="#{msges['input.mandatory']}" >
<f:validateRequired />
<vd:validateLength maximum="7"/>
</gs:inputText>

你可能感兴趣的:(JSF,自定义标签,验证器)