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.
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.
You can obtain the response object in the managed bean by calling
HttpServletResponse response = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse()
Code adapted from How to stream a file download in a JSF backing bean?)
Once you have the response object you can perform any operations on it like changing the headers. Obviously, there are things that you can't do like sending a redirect from an ajax request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With