一、在tomcat conf目录下的context.xml文件里的Context标签下添加如下配置
<Resource name="jdbc/news" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000" username="root"
password="123456" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/newsmanagersystem?
useUnicode=true&amp;characterEncoding=utf-8"/>
二、
在当前项目的web.xml文件里配置如下信息
 <!--jndi数据库配置  -->
  <resource-ref>
    <description>news DataSource</description>
    <res-ref-name>jdbc/news</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>
三、

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
//获得数据库连接
    public static Connection getConnection(){
        Connection conn=null;
        try {
            Context context=new InitialContext();
            DataSource ds = (DataSource)context.lookup("java:comp/env/jdbc/news");
            conn=ds.getConnection();
            return conn;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return conn;
    }

 

 

 

posted on 2018-01-12 17:26  想把愿望写在里面  阅读(264)  评论(2编辑  收藏  举报