相关疑难解决方法(0)

Web应用程序中的有状态EJB?

我从未使用过有状态的EJB.我知道有状态EJB对java客户端很有用.

但我想知道:在哪种情况下在Web应用程序中使用它们?如何?我们应该把这些有状态的bean放在Session中吗(因为无状态的http)?

这是一个好习惯吗?(没有过多讨论有状态与无状态)

web-applications stateful java-ee ejb-3.0

15
推荐指数
1
解决办法
6581
查看次数

Java:跟踪用户登录会话 - 会话EJB与HTTPSession

如果我想使用我的Web应用程序跟踪每个客户端的会话状态,这是一个更好的选择 - 会话Bean还是HTTP会话 - 要使用?

使用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)

使用Session EJB:

在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)

java session servlets ejb stateful

13
推荐指数
1
解决办法
1万
查看次数

使用Servlet正确使用有状态Bean

我们目前有一个注入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实例重复打开和关闭数据库连接似乎非常低效.

java servlets ejb stateful java-ee

8
推荐指数
2
解决办法
8396
查看次数

标签 统计

stateful ×3

ejb ×2

java ×2

java-ee ×2

servlets ×2

ejb-3.0 ×1

session ×1

web-applications ×1