在JSF 2.0应用程序中使会话无效的最佳方法是什么?我知道JSF本身不会处理会话。到目前为止,我找到了
private void reset() {
HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
.getExternalContext().getSession(false);
session.invalidate();
}
@SessionScoped
UserBean处理的情况
登录注销用户。我在同一个bean中有这个方法。现在
在我完成必要的DB之后调用reset()
方法时
更新,我当前会话scoped bean会发生什么?以来
甚至bean本身都存储在HttpSession
?答案 0 :(得分: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";
}
// ...
}
我当前的会话作用域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");
}
然而,在这种情况下,它的使用是有问题的,因为使用导航结果更简单。
答案 1 :(得分:13)
public void logout() {
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
}
答案 2 :(得分:-1)
前端代码为:
<h:form>
<h:commandLink action="#{userManager.logout()}">
<span>Close your session</span>
</h:commandLink>
</h:form>
后端代码为:
public String logout() {
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
if (session != null) {
session.invalidate();
}
return "/login.xhtml?faces-redirect=true";
}