如何在JSF 2.0中使会话无效? [英] How to invalidate session in JSF 2.0?
问题描述
在JSF 2.0应用程序中使会话无效的最佳方法是什么?我知道JSF本身不处理会话.到目前为止,我可以找到
What is the best possible way to invalidate session within a JSF 2.0 application? I know JSF itself does not handle session. So far I could find
private void reset() {
HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
.getExternalContext().getSession(false);
session.invalidate();
}
- 此方法正确吗?有没有办法不碰 ServletAPI?
- 考虑以下情况,其中
@SessionScoped
UserBean处理 用户的注销登录.我在同一个bean中有此方法.现在 完成必要的数据库后调用reset()
方法时 更新,我当前的会话作用域bean将发生什么?自从 甚至bean本身也存储在HttpSession
中?
- Is this method correct? Is there a way without touching the ServletAPI?
- Consider a scenario wherein a
@SessionScoped
UserBean handles the login-logout of a user. I have this method in the same bean. Now when I call thereset()
method after I'm done with necessary DB updates, what will happen to my current session scoped bean? since even the bean itself is stored inHttpSession
?
推荐答案
首先,此方法正确吗?有没有不碰ServletAPI的方法?
您可以使用 ExternalContext#invalidateSession()
使会话无效,而无需获取Servlet API.
You can use ExternalContext#invalidateSession()
to invalidate the session without the need to grab the 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()
.
It will still be accessible in the current response, but it will not be there anymore in the next request. Thus it's important that a redirect (a new request) is fired after invalidate, otherwise you're still displaying data from the old session. A redirect can be done by adding faces-redirect=true
to the outcome, as I did in the above example. Another way of sending a redirect is using ExternalContext#redirect()
.
public void logout() throws IOException {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
ec.invalidateSession();
ec.redirect(ec.getRequestContextPath() + "/home.xhtml");
}
但是,在这种情况下,它的使用值得怀疑,因为使用导航结果更为简单.
Its use is however questionable in this context as using a navigation outcome is simpler.
这篇关于如何在JSF 2.0中使会话无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!