ExternalContext#redirect()不会重定向到父目录

abd*_*efe 7 directory jsf redirect parent

我有两页:

String page1 = "user/newuser.jsf";
String page2 = "department/newdepartment.jsf";
Run Code Online (Sandbox Code Playgroud)

如果我重定向到page1这样:

FacesContext.getCurrentInstance().getExternalContext().redirect(page1);
Run Code Online (Sandbox Code Playgroud)

网址更改为localhost:8080/NavFile/user/newuser.jsf.

在此页面上,我重定向到page2:

FacesContext.getCurrentInstance().getExternalContext().redirect(page2);
Run Code Online (Sandbox Code Playgroud)

网址更改为localhost:8080/NavFile/user/department/newdepartment.jsf.但是user/department我的应用程序中没有目录.我的目标是重定向到localhost:8080/NavFile/department/newdepartment.jsf.

这是怎么造成的,我该如何解决?

Bal*_*usC 13

相对重定向URL(即不以/或以方案开头)与当前请求URL相关(如最终用户在浏览器的地址栏中看到的).它不是神奇地相对于服务器端的上下文路径,因为这些信息在客户端是完全未知的(你知道,重定向是由webbrowser执行的,而不是由webserver执行的).

如果要相对于上下文路径重定向,则应包括上下文路径,以使其成为域相关.您可以通过动态获取上下文路径ExternalContext#getRequestContextPath().

ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
ec.redirect(ec.getRequestContextPath() + "/" + page1);
Run Code Online (Sandbox Code Playgroud)

如果是page2,完整的重定向URL变为/user/department/newdepartment.jsf,并且前导斜杠/将使其相对于域http://localhost:8080,这正是您想要的.

也可以看看: