I have at least 2 Servlets and try to share Statefull bean between them. But, unfortunatelly, I can't because it inits for each Servlet.
@WebServlet(name = "FirstServlet", urlPatterns = {"/first/*"})
public class FirstServlet extends BaseServlet {
@EJB
private IUserSession userSession;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
userSession.setUserName("my name");
// todo something and put breakpoint here
}
}
@WebServlet(name = "SecondServlet", urlPatterns = {"/second/*"})
public class SecondServletextends BaseServlet {
@EJB
private IUserSession userSession;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// todo something and put breakpoint here
}
}
public interface IUserSession {
void initItems();
void setUserName(String userName)
}
@Stateful(name = "userSession")
public class UserSession implements IUserSession {
private String userName;
@PostConstruct
private void init() {
initItems();
}
public void initItems(){
// todo something
}
public void setUserName(String userName){
this.userName = userName;
}
}
So, while I am debugging, I can see, that before call doGet FirstServlet we go in to UserSession.init() method because it is PostConstruct. After we go into FirstServlet.doGet(). When I do the second request in the same session via browser and go to the SecondServlet I again go into UserSession.init() and after that, of course SecondServlet.userSession.userName return null.
How to share UserSession inside Application? I want to construct some... SessionBean for user information.
I know, that I can put it inside request like
request.getSession().setAttribute(USER_SESSION_KEY, userSession)
but I want to use Enterprise mechanism. I am sure that I lost something easy but important.