微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何让JSF传递HTML属性

我在JSF 2中使用Primefaces 3来制作搜索框.我需要向控件添加一个非标准属性(x-webkit-speech),这样你就会有这样的东西……
<p:autoComplete x-webkit-speech="x-webkit-speech" ... />

由于此属性不是autoComplete控件的一部分,因此JSF给出了500错误.但是当我删除它时,页面渲染得很好.一般来说,如何在JSF标记上指定传递属性,以便忽略它们?

解决方法

设计JSF在呈现HTML时忽略所有自定义属性.您需要一个自定义渲染器.这是在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,newAttrs,attrs.length);
        newAttrs[attrs.length] = "x-webkit-speech";
        super.renderPassthruAttributes(facesContext,component,newAttrs);
    }

}

要使其运行,请在webapp的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常量)

不,当目的是覆盖自己已经在faces-config.xml中注册自定义渲染器时,@ FacesRenderer注释将无法工作.

原文地址:https://www.jb51.cc/html/231729.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐