tomcatでのデータベース接続とプロジェクト導入の構成

4192 ワード

ステップ3:1、tomcatディレクトリの下のconfフォルダの中のserver.xml配置プロジェクト2、tomcatディレクトリ下confフォルダ内のcontext.xmlは、データベース接続3、プロジェクト内書き込み呼び出しcontextを設定する.xmlのクラス
server.xml
<Context path="/   " docBase="    " reloadable="true">
Context>

context.xml
"jdbc/   "
    auth="Container"
    type ="javax.sql.DataSource"
    driverClassName = "com.mysql.jdbc.Driver"
    url = "jdbc:mysql://localhost:3306/xxxxx"
    username = "dbuser"
    password = "dbpassword"
/>

DbBean.JAva(mysqlの接続jarパッケージをプロジェクトにインポート)
import java.sql.*;
import javax.sql.*;

public class DbBean {

    private Connection dbCon;

    String dbURL = "jdbc:mysql://localhost:3306/xxxxx";
    String dbDriver = "com.mysql.jdbc.Driver" ;
    String dbUser = "dbuser";
    String dbPassword = "dbpassword";

    public DbBean() {
        super();
    }

    public boolean connect() throws ClassNotFoundException, SQLException {

        try{
            Context initCtx = new InitialContext();
            if(initCtx == null ){
                throw new Exception("No Context");
            }
            Context ctx = (Context) initCtx.lookup("java:comp/env");
            DataSource ds = (DataSource)ctx.lookup("jdbc/   ");  //     context.xml     
            if(ds != null){
                dbCon = ds.getConnection();
                dbCon.setAutoCommit(false);
                return true;
            }else{
                return false;
            }  
        }catch(javax.naming.NoInitialContextException e){   //     tomcat    context.xml   
            Class.forName(this.getDbDriver());
            dbCon = DriverManager.getConnection(this.getDbURL() , dbUser ,dbPassword);
            dbCon.setAutoCommit(false);
            return true;
        }catch(Exception e){
            return false;
        }

    }

}

あとはDbBeanに自分のコードを入れて