Nik*_*hil 58 session session-scope httpsession jsf-2 managed-bean
在JSF 2.0应用程序中使会话无效的最佳方法是什么?我知道JSF本身不会处理会话.到目前为止我能找到
private void reset() {
HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
.getExternalContext().getSession(false);
session.invalidate();
}
Run Code Online (Sandbox Code Playgroud)
@SessionScoped
UserBean处理用户的登录注销.我在同一个bean中有这个方法.现在,当我reset()
完成必要的数据库更新后调用该方法时,我当前的会话作用域bean会发生什么?既然豆本身也存放在HttpSession
?Bal*_*usC 124
首先,这种方法是否正确?有没有办法没有触及ServletAPI?
您可以使用它ExternalContext#invalidateSession()
来使会话无效,而无需获取Servlet API.
@ManagedBean
@SessionScoped
public class UserManager {
private User current;
public String logout() {
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
return "/home.xhtml?faces-redirect=true";
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
我当前会话scoped bean会发生什么?因为即使bean本身也存储在HttpSession中?
它仍然可以在当前响应中访问,但在下一个请求中它将不再存在.因此,在invalidate之后触发重定向(新请求)非常重要,否则您仍然会显示旧会话中的数据.可以通过添加faces-redirect=true
结果来完成重定向,就像我在上面的示例中所做的那样.另一种发送重定向的方法是使用ExternalContext#redirect()
.
public void logout() throws IOException {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
ec.invalidateSession();
ec.redirect(ec.getRequestContextPath() + "/home.xhtml");
}
Run Code Online (Sandbox Code Playgroud)
然而,在这种情况下,它的使用是有问题的,因为使用导航结果更简单.
小智 13
public void logout() {
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
}
Run Code Online (Sandbox Code Playgroud)