我有两页:
String page1 = "user/newuser.jsf";
String page2 = "department/newdepartment.jsf";
如果我重定向到
page1
像这样:FacesContext.getCurrentInstance().getExternalContext().redirect(page1);
URL 更改为
localhost:8080/NavFile/user/newuser.jsf
.在此页面上,我重定向到
page2
:FacesContext.getCurrentInstance().getExternalContext().redirect(page2);
URL 更改为
localhost:8080/NavFile/user/department/newdepartment.jsf
.但是没有user/department
我的应用程序中的目录。我的目标是重定向到 localhost:8080/NavFile/department/newdepartment.jsf
.这是怎么引起的,我该如何解决?
最佳答案
相对重定向 URL(即当不以 /
或方案开头时)是相对于当前请求 URL(如最终用户在浏览器地址栏中看到的)。它与服务器端的上下文路径并不神奇,因为这些信息在客户端是完全未知的(您知道,重定向是由网络浏览器执行的,而不是由网络服务器执行的)。
如果要相对于上下文路径重定向,则应包含上下文路径,使其成为域相关的。您可以通过 ExternalContext#getRequestContextPath()
动态获取上下文路径.
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
ec.redirect(ec.getRequestContextPath() + "/" + page1);
如果是 page2
,完整的重定向 URL 变为 /user/department/newdepartment.jsf
和前导斜杠 /
将使它相对于域 http://localhost:8080
,这正是您想要的。也可以看看:
关于jsf - ExternalContext#redirect() 不会重定向到父目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15070505/