@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");
}
}
答案 0 :(得分:3)
此代码应该可以正常工作。请注意,FacesContext
不一定在那里可用,因为在该点运行的线程中不一定有HTTP请求的方法,但您已经对其进行了评估。您确定您实际正在运行问题中显示的代码吗?清理,重建,重新部署等。
另一种方法是让UserSessionBean
实施HttpSessionBindingListener
,然后使用valueUnbound()
方法完成工作。
@ManagedBean
@SessionScoped
public class UserSessionBean implements HttpSessionBindingListener {
@Override
public void valueUnbound(HttpSessionBindingEvent event) {
for (File file : files) {
file.delete();
}
}
// ...
}