我从未使用过有状态的EJB.我知道有状态EJB对java客户端很有用.
但我想知道:在哪种情况下在Web应用程序中使用它们?如何?我们应该把这些有状态的bean放在Session中吗(因为无状态的http)?
这是一个好习惯吗?(没有过多讨论有状态与无状态)
如果我想使用我的Web应用程序跟踪每个客户端的会话状态,这是一个更好的选择 - 会话Bean还是HTTP会话 - 要使用?
//request is a variable of the class javax.servlet.http.HttpServletRequest
//UserState is a POJO
HttpSession session = request.getSession(true);
UserState state = (UserState)(session.getAttribute("UserState"));
if (state == null) { //create default value .. }
String uid = state.getUID();
//now do things with the user id
Run Code Online (Sandbox Code Playgroud)
在ServletContextListener的实现中注册为Web应用程序监听器WEB-INF/web.xml:
//UserState NOT a POJO this this time, it is
//the interface of the UserStateBean Stateful Session EJB
@EJB
private UserState userStateBean;
public void contextInitialized(ServletContextEvent sce) {
ServletContext servletContext …Run Code Online (Sandbox Code Playgroud) 我们目前有一个注入Servlet的有状态bean.问题是有时候我们会Caused by: javax.ejb.ConcurrentAccessException: SessionBean is executing another request. [session-key: 7d90c02200a81f-752fe1cd-1]在有状态bean上执行一个方法.
public class NewServlet extends HttpServlet {
@EJB
private ReportLocal reportBean;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String[] parameters = fetchParameters(request);
out.write(reportBean.constructReport(parameters));
} finally {
out.close();
}
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,constructReport将检查是否需要打开与Report中指定的数据库的新连接,之后在根据指定的参数构建的查询中构建HTML中的Report.
我们选择在无状态bean上使用有状态bean的原因是因为我们需要打开与未知数据库的数据库连接并对其执行查询.对于无状态bean,使用每个注入的bean实例重复打开和关闭数据库连接似乎非常低效.