Question

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)?

Was it helpful?

Solution

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 :)

OTHER TIPS

Try getting the session without recreation

HttpSession httpSession = (HttpSession) context.getExternalContext().getSession(false);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top