我正在编写自己的自定义组件扩展UIInput
以及自定义渲染器。我希望我的组件在validator
属性中应用方法表达式。但验证器属性不会呈现为html标记。因此writeAttribute("validator", validator, null)
对此案例无效。我怎么能这样做?
我为UIInput
撰写了渲染器。
@FacesRenderer(componentFamily = "javax.faces.Input", rendererType = "text")
public class TextFieldRenderer extends Renderer{
@Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException{
String ClientId= component.getClientId(context);
String hint= (String) component.getAttributes().get("placeholder");
String styleClass= (String) component.getAttributes().get("styleClass");
String value =(String) component.getAttributes().get("value");
ResponseWriter writer= context.getResponseWriter();
writer.startElement("input", component);
writer.writeAttribute("type", "text", null);
writer.writeAttribute("name", ClientId, null);
writer.writeAttribute("placeholder", hint, "hint");
writer.endElement("input");
}
}
和text.taglib.xml
<?xml version="1.0" encoding="UTF-8"?>
<facelet-taglib>
<namespace>http://text.com</namespace>
<tag>
<tag-name>hintText</tag-name>
<component>
<component-type>javax.faces.Input</component-type>
<renderer-type>text</renderer-type>
</component>
</tag>
</facelet-taglib>
我在LBean.java
public void validateLoginField(FacesContext context, UIComponent toValidate, Object value) {
if (((String) value).length() < 4) {
FacesMessage msg = new FacesMessage("Must contains more then 4 caharacters");
context.addMessage(toValidate.getClientId(), msg);
} else if (((String) value).length() > 25) {
FacesMessage msg= new FacesMessage("Must contains less then 25 character");
context.addMessage(toValidate.getClientId(), msg);
}
}
现在我写index.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:lpform="http://xmlns.jcp.org/jsf/composite/lpform"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:text="http://text.com">
<h:head></h:head>
<h:body>
<h:form>
<text:hintText id="ht" placeholder="hint" validator="#{LBean.validateLoginField}">
<f:validateLength minimum="4"/>
</text:hintText>
<h:commandButton value="sub"/>
<h:message for="ht"/>
</h:form>
</h:body>
</html>
我想验证hintText
的{{1}}值与validator
上执行的<h:inputText validator="#{LBean.validateLoginField}"/>
属性一样。但<f:validateLenght minimum="4">
和validator="#{LBean.validateLoginField}"
都不会验证我的hintText
。