溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Tomcat中數(shù)據(jù)庫連接池如何設(shè)置與應(yīng)用

發(fā)布時間:2021-11-01 10:06:41 來源:億速云 閱讀:151 作者:小新 欄目:MySQL數(shù)據(jù)庫

這篇文章主要介紹了Tomcat中數(shù)據(jù)庫連接池如何設(shè)置與應(yīng)用,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

配置:Tomcat5.5+JEE(jsdk1.5)+WINXP

還是簡單的說一說文件配置:
1:修改%tomcat%/conf/server.xml在

后加如下內(nèi)容.
     <Resource
name="jdbc/DBPool" //數(shù)據(jù)源名稱
     type="javax.sql.DataSource"
     password="xxxxxxxx"
     driverClassName="com.mysql.jdbc.Driver"
     maxIdle="2"
     maxWait="5000"
     username="root"
     url="jdbc:mysql://127.0.0.1:3306/hptest"
     maxActive="4"/>
2.修改%tomcat%/conf/context.xm;在后加
  <ResourceLink
name="jdbc/DBPool"
  type="javax.sql.DataSource"
  global="jdbc/DBPool"/>
3.修改%tomcat%/conf/web.xml

   MySQL DB Connection Pool
   jdbc/DBPool
   javax.sql.DataSource
   Container
   Shareable

 這樣配置就算差不多了.如果具體的還不懂可見上次發(fā)的文章.
4.寫一個程序測試.(寫一個WEB程序)
  我的是Myeclipse 寫的程序,這里不能從電腦上貼圖真有點不方便(我想哭).
    1:寫一個連接類:    
 DBPool.java
package com.test;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DBPool {
   private static DataSource pool;
   static {
        Context env = null;
         try {
             env = (Context) new InitialContext().lookup("java:comp/env");
             pool = (DataSource)env.lookup("jdbc/DBPool");
             if(pool==null)
                 System.err.println("'DBPool' is an unknown DataSource");
              } catch(NamingException ne) {
                 ne.printStackTrace();
         }
     }
   public static DataSource getPool() {
       return pool;
   }
 
}
   2:寫一個Servlet:  
 其中有是用來連接數(shù)據(jù)庫和顯示查詢結(jié)果.
 Mytest.java
 package com.test;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Mytest extends HttpServlet {

   /**
    * Constructor of the object.
    */
   public Mytest() {
       super();
   }

   /**
    * Destruction of the servlet.

    */
   public void destroy() {
       super.destroy(); // Just puts "destroy" string in log
       // Put your code here
   }

   /**
    * The doGet method of the servlet.

    *
    * This method is called when a form has its tag value method equals to get.
    *
    * @param request the request send by the client to the server
    * @param response the response send by the server to the client
    * @throws ServletException if an error occurred
    * @throws IOException if an error occurred
    */
   public void doGet(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {

       response.setContentType("text/html;charset=gb2312");
       PrintWriter out = response.getWriter();
       String id=(String)request.getParameter("id");
       Connection con=null;
       try{
           
           con=DBPool.getPool().getConnection();
            Statement stmt=con.createStatement();
               ResultSet rst=stmt.executeQuery("select * from userinf where userid='"+id+"'");
                 if(rst.next()){
                                         out.println("
ID號:"+rst.getInt("userid"));
                     out.println("
用戶名:"+com.test.ASSICTOGBR2312.trans(rst.getString("name")));
                     out.println("
地址:"+rst.getString("address" ));
                     out.println("
生日"+rst.getDate("year" ));
                 }
                 else{
                 out.println("沒有這個ID");
                 stmt.close();
                 }
       }
       catch(Exception e){
           e.printStackTrace();
       }
       finally{  //一定要注意這里對數(shù)據(jù)庫的關(guān)閉不然
                            //自己想了
           try{
               if(con!=null){
                   con.close();
               }
               
           }
         catch(Exception e){
          e.printStackTrace();
         
      }
           
       }
   
   }

   /**
    * The doPost method of the servlet.

    *
    * This method is called when a form has its tag value method equals to post.
    *
    * @param request the request send by the client to the server
    * @param response the response send by the server to the client
    * @throws ServletException if an error occurred
    * @throws IOException if an error occurred
    */
   public void doPost(HttpServletRequest request, HttpServletResponse response)
           throws ServletException, IOException {
       doGet(request,response);
       
   }

   /**
    * Initialization of the servlet.

    *
    * @throws ServletException if an error occure
    */
   public void init() throws ServletException {
       // Put your code here
   }

}
     3:寫一個JSP頁面:
        Myjsp.jsp
   
<%@ page="" language="java" import="java.util.*" pageencoding="gb2312">
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



 
   "/>
   
   My JSP 'MyJsp.jsp' starting page
   
   
   
   
   
   
   
   <!--
   
   --&gt
 
 
 
 
   This is my JSP page.

   

   print input search id:
   
   

 

  4:其中有轉(zhuǎn)字,為了不顯示亂碼
   package com.test;

import java.io.*;
public class ASSICTOGBR2312 {
     public static String trans(String ass){
         String res=null;
         byte temp[];
         try{
             temp=ass.getBytes("iso-8859-1");
             res=new String(temp);
         }
         catch(UnsupportedEncodingException en) {
             System.out.println(en.toString());
         }
         
       
         
         return res;
   
     }
}


  5:web.xml

 
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 
   This is the description of my J2EE component
   This is the display name of my J2EE component
   Mytest
   com.test.Mytest
 


 
   Mytest
   /servlet/Mytest
 




  6: 其中數(shù)據(jù)庫結(jié)構(gòu)如下:
     數(shù)據(jù)庫名:hptest
     表:userinf
     用下面的命令建一個數(shù)據(jù)庫和表
     create database hptest;
     create table  userinf (
      userid int(4) not null,
      name char(10) not null,
      address varchar(50),
      year date,
      constraint fk_userinf primary key(userid));
      )
      insert into userinf values(19,'hp','cq','1982-10-22');

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“Tomcat中數(shù)據(jù)庫連接池如何設(shè)置與應(yīng)用”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI