出于记录目的,我有兴趣检测 JSF 应用程序中何时发生 session 超时。
我已经实现了一个 PhaseListener 来检查用户是否已登录并且其 session 是否已处于 Activity 状态。我的 afterPhase 方法的实现是:
var url_accepted(在代码中使用)包含用户应有权访问的公共(public)页面列表,以便提供登录表单。
public void afterPhase(PhaseEvent event) { FacesContext context = event.getFacesContext(); HttpSession session = (HttpSession) context.getExternalContext().getSession(true); AuthenticationBean sessionBean = (AuthenticationBean) session.getAttribute("sessionBean"); String url_req = context.getViewRoot().getViewId(); //1. Check if user has a session and is logged in: if(((sessionBean == null) || (sessionBean != null && !sessionBean.isLoggedIn())) && !url_accepted.contains(url_req)){ context.getApplication().getNavigationHandler().handleNavigation(context,null,"auth_error"); return; } //2. Code continues in order to check if a logged user has permissions to access the requested page(not relevant): }
当用户由于 session 超时而断开连接时,PhaseListener 无法从 ExternalContext 检索我的 sessionBean,并将 null 分配给 sessionBean 属性。此时我无法区分用户是之前没有登录过还是超时断开连接。
我读到可以使用 errorPages 来检测 ViewExpiredException 异常并将 View 重定向到特定页面。但我不知道是否可以在我的源代码中管理此异常。
我的问题是:我可以在 PhaseListener 实现中捕获此 ViewExpiredException 以处理 session 超时吗?
提前致谢。
最佳答案
我在 JSF 项目中遇到过同样的情况。解决方案是使用过滤器来捕获过期的 session 。 BalusC(JSF专家)解释了这个问题并展示了一个很好的例子:
另外,别忘了加上session.invalidate()
在您的注销方法和 session 超时处理程序中。
关于java - 是否可以在 PhaseListener 中捕获 ViewExpiredException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11666210/