JSF - 以编程方式获取UIComponent的HTML

时间:2014-12-05 02:38:18

标签: jsf java-ee jsf-2

如何以编程方式检索单个UIComponent的HTML响应?

1 个答案:

答案 0 :(得分:0)

我想你已经在JSF请求中了。

在这种情况下,您可以将自定义响应编写器设置为当前的FacesContext,例如新的com.sun.faces.renderkit.html_basic.HtmlResponseWriter并在之后呈现该组件:

public String createHtml(UIComponent component) {
    FacesContext context = FacesContext.getCurrentInstance();
    ResponseWriter oldWriter = context.getResponseWriter();
    try {
        StringWriter buffer = new StringWriter();
        context.setResponseWriter(new HtmlResponseWriter(buffer, "text/html", "UTF-8"));
        component.encodeAll(context);
        context.getResponseWriter().close();
        return buffer.toString();
    } finally {
        context.setResponseWriter(oldWriter);
    }
}

请注意,您的组件或其子组件之一不得使用页面上其他位置定义的任何变量,因为如果只渲染单个组件,则不会定义这些变量。

如果你想初始化所有变量,你可以打印HTML,就像对AJAX请求的响应一样(部分响应):

public String createHtml(UIComponent component) {
    FacesContext context = FacesContext.getCurrentInstance();
    ResponseWriter oldWriter = context.getResponseWriter();
    try {
        StringWriter buffer = new StringWriter();
        context.setResponseWriter(new HtmlResponseWriter(buffer, "text/html", "UTF-8"));

        final VisitContext vc = VisitContext.createVisitContext(context,
                Collections.singleton(component.getClientId()), 
                Collections.<VisitHint> emptySet());

        context.getViewRoot().visitTree(vc, new VisitCallback() {
            public VisitResult visit(final VisitContext ctx, final UIComponent comp) {
                try {
                    comp.encodeAll(ctx.getFacesContext());
                } catch (final IOException e) {
                    throw new IllegalStateException(e);
                }

                return VisitResult.COMPLETE;
            }
        });
        context.getResponseWriter().close();
        return buffer.toString();
    } finally {
        context.setResponseWriter(oldWriter);
    }

}