Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 259|回复: 0

[servlet学习]在servlet中用连接池DDConnectionBroker

[复制链接]
  • TA的每日心情
    开心
    2021-3-12 23:18
  • 签到天数: 2 天

    [LV.1]初来乍到

    发表于 2014-10-10 00:57:11 | 显示全部楼层 |阅读模式
    下面用到的连接代理DDConnectionBroker,请从http://opensource.devdaily.com/下载其jar文件DDConnectionBroker.jar。

      

      
        先写一个Singleton(单态)类,以便在服务器中共享连接池。

    package examples;

    import com.devdaily.opensource.database.DDConnectionBroker;

    import java.io.*;

    import java.sql.*;  
       
       /**
       /* This is our class that will be shared across all of the
        * Servlets for the "Lavender" database. It is a singleton,
        * and also works as an adapter to the connection broker
        * class that we are using.
       */  
      
       
       
         
       
                         
         
       
      
      
       public class LavenderDBSingleton
       {
       
         private DDConnectionBroker m_broker;
         private static LavenderDBSingleton m_singleton = null;
       
         private LavenderDBSingleton()
         {
            /*
             * We will put all of our database-specific information
             * here. Please note that we could have read this
             * information from a properties file.
             */
       
              String driver         = "sun.jdbc.odbc.JdbcOdbcDriver";
              String url            = "jdbc:odbc:Lavender";
              String uname = "";
              String passwd = "";  
       
              int minConnections  = 1;
              int maxConnections  = 10;
              long timeout        = 100;
              long leaseTime      = 60000;
              String logFile        = "c:/tmp/ConnectionPool.log";  
               
              try
              {
                  m_broker = new DDConnectionBroker(driver,
                                                  url, uname, passwd,
                                                  minConnections,
                                                  maxConnections,
                                                  timeout,
                                                  leaseTime,
                                                  logFile);
              }
              catch (SQLException se)
              {
                  System.err.println( se.getMessage() );
              }
         }
         /**  
          *  getInstance() returns the class, instantiating it
          *  if there is not yet an instance in the VM.  
          */
         public static LavenderDBSingleton getInstance()
         {
             if (m_singleton == null)
             {
                 m_singleton = new LavenderDBSingleton();  
             }
             
             return (m_singleton);  
         }
       
         /*
          * calls getConnection() on the broker class  
          */
         public synchronized Connection getConnection() throws Exception  
         {
             if (m_broker == null)
             {
                 throw new Exception("Can"t get Connection broker!");  
             }
             return (m_broker.getConnection());
         }
       
         /*
          * frees the connection from the broker class
          */
         public synchronized void freeConnection(Connection con)  
          throws Exception  
         {
             if (m_broker == null )
             {
                 throw new Exception("Can"t get Connection broker!");  
             }
             m_broker.freeConnection(con);  
         }
       }

    下面是测试代码:

    package examples;

    import java.io.*;
    import java.sql.*;
    import java.text.*;
    import java.util.*;  
    import javax.servlet.*;
    import javax.servlet.http.*;

    public class BestQueryServlet extends HttpServlet
    {
       //only set in the init() method, so concurrency
       //issues should be fine.  
       private LavenderDBSingleton m_dbsingleton = null;

       public void init()
       {
         /*
          * This will instantiate it within the Servlet"s
          * virtual machine if it hasn"t already. If it  
          * has, we have the instance of it.  
          */
         m_dbsingleton = LavenderDBSingleton.getInstance();   
       }
       /**
        *  simply forwards all to doPost()  
        */
       public void doGet(HttpServletRequest request,
                         HttpServletResponse response)
       throws IOException, ServletException
       {
         doPost(request,response);  
       }

       /**
        * The main form!  
        */
       public void doPost(HttpServletRequest request,
                          HttpServletResponse response)
       throws IOException, ServletException
       {
         PrintWriter out = response.getWriter();  

         out.println("<TITLE>Internal Inventory Check</TITLE>");  
         out.println("<BODY BGCOLOR="white">");
         out.println("<H1>Lavender Fields Farm Internal Inventory</H1>");

         //show the date.  
         SimpleDateFormat sdf =new SimpleDateFormat ("EEE, MMM d, yyyy h:mm a");  
         java.util.Date newdate = new java.util.Date(Calendar.getInstance().getTime().getTime());  
         String datestring = sdf.format(newdate);  

         out.println("<H3>Inventory as of: " + datestring + "</H3>");  

         out.println("<TABLE BORDER=1>");
         out.println("<TR><TD BGCOLOR="yellow">" +
                     "<B><CENTER>Name</CENTER></B></TD>" +
                     "<TD BGCOLOR="yellow"><B>" +
                     "<CENTER>Description</CENTER></B></TD>" +
                     "<TD BGCOLOR="yellow"><B>" +
                     "<CENTER>Inventory Amount</CENTER></B></TD></TR>");

         //Load the inventory from the database.  

         try
         {

           Connection con = m_dbsingleton.getConnection();
           if (con == null)
           {
             out.println("<B>There are currently database problems. " +
                         "Please see your administrator for details.</B>");
             return;  
           }


           Statement stmt = con.createStatement();
           ResultSet rs = stmt.executeQuery("select * from Inventory");

           while (rs.next())
           {
             String amtString = "";  
             int amt = rs.getInt("Amount");  
             if (amt < 50)
               amtString ="<TD><CENTER><FONT COLOR="RED">" +  
                            amt + "</FONT></CENTER></TD>";
             else
               amtString ="<TD><CENTER>" +  
                            amt + "</CENTER></TD>";  

             out.println("<TR><TD><CENTER>" + rs.getString("Name") +  
                         "</CENTER></TD><TD><CENTER>" +  
                         rs.getString("Description") +  
                         "</CENTER></TD>" + amtString + "</TR>");                                    
           }
           rs.close();
           out.println("</TABLE><HR>Items in <FONT COLOR="red">RED</FONT>" +
                       " denote a possible low inventory. Click Here to " +
                       " contact <A HREF="mailto:mgmt@localhost">" +
                       "MANAGEMENT</A> to order more supplies.");

           //Free the connection!
           m_dbsingleton.freeConnection( con );

         }  
         catch (Exception e)
         {
           out.println("There were errors connecting to the database." +
                       " Please see your systems administrator for details.");
           e.printStackTrace();  
         }

       }

    }

    在我们的应用中需要连接时,只需简单地象下面这样:

       LavenderDBSingleton singleton=LavenderDBSingleton.getInstance();
       Connection con=singleton.getConnection();
       try{
           Statement stmt=con.createStatement();
           ResultSet rs=stmt.executeQuery("select * from Inventory");
           //do something
           singleton.freeConnection(con);
      }catch(Exception e){
        //......
      }

      

      
      
       
       

         
       

         
       
      



    源码下载:http://file.javaxxz.com/2014/10/10/005711125.zip
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-6-16 07:52 , Processed in 0.304341 second(s), 38 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表