Manipulating the HttpSession in a JSF ViewHandlerWrapper doesn't work
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)?
Try getting the session without recreation
HttpSession httpSession = (HttpSession) context.getExternalContext().getSession(false);
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 :)
精彩评论