2014-12-05 71 views

回答

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); 
    } 
} 

它注意到重要的是您的組件或它的一個子絕不要使用在頁面上另一個地方定義的變量,因爲如果您只渲染單個組件,則這些變量未定義。

如果你想初始化所有變量,以及,你可以打印喜歡的響應AJAX請求(部分緩解)的HTML:

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); 
    } 

}