如何以编程方式检索单个UIComponent的HTML响应?
答案 0 :(得分:0)
我想你已经在JSF请求中了。
在这种情况下,您可以将自定义响应编写器设置为当前的FacesContext,例如新的com.sun.faces.renderkit.html_basic.HtmlResponseWriter
并在之后呈现该组件:
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);
}
}
请注意,您的组件或其子组件之一不得使用页面上其他位置定义的任何变量,因为如果只渲染单个组件,则不会定义这些变量。
如果你想初始化所有变量,你可以打印HTML,就像对AJAX请求的响应一样(部分响应):
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);
}
}