[英]Most elegant way to update data from a user POST in a SessionScoped bean (CDI, JSF)
[英]@Schedule could not fetch data from @SessionScoped CDI bean
登錄后存儲在 SessionScoped bean 中的用戶數據。 我想每 5 秒獲取存儲在 session 中的每個帳戶並發送到后端。 我的計時器
@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 class。 將用戶數據保存在前端的唯一方法是將帳戶保存到 SessionScoped CDI bean,不推薦使用 JSF 原生 bean。
您將收到如下錯誤:WELD-001303: No active contexts for scope type javax.enterprise.context.SessionScoped
項目位置在這里https://github.com/armdev/eap Class 自己https://github.com/armdev/eap/blob/master/eap-webapp/ /前端定時器.java
基本上我想要一個標准計時器,可以從 Session Scope 獲取數據。
您當前的方法將無法按預期工作,因為每個調度程序調用都將發生在與會話完全隔離的上下文中(因此出現No active contexts...
錯誤消息)。
我建議你在這里使用一個簡單的反轉。 在您的應用程序范圍 singleton 中,添加一個簡單的List<String> currentSessions
和相應的方法到void add(String account)
和void remove(String account)
。 然后@Inject
singleton 到 session 范圍的 bean 中(而不是相反)。 最后,添加一個@WebListener
來處理 session 事件。
@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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.