登录后,用户数据存储在SessionScoped bean中。我想每5秒钟就将每个帐户存储在会话中并发送到后端。我的计时器
@Singleton
@Startup
public class FrontendTimer {
@Inject
private UserContext userContext;
@Schedule(second = "*/5", minute = "*", hour = "*", persistent = false)
@Asynchronous
public void atSchedule() throws InterruptedException {
System.out.println("Get Logged user stored in the session each 5 seconds ");
System.out.println("FR " + userContext.getAccount().toString());
}
}
启动调度程序的唯一方法是创建@Startup和@Singleton类。只有这样才能将用户数据保留在前端,将帐户保存到SessionScoped CDI bean,不建议使用JSF本机bean。
您将收到类似这样的错误:WELD-001303:作用域类型javax.enterprise.context.SessionScoped没有活动上下文
项目位置在这里https://github.com/armdev/eap单独分类https://github.com/armdev/eap/blob/master/eap-web/src/main/java/io/project/app/beans/FrontendTimer.java
基本上我希望有一个标准计时器,可以从Session Scope中获取数据。
您当前的方法将无法按您预期的那样工作,因为每次调度程序调用都将在与会话完全隔离的上下文中发生(因此No active contexts...
错误消息。
我建议您在这里使用简单的反演。在应用程序范围内的单例中,向List<String> currentSessions
和void add(String account)
添加一个简单的void remove(String account)
和相应的方法。然后,将@Inject
单身人士放入会话范围的Bean(而不是相反)。最后,添加@WebListener
以处理会话事件。
@Singleton
public class SessionManager {
private List<String> currentSessions;
@Schedule(second = "*/5", minute = "*", hour = "*", persistent = false)
@Asynchronous
public void atSchedule() throws InterruptedException {
//Do something with currentSessions
}
public void add(String account){
currentSessions.add(account);
}
public void remove(String account){
currentSessions.remove(account);
}
}
@SessionScoped
public class UserContext implements Serializable {
@Inject
private SessionManager sessionManager;
/*
...
*/
public void sessionCreated(){
sessionManager.add(account.toString());
}
public void sessionDestroyed(){
sessionManager.remove(account.toString());
}
}
@WebListener
public class SessionListener implements HttpSessionListener {
@Override
public void sessionCreated(HttpSessionEvent se) {
HttpSession session = se.getSession();
FacesContext context = FacesContext.getCurrentInstance();
UserContext userContext = (UserContext) session.getAttribute("userContext");
userContext.sessionCreated();
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
HttpSession session = se.getSession();
FacesContext context = FacesContext.getCurrentInstance();
UserContext userContext = (UserContext) session.getAttribute("userContext");
userContext.sessionDestroyed();
}
}