When navigating from the login page of my portal to the index page, there is a situation when based on some facts the user can be redirected externally, which looks like:
if (!(marketVo.getAbsoluteUrl() != null && marketVo.getAbsoluteUrl().equals(absoluteUrlToRedirect))) {
logger.info("---WILL REDIRECT TO ABS URL: " + absoluteUrlToRedirect);
final FacesContext context = FacesContext.getCurrentInstance();
context.responseComplete();
try {
final HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
if (context.getViewRoot() != null) {
// this step will clear any queued events
context.getViewRoot().processDecodes(context);
}
response.sendRedirect(absoluteUrlToRedirect);
} catch (final Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Well, it throws an exception:
14:24:35,579 INFO [CmwSessionHelperBean] ---WILL REDIRECT TO ABS URL: http://hi
tachi.mygravitant.com
14:24:35,580 ERROR [STDERR] java.lang.IllegalStateException
14:24:35,582 ERROR [STDERR] at org.apache.catalina.connector.ResponseFacade.
sendRedirect(ResponseFacade.java:435)
14:24:35,590 ERROR [STDERR] at com.example.cloud.common.jsf.core.beans.Cmw
SessionHelperBean.createCmwUserSession(CmwSessionHelperBean.java:269)
Can you please give me a suggestion to avoid this exception to occure? Please note that the redirect is done, but because of this exception, when I come back to my portal, it is no longer working properly...
You should be using ExternalContext#redirect()
to perform a redirect in a JSF-safe way.
public void createCmwUserSession() throws IOException {
if (!(marketVo.getAbsoluteUrl() != null && marketVo.getAbsoluteUrl().equals(absoluteUrlToRedirect))) {
logger.info("---WILL REDIRECT TO ABS URL: " + absoluteUrlToRedirect);
FacesContext.getCurrentInstance().getExternalContext().redirect(absoluteUrlToRedirect);
}
}
This method will also implicitly call FacesContext#responseComplete()
, you don't need to do it yourself.
Further you need to make sure that you are not calling the redirect method multiple times on the same response, or are performing a navigation afterwards.