Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Response object in JSF

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.

like image 362
Akheloes Avatar asked May 27 '13 16:05

Akheloes


2 Answers

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.

like image 78
Sazzadur Rahaman Avatar answered Sep 22 '22 23:09

Sazzadur Rahaman


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.

like image 43
Luiggi Mendoza Avatar answered Sep 23 '22 23:09

Luiggi Mendoza