代码之家  ›  专栏  ›  技术社区  ›  Barry Brown

GWT-RPC:跨多个请求使用相同的DB连接

  •  1
  • Barry Brown  · 技术社区  · 15 年前

    我正在开发一个数据库的web前端。其目的是创建一个学生可以用来学习SQL、发出查询并查看结果的工具。在此之前,我一直在使用CLI。它的主要缺点是a)现在的学生更习惯于gui;b)当查询返回一个非常宽的表时,它很难阅读,因为它是环绕的。我的webgui旨在解决这些缺陷。

    我使用GWT作为客户端前端和PostgreSQL数据库后端。GWT通过Jetty或Tomcat托管的javaservlet容器与数据库通信。

    (这不是一个高性能的数据库服务器。这是一个教学工具,所以我更看重用户体验而不是速度。)

    为了实现这一点,我需要确保通过整个事务,客户机将连接到同一个数据库连接。使用传统(无状态)技术,数据库连接要么是短期的,要么是池连接。因此,不能确定同一数据库连接将在多个查询之间使用。

    恐怕我对javaservlets有点陌生,所以我有几个问题要问。

    首先也是最重要的是,是否有一种现有的机制可以打开数据库连接并在整个用户会话中使用它?

    1 回复  |  直到 15 年前
        1
  •  3
  •   dslh    15 年前

    Java servlet保持 HttpSession

    // getThreadLocalRequest is a member of GWT's RemoteServiceServlet
    HttpSession session = getThreadLocalRequest().getSession();
    Connection connection = (Connection)session.getAttribute("connection");
    
    if (connection == null) {
         // I'll leave it to you to implement createConnection
         final Connection c = createConnection();
         connection = c;
    
         session.setAttribute("connection", connection);
         session.setAttribute("expiryListener", new HttpSessionBindingListener() {
             public void valueBound(HttpSessionBindingEvent e) {}
    
             // This method will be called when the user's session expires
             public void valueUnbound(HttpSessionBindingEvent e) {
                 c.close();
             }
         });
    }
    
    // connection is ready to use!
    Statement statement = connection.createStatement();
    
    推荐文章