tags:

views:

23

answers:

2

In a ViewHandlerWrapper-implementation I have following code:

public void renderView(FacesContext context, UIViewRoot viewToRender) throws IOException, FacesException {
    final String token = UUID.randomUUID().toString();

    HttpSession httpSession = (HttpSession) context.getExternalContext().getSession(true);
    httpSession.setAttribute("expectedToken", token);

    getWrapped().renderView(context, viewToRender);
}

As you can see, I want to add a UUID to the Session. Following the debugger I can see that the attribute stays on the Session until the entire request-response cycle of the servlet container is complete. However, at the next invocation the "expectedToken" attribute is null.

Before going "old school" (fetching the HttpSession) I tried to manipulate a value object on the session, which rendered the same result. The change was dismissed.

Is this not supposed to work (after all, the response is not committed when renderView is invoked)?

+2  A: 

Try getting the session without recreation

HttpSession httpSession = (HttpSession) context.getExternalContext().getSession(false);
mmanco
Too bad but that didn't do the trick. :/
sicn
+1  A: 

Rather use the JSF-provided ExternalContext#getSessionMap(). This is in turn transparently backed by the HTTP session.

ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
externalContext.getSessionMap().put("key", "value");

A hint for the future, whenever you need to haul the raw Servlet API from under the JSF hoods, ask yourself twice: Am I doing it the right way? Isn't there a JSF-ish way? In almost all cases there is. If in vain, just ask here :)

BalusC
Well, as I said "before going old school" I did try it the JSF-way... Which didn't work either :(
sicn
Apparently the session has not been maintained for the subsequent request. This can have a lot of causes, the important being: 1) domain has changed, 2) context has changed, 3) client doesn't support cookies, 4) session was programmatically invalidated.
BalusC
Turns out that all versions presented here and which I tested before were OK and worked. The problem is that I read the session values at the wrong point in time, always rendering "NULL" as a result. Apperantely it has to be read before RENDER_RESPONSE and after UPDATE_MODEL_VALUES. I will accept both answers because you guys made me confident that it's not wrong to add something to the session in a ViewHandler.
sicn
Interesting. Haven't seen that before. What JSF impl/version exactly?
BalusC
Sun's Mojarra 2.0.3
sicn