大家好。我正在尝试在 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<File> fileList;
public UserSessionBean() {
fileList = new ArrayList<File>();
}
@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<File> 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");
}
}