在Tomcat中配置資料來源

來源:互聯網
上載者:User

在Tomcat中配置資料來源
作者:yi5    轉貼自:yi5_yuyu    點擊數:26    文章錄入: yuyu3007

Datasource對象是由Tomcat提供的,因而需要使用JNDI來獲得Datasouce

在Javax.naming 中提供了Context介面,

資料來源的配置涉及到Server.xml和web.xml,需要在server.xml中加入如下內容:說明一下:我的資料庫是MYsql

<Context path="/text" docBase="d:/upload" debug="0">
     <Resource name="jdbc/testDb" auth="Container"
                    type="javax.sql.DataSource"/>
          <ResourceParams name="jdbc/testDB">//資料來源的名稱
            <parameter><name>username</name><value>root</value></parameter>資料庫的名稱
            <parameter><name>password</name><value>password</value></parameter>資料庫密碼
            <parameter><name>driverClassName</name>
              <value>org.gjt.mm.mysql.Driver</value></parameter>//要載入的驅動
            <parameter><name>url</name>
              <value>jdbc:mysql://172.20.0.73/rk?</value></parameter>//要串連的URL
          </ResourceParams>
         
   </Context>

具體還有一些詳細的選項例如:MaxActive等,參加Server.xml中說明

另外在Web.xml中加入如下內容:
<description>test connection</description>//描述
    <res-ref-name>jdbc/testDB</res-ref-name>//名稱與上對應
    <res-type>javax.sql.DataSource</res-type>//與上對應
    <res-auth>Container</res-auth>//與上一置
    </resource-ref>

配置以上內容後,只要在你的Jsp或Javabean 中按以下方式建立串連,就可以

Context ctx=new InitialContext();
  DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbc/testDB");
  conn = ds.getConnection();

以上代碼均測試成功,但是在Server.xml中設定資料庫的URL中我不能加入useUnicode=true&characterEncoding=GBK,所以從資料庫中取出來的漢字都是????

我用如下代碼來解決這個問題:

public static String toChinese(String strvalue) {
  try{
   if(strvalue==null)
  {
  return null;
  }
  else {
   strvalue = new String(strvalue.getBytes("ISO8859_1"), "GBK");
   return strvalue;
  }
  }catch(Exception e){
   return null;
  }
 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.