JSF Response Object

I feel that this will be the question that will have the shortest answer: “why did the JSF replace the JSP”, but I just go ahead and ask it.

Question: I am wondering: is it possible to get a Response object on a JSF page (if any)?

Why wonder? . I found myself in a situation where I needed to switch from a JSF page to a JSP, so I thought, why not redirect (with response.sendRedirect ) from the bean that is called from the JSF page, and then ... you can see where it is heading.

It seems to me that this can be done in a cleaner way, I can’t understand how to do it!

EDIT: while I'm on it, I will also ask which way is best to redirect to JSF pages.

Thanks in advance for your suggestions.

+4
source share
2 answers

Well, if you want to get a response object, you can get it in JSF , as shown below:

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

But you really don't need to get a response object just for redirection 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

If you use any non-action method, you can use any of the above! But when you are in any action , the correct JSF redirection method is:

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

The method should return a context-specific view identifier, and the target should be a JSF page.

+9
source

You can get the response object in a managed bean by calling

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

Code adapted from How to transfer file upload to JSF bean support? )

When you have a response object, you can perform any operation on it, like changing the headers. Obviously, there are things you cannot do, like sending a redirect from an ajax request.

+1
source

Source: https://habr.com/ru/post/1482996/


All Articles