我正在JSF 2中使用Primefaces 3创建搜索框。我需要在控件中添加非标准属性(x-webkit-speech),这样您就可以得到类似的内容...
<p:autoComplete x-webkit-speech="x-webkit-speech" ... />
由于此属性不是autoComplete控件的一部分,因此JSF给了我500错误。但是,当我删除它时,页面呈现良好。通常,如何在JSF标记上指定传递属性,以便忽略它们?
JSF设计为在呈现HTML时会忽略所有自定义属性。
如果您已经在使用JSF 2.2+,只需将其指定为passthrough attribute:
<html ... xmlns:a="http://xmlns.jcp.org/jsf/passthrough">
...
<p:autoComplete a:x-webkit-speech="x-webkit-speech" ... />
如果尚未使用JSF 2.2,则需要一个自定义渲染器。幸运的是,PrimeFaces <p:autoComplete>
(和所有其他组件)相对简单。仅重写renderPassThruAttributes()
方法就足够了,在该方法中,您要将要呈现的新属性添加到attrs
参数中,并最终委托给super方法。
例如
package com.example;
import java.io.IOException;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import org.primefaces.component.autocomplete.AutoCompleteRenderer;
public class MyAutoCompleteRenderer extends AutoCompleteRenderer {
@Override
protected void renderPassThruAttributes(FacesContext facesContext, UIComponent component, String[] attrs) throws IOException {
String[] newAttrs = new String[attrs.length + 1];
System.arraycopy(attrs, 0, newAttrs, 0, attrs.length);
newAttrs[attrs.length] = "x-webkit-speech";
super.renderPassThruAttributes(facesContext, component, newAttrs);
}
}
要使其运行,请按以下步骤在您的Web应用程序的faces-config.xml
中进行注册:
<render-kit>
<renderer>
<component-family>org.primefaces.component</component-family>
<renderer-type>org.primefaces.component.AutoCompleteRenderer</renderer-type>
<renderer-class>com.example.MyAutoCompleteRenderer</renderer-class>
</renderer>
</render-kit>
((通过查看AutoComplete
类的源代码可以找到组件族和渲染器类型,它们在其中被指定为COMPONENT_FAMILY
和RENDERER_TYPE
常量)
不,@FacesRenderer
注释仅用于覆盖自定义渲染器,而这些渲染器本身已经在faces-config.xml
中注册。
可以使用JSF-Ext的Attribute-Tag扩展最多的Tag。
我不确定这是否完全可能。我会使用javascript或jQuery在客户端添加这些属性。