如何让JSF传递HTML属性[重复]

问题描述 投票:6回答:3

我正在JSF 2中使用Primefaces 3创建搜索框。我需要在控件中添加非标准属性(x-webkit-speech),这样您就可以得到类似的内容...

<p:autoComplete x-webkit-speech="x-webkit-speech" ... />

由于此属性不是autoComplete控件的一部分,因此JSF给了我500错误。但是,当我删除它时,页面呈现良好。通常,如何在JSF标记上指定传递属性,以便忽略它们?

html jsf jsf-2 primefaces servlet-3.0
3个回答
7
投票

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_FAMILYRENDERER_TYPE常量)

不,@FacesRenderer注释仅用于覆盖自定义渲染器,而这些渲染器本身已经在faces-config.xml中注册。


1
投票

可以使用JSF-Ext的Attribute-Tag扩展最多的Tag。


0
投票

我不确定这是否完全可能。我会使用javascript或jQuery在客户端添加这些属性。

© www.soinside.com 2019 - 2024. All rights reserved.