Response object in JSF

Akheloes picture Akheloes · May 27, 2013 · Viewed 16.2k times · Source

I feel like this is going to be a question to which the shortest answer will be : "that's why JSF replaced JSP", but I'll just go ahead and ask it.

Question : I am wondering : could I obtain the Response object of a JSF page (if there's any) ?

Why wonder ? : I found myself in a situation where I need to to pass from a JSF page to a JSP one, so I thought why not redirect (with response.sendRedirect) from a bean that gets invoked from the JSF page and then... you can see where it's heading.

I feel like this can be done in a cleaner way, can't see how though !

EDIT : while on it, I'll also ask about which way would be best for redirecting from to JSF pages.

Thanks in advance for your suggestions.

Answer

Sazzadur Rahaman picture Sazzadur Rahaman · May 27, 2013

Well, if you want to get the response object, you can have it in JSF like bellow!

HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();

But you don't really need to get the response object only to redirect outside of JSF. This can be done more easily with the following:

ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
externalContext.redirect("http://www.example.com/myJspPage.jsp");

Edit:

When you are in any non-action method, you can use any of the above! But when you are in any action method, the proper JSF way of redirecting is:

public String goToOutsideAction(){
    ....
    return "/myPage.xhtml?faces-redirect=true"
}

The method should return a context-relative view ID and the target must be a JSF page.