tomcat上配置数据库连接和项目部署

分三步:
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里面加上自己要的代码

你可能感兴趣的:(配置笔记)