tomcat connection pool(mysql)

1.簡介

org.apache.tomcat.jdbc.pool是tomcat jdbc connection pool,是多線程connection pool,是另一種選擇。而且支持java.sql和javax.sql接口,同時支持initSQL屬性。

2.支持的jdbc版本:mysql3.23.47、3.23.58、4.0.1alpha、connector/j3.0.11、mm.mysql2.0.14

3.代碼實現

A.copy jdbc driver into $TOMCAT_HOME/lib

B.配置Context

    <Resource name="jdbc/mysql" auth="Container" type="javax.sql.DataSource"
               maxTotal="100" maxIdle="30" maxWaitMillis="10000"
               username="root" password="root" driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://localhost:3306/test"/>

C.配置web.xml

  <resource-ref>
      <description>MySQL DB Connection</description>
      <res-ref-name>jdbc/mysql</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
  </resource-ref>

D.servlet代碼

 public void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException,IOException
    {
      
        resp.setContentType("text/html;charset=gb2312");
      
        String name=req.getParameter("username");
        String pwd=req.getParameter("password");
       DbUtil db=new DbUtil();
       String pwd1=db.getPass(name);
        if(pwd.equals(pwd1))
        {
            resp.sendRedirect("success.html");
        }
        else
        {
            resp.sendRedirect("fail.html");
//            resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,"服務器忙,請稍後再登錄!");
        }
      
    }

E.數據庫數據讀取代碼

package com.edu.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

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

public class DbUtil {

 public String getPass(String uname){
  String rtn=null;
  
  Context ctx=null;
   DataSource ds=null;
   Connection conn=null;
   Statement stmt=null;
   ResultSet rs=null;
   try{
    ctx = new InitialContext();
    ds = (DataSource) ctx.lookup("java:comp/env/jdbc/mysql"); 
    conn = ds.getConnection();
    stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
    String strSql = " select * from weian where name='"+uname+"'";
    rs = stmt.executeQuery(strSql);
    while(rs.next()){ 
     rtn=rs.getString(“password”);
     break;
    }
   } catch(Exception ex) {
    ex.printStackTrace(); 
   }finally{
    try{
     if( rs != null )
     rs.close();
     if( stmt != null )
     stmt.close();
     if( conn != null)
     conn.close();
     if( ctx != null )
     ctx.close();
    }catch(Exception ee){}
   }
   return rtn;
 }
}
F.數據庫代碼

CREATE TABLE `weian` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `name` char(8) NOT NULL DEFAULT '',
  `password` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`Id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

G.數據庫數據

id name password

1 weian 1
5 user1 1234
6 user2i 234

4.總結

如果數據庫的weian表中,有所輸入的數據weian、1234,則登錄成功,反之失敗。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章