Is there a way to get the generated HTML as a String from a UIComponent object?

后端 未结 2 1803
野趣味
野趣味 2021-01-05 05:07

I have a UIComponent object. I would like to get the HTML code generated by this component at runtime so I can analyze it.

Is there a way to achieve this?

I

2条回答
  •  迷失自我
    2021-01-05 05:39

    Just do the same what JSF does under the covers: invoke UIComponent#encodeAll(). To capture the output, set the response writer to a local buffer by FacesContext#setResponseWriter().

    E.g. (assuming that you're sitting in invoke application phase; when sitting in render response phase, this needs to be done differently):

    FacesContext context = FacesContext.getCurrentInstance();
    ResponseWriter originalWriter = context.getResponseWriter();
    StringWriter writer = new StringWriter();
    
    try {
        context.setResponseWriter(context.getRenderKit().createResponseWriter(writer, "text/html", "UTF-8"));
        component.encodeAll(context);
    } finally {
        if (originalWriter != null) {
            context.setResponseWriter(originalWriter);
        }
    }
    
    String output = writer.toString();
    // ...
    

提交回复
热议问题