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

后端 未结 2 1801
野趣味
野趣味 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:41

    Solution by BalusC to invoke UIComponent#encodeAll()generally works, but I had a problem with unicode characters when using utf-8 encoding. All non-ascii characters in ajax response were damaged after I modified current context's response writer.

    Instead of modifying response writer on current context retrieved by FacesContext.getCurrentInstance(), I created a wrapper over current context by extending FacesContextWrapper, so that original context is left unmodified:

    StringWriter writer = new StringWriter();
    FacesContext context = new FacesContextWrapper() {
        private ResponseWriter internalWriter = getWrapped()
            .getRenderKit().createResponseWriter(writer, "text/html", "UTF-8");
    
        @Override
        public FacesContext getWrapped() {
            return FacesContext.getCurrentInstance();
        }
    
        @Override
        public ResponseWriter getResponseWriter() {
            return internalWriter;
        }
    
    };
    
    component.encodeAll(context);
    String output = writer.toString();
    

提交回复
热议问题