Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExternalContext#redirect() does not redirect to parent directory

I have two pages:

String page1 = "user/newuser.jsf";
String page2 = "department/newdepartment.jsf";

If I redirect to page1 like this:

FacesContext.getCurrentInstance().getExternalContext().redirect(page1);

URL changes to localhost:8080/NavFile/user/newuser.jsf.

On this page I redirect to page2:

FacesContext.getCurrentInstance().getExternalContext().redirect(page2);

URL changes to localhost:8080/NavFile/user/department/newdepartment.jsf. But there is no user/department directory in my application. My goal was to redirect to localhost:8080/NavFile/department/newdepartment.jsf.

How is this caused and how can I solve it?

like image 371
abdurrahimefe Avatar asked Feb 25 '13 15:02

abdurrahimefe


People also ask

What is ExternalContext?

public abstract class ExternalContext extends Object. This class allows the Faces API to be unaware of the nature of its containing application environment. In particular, this class allows JavaServer Faces based appications to run in either a Servlet or a Portlet environment.

What does FacesContext getCurrentInstance () do?

getCurrentInstance. Return the FacesContext instance for the request that is being processed by the current thread.


1 Answers

A relative redirect URL (i.e. when not starting with / or scheme) is relative to the current request URL (as the enduser sees in browser's address bar). It's not magically relative to the context path in the server side as this information is completely unknown in the client side (you know, a redirect is performed by the webbrowser, not by the webserver).

If you want to redirect relative to the context path, then you should include the context path so that it becomes domain-relative. You can get the context path dynamically via ExternalContext#getRequestContextPath().

ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
ec.redirect(ec.getRequestContextPath() + "/" + page1);

In case of page2, the full redirect URL becomes /user/department/newdepartment.jsf and the leading slash / would make it relative to the domain http://localhost:8080, which is exactly what you want.

See also:

  • What URL to use to link / navigate to other JSF pages
  • Redirect to external URL in JSF
  • Hit a bean method and redirect on a GET request
  • How to navigate in JSF? How to make URL reflect current page (and not previous one)
like image 93
BalusC Avatar answered Sep 20 '22 07:09

BalusC