从HttpSessionListener获取SessionScoped bean?

大家好。 我正在尝试在HttpSessionListener中获取会话bean,以便当用户注销或会话到期时,我可以删除用户在应用程序中创建的一些文件。 我猜测会话bean不存在,因为会话被销毁了。 我希望仍然删除这些文件的一些方法。 谢谢您的帮助。

@WebListener public class SessionListener implements HttpSessionListener { @Override public void sessionCreated(HttpSessionEvent se) { HttpSession session = se.getSession(); System.out.print(getTime() + " (session) Created:"); System.out.println("ID=" + session.getId() + " MaxInactiveInterval=" + session.getMaxInactiveInterval()); } @Override public void sessionDestroyed(HttpSessionEvent se) { HttpSession session = se.getSession(); FacesContext context = FacesContext.getCurrentInstance(); //UserSessionBean userSessionBean = (UserSessionBean) context.getApplication().evaluateExpressionGet(context, "#{userSessionBean}", UserSessionBean.class) UserSessionBean userSessionBean = (UserSessionBean) session.getAttribute("userSessionBean"); System.out.println(session.getId()); System.out.println("File size :" + userSessionBean.getFileList().size()); for (File file : userSessionBean.getFileList()) { file.delete(); } } } 

致BalusC:我回到了你之前想到的方法。 在我的应用程序中,将字节流式传输给用户并不灵活。 我发现我需要在页面上的ajax中做很多事情,如果我必须发送非ajax请求来流式传输要下载的文件,那么这是不可能的。 这样,通过ajax调用(生成文档)完成繁重的工作,并且可以使用非ajax调用来完成快速简便的工作。

  @ManagedBean(name = "userSessionBean") @SessionScoped public class UserSessionBean implements Serializable, HttpSessionBindingListener { final Logger logger = LoggerFactory.getLogger(UserSessionBean.class); @Inject private User currentUser; @EJB UserService userService; private List fileList; public UserSessionBean() { fileList = new ArrayList(); } @PostConstruct public void onLoad() { Principal principal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal(); String email = principal.getName(); if (email != null) { currentUser = userService.findUserbyEmail(email); } else { logger.error("Couldn't find user information from login!"); } } public User getCurrentUser() { return currentUser; } public void setCurrentUser(User currentUser) { this.currentUser = currentUser; } public List getFileList() { return fileList; } @Override public void valueUnbound(HttpSessionBindingEvent event) { logger.info("UserSession unbound"); logger.info(String.valueOf(fileList.size())); for (File file : fileList) { logger.info(file.getName()); file.delete(); } } @Override public void valueBound(HttpSessionBindingEvent event) { logger.info("UserSessionBean bound"); } } 

此代码应该可以正常工作。 请注意, FacesContext不一定在那里可用,因为在该点运行的线程中不一定有HTTP请求的方法,但是您已经对其进行了评估。 您确定您实际上正在运行问题中显示的代码吗? 清洁,重建,重新部署等

另一种方法是让UserSessionBean实现HttpSessionBindingListener ,然后在valueUnbound()方法中执行该任务。

 @ManagedBean @SessionScoped public class UserSessionBean implements HttpSessionBindingListener { @Override public void valueUnbound(HttpSessionBindingEvent event) { for (File file : files) { file.delete(); } } // ... }