djmj
djmj

Reputation: 5554

JSF - Get HTML of UIComponent programmatically

How can I retrieve the HTML response of a single UIComponent programmatically?

Upvotes: 1

Views: 919

Answers (2)

Tobias Liefke
Tobias Liefke

Reputation: 9032

I suppose you are already in a JSF request.

In that case you can set a custom response writer to the current FacesContext, for example a new com.sun.faces.renderkit.html_basic.HtmlResponseWriter and render the component afterwards:

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);
    }
}

It's important to notice that your component or one of its children must not use any variables that are defined in another place on the page, as these variables are not defined if you just render the single component.

If you want to initialize all variables as well, you can print the HTML like the response to an AJAX request (partial response):

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);
    }

}

Upvotes: 1

djmj
djmj

Reputation: 5554

To a certain degree where only a simple text is required Omnifaces outputFormat can save its output into a var.

http://showcase.omnifaces.org/components/outputFormat

Upvotes: 0

Related Questions