问题
I have observed an interesting thing in my JSF2.1/Richfaces 4.2 application. Some how all response.sendRedirect() calls inside either Filter (or) JSF Bean action methods are not working.
If we use location.href on client side (Browser), it is working fine.
Any suggestions on what could be causing send redirect failure? I have tried below signatures.
response.sendRedirect("/appRoot/mypage.xhtml");
or
(HttpServletResponse) facesCtx.getResponse()).sendRedirect(((HttpServletRequest)request).getContextPath()+"/appRoot/mypage.faces");
回答1:
Some how all response.sendRedirect() calls inside either Filter (or) JSF Bean action methods are not working.
That can happen if the request is actually an ajax request. The webbrowser doesn't translate redirects on XMLHttpRequest
to the main window at all. The JS code who's sending the ajax request is responsible for that. It needs either a special/different response so that the JS code understands that it needs to change the window location, or the JS code itself needs to be altered so that it can handle the response accordingly.
If the ajax request is initiated by JSF itself (e.g. <f:ajax>
and so on) and the Java code is running inside the JSF context, then you should be using ExternalContext#redirect() instead. This autodetects if the current request is an ajax request and will return a special XML response which tells the JSF ajax engine to change the location of the window. If you're not inside the JSF context (e.g. inside a Filter
), then you need to create this special XML response yourself as follows:
response.setContentType("text/xml");
response.getWriter()
.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
.printf("<partial-response><redirect url=\"%s\"></redirect></partial-response>", url);
See also:
- Using JSF 2.0 / Facelets, is there a way to attach a global listener to all AJAX calls?
回答2:
FacesContext.getCurrentInstance().getExternalContext().redirect(url);
来源:https://stackoverflow.com/questions/10954319/jsf-2-response-sendredirect-is-not-working