Wednesday, February 9, 2011

Escape characters in ResponseWriter

While development of JSF components I have faced a task to escape apostrophe ' in the HTTP response generated by javax.faces.context.ResponseWriter. Here is a solution:
ResponseWriter writer = facesContext.getResponseWriter();
// swap writers
FastStringWriter fsw = new FastStringWriter();
ResponseWriter clonedWriter = writer.cloneWithWriter(fsw);

// render children
renderChildren(facesContext, uiTreeNode);

// restore the original writer

// escape output and write it back
String renderedKids = fsw.toString();
if (renderedKids != null && !renderedKids.isEmpty()) {
    writer.write(renderedKids.replace("'", "\\\'"));
We replace the original Writer by FastStringWriter, write there, get the output from it, do escaping and write the escaped output to the response.

P.S. This post was triggered by an issue in PrimeFaces. I guess, writeText would do the escaping. But if you have a third-party library and don't have many control over the rendering of component subtrees (s. renderChildren), you have not much alternatives.

1 comment:

  1. hi, I'm new to JSF and have somewhat similar issue. The question is, where this code have to be inserted, for each component renderer? other question is can I replace writer globaly for server.


Note: Only a member of this blog may post a comment.