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

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

Is there any way to achieve this?

I am trying to use JsfUnit to create automated tests. I can get UICompoment objects from testing methods. However, I could not find a way to check the Html generated by the component.

+4
source share
2 answers

Just do the same thing that JSF does under covers: invoke UIComponent#encodeAll() . To capture the output, set the response script to the local buffer FacesContext#setResponseWriter() .

eg. (assuming you are sitting in the application-application phase, and when you are sitting in the rendering response phase, you need to do this 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(); // ... 
+6
source

BalusC's solution to calling UIComponent#encodeAll() usually works, but when using utf-8 encoding, I had a problem with Unicode characters. All non-ascii characters in ajax response were corrupted after I changed the current response script to a script.

Instead of changing the response script in the current context obtained by FacesContext.getCurrentInstance () , I created a wrapper on top of the current context by expanding FacesContextWrapper so that the original context remains unchanged:

 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(); 
+1
source

Source: https://habr.com/ru/post/1484850/


All Articles