在JSF2.0应用程序中使会话失效的最佳方法是什么?我知道JSF本身并不处理会话。到目前为止我能找到
private void reset() {
HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
.getExternalContext().getSession(false);
session.invalidate();
}
@SessionScoped
UserBean处理用户的登录-注销。我在同一个bean中也有这个方法。现在,当我在完成必要的DB更新后调用reset()
方法时,我当前的会话作用域bean将发生什么情况?因为即使是bean本身也存储在HttpSession
中
发布于 2011-04-11 19:25:54
首先,这个方法正确吗?有没有一种不接触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中?
它仍然可以在当前响应中访问,但在下一个请求中将不再存在。因此,在无效之后触发重定向(一个新请求)是很重要的,否则您仍然会显示来自旧会话的数据。重定向可以通过将faces-redirect=true
添加到结果来完成,就像我在上面的示例中所做的那样。另一种发送重定向的方法是使用ExternalContext#redirect()
。
public void logout() throws IOException {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
ec.invalidateSession();
ec.redirect(ec.getRequestContextPath() + "/home.xhtml");
}
然而,在这种情况下,它的使用是有问题的,因为使用导航结果更简单。
发布于 2012-07-19 17:57:04
public void logout() {
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
}
发布于 2020-12-11 19:21:29
前端代码为:
<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";
}
https://stackoverflow.com/questions/5619827
复制相似问题