有没有办法从UIComponent对象获取生成的HTML作为字符串? [英] Is there a way to get the generated HTML as a String from a UIComponent object?

查看:92
本文介绍了有没有办法从UIComponent对象获取生成的HTML作为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个

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?

我正在尝试使用JsfUnit创建自动化测试.我可以从测试方法中获取UICompoment对象.但是,我找不到一种方法来检查由组件生成的HTML.

I am trying to use JsfUnit to create automated tests. I can get ahold of the UICompoment objects from within the test methods. However, I couldn't find a way to check the Html generated by the component.

推荐答案

只需执行JSF幕后的操作即可:调用 FacesContext#setResponseWriter() .

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();
// ...

这篇关于有没有办法从UIComponent对象获取生成的HTML作为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆