0

In my JSF application I need to redirect from the the managed bean constructor. I have following code to do so:

HttpServletResponse httpServletResponse = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
httpServletResponse.sendRedirect("HomeV.jsf");

but this is throwing following exception:

java.lang.IllegalStateException
    at org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:435)
    at javax.servlet.http.HttpServletResponseWrapper.sendRedirect(HttpServletResponseWrapper.java:126)
    at com.sun.faces.context.ExternalContextImpl.redirect(ExternalContextImpl.java:419)

I even tried following:

FacesContext.getCurrentInstance().getExternalContext().redirect("HomeV.jsf");

as mentioned in the stackoverflow question related to this here but still I face the same exception.

Community
  • 1
  • 1
Abhishek Dhote
  • 1,638
  • 10
  • 41
  • 62
  • Related: http://stackoverflow.com/questions/4032825/how-to-make-a-redirection-in-jsf/4099405#4099405 But in this particular case you don't seem to need navigation cases. Depending on the functional requirement I'd use a Filter. – BalusC Apr 14 '11 at 12:29

2 Answers2

2

Don't do that in the constructor. I doubt the response is in a proper state there. Perhaps you can try doing it in @PostConstruct, but I don't guarantee it will work.

Ideally, you should do redirections via navigation rules from the bean action methods. If you want redirect on multiple actions, you can use a PhaseListener

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • +1 , @Abhishek you can add some more info why you are doing this ? – jmj Apr 14 '11 at 09:23
  • I tried this with navigation rule as well. The problem there is as follows: I call a method from the constructor of the bean and wrote the navigation to work on the outcome of this method. The function gets called from the bean and works as expected but dont see navigation happening. The reason I thought this is not working is, as navigation works on the action performed and not if the function getting called from some other function. Is my understanding right? Can someone suggest any other approach – Abhishek Dhote Apr 14 '11 at 10:01
  • @Abhishek yes, you are right. The constructor is something that should not be used in a managed environemtn like JSF/CDI. Why in the first place you want to redirect on bean creation? – Bozho Apr 14 '11 at 10:42
0

Beans can also be created when simply context is initialized, So This is not at all proper approach.

jmj
  • 237,923
  • 42
  • 401
  • 438