7

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?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
abdurrahimefe
  • 123
  • 1
  • 1
  • 6

2 Answers2

15

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:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
-1

You can do it like this:

String redirectTo = "../department/newdepartment.jsf"; FacesContext.getCurrentInstance().getExternalContext().redirect(redirectTo );

It works for me.

Vic
  • 1
  • Hi and welcome to Stack Overflow! Please take the [tour](https://stackoverflow.com/tour). Thanks for contributing an answer but can you also add an explanation on how your code solves the problem? Check this [help center article](https://stackoverflow.com/editing-help) for info on how to format code. – Jeanne Dark Dec 02 '20 at 08:32
  • This approach is not recommended. It will break when the current URL is not at all in a subfolder. You must use `ec.getRequestContextPath()` instead of `".."` to avoid this potential bug. See also the currently accepted answer. – BalusC Dec 02 '20 at 11:33