vineri, 19 decembrie 2014

OmniFaces Approach for Passing Objects Between encodeXxx() Methods

Have you ever been in the situation of passing parameters between encodeXxx() methods ? Or, other JSF methods with fix signatures ? Of course, you almost always can use global private variables (even static) to globally store something and use from anywhere  in the class, but this is not a very nice approach.
OmniFaces provides a solution in the source code of the OutputFormat component. In this class, OmniFaces need the "original" ResponseWriter to be used in encodeBegin() and encodeEnd() methods. More exactly, in encodeBegin(), OmniFaces obtain the ResponseWriter via FacesContext.getResponseWriter() and stores it under the originalResponseWriter variable:

@Override
public void encodeBegin(FacesContext context) throws IOException {
   ...
   ResponseWriter originalResponseWriter = context.getResponseWriter();
   ...

Further, it uses another ResponseWriter, and, in encodeEnd() method, OmniFaces need to restore the originalResponseWriter by calling FacesContext.setResponseWriter(). For having access encodeEnd() method to the originalResponseWriter, OmniFaces stores it under a context as an attribute, like this:

   ...   
   context.getAttributes().put(this + "_writer", originalResponseWriter);
   ...
}

Now, in encodeEnd(), OmniFaces takes the originalResponseWriter and remove it after that:

@Override
public void encodeEnd(FacesContext context) throws IOException {
   ...
   ResponseWriter originalResponseWriter = (ResponseWriter)
       context.getAttributes().remove(this + "_writer");
   ...
}

So, whenever you are in this situation you can try the OmniFaces approach. 

Niciun comentariu:

Trimiteți un comentariu