Tomcat6.0中配置資料來源

來源:互聯網
上載者:User
Tomcat6.0中配置資料來源
 

利用資料來源完成資料連線.可以提高程式訪問速度,在前面講Struts時,曾講過資料來源在Struts中的配置方法,今天配置的資料來源中在tomcat6.0中完成的,由於不同的Tomcat版本,資料來源的配置方式不同,所以在配置時參數Tomcat官方網站。

http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html

本例使用的是SQL Server2005做的案例:

具體步驟:

1. 把資料來源串連相關的JAR包複製到Tomcat的lib,( $CATALINA_HOME/lib/)。

sqljdbc.jar

tomcat-dbcp.jar (已包含在Tomcat中)

2. 在$CATALINA_HOME/conf中找到伺服器設定檔server.xml,建議大家在修改之前先備份一個,一旦改亂了,還可以複製回來!

3. 在server.xml中找到<Host>元素,在<Host>中添加上下文元素<Context>,注意EmployeeWeb是上下文名稱。

4. 在<Context>中添加<Resource>元素,其中name屬性為資料來源名稱,其他屬性自己分析。修改結束後儲存退出。
      <Host name="localhost" appBase="webapps"
            unpackWARs="true" autoDeploy="true"
            xmlValidation="false" xmlNamespaceAware="false">

     <Context path="/EmployeeWeb" docBase="EmployeeWeb"
        debug="5" reloadable="true" crossContext="true">

     <Resource name="jdbc/onlineShopDataSource" auth="Container" type="javax.sql.DataSource"
               maxActive="100" maxIdle="30" maxWait="10000"
               username="sa" password="123456"
               driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
               url="jdbc:sqlserver://localhost:1433;databaseName=onlineShop"/>

</Context>
      </Host>

5. 開啟項目EmployeeWeb,在web.xml中添加配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
    <servlet-name>DepartmentController</servlet-name>
    <servlet-class>cn.sunfengwei.employee.controller.DepartmentController</servlet-class>
</servlet>
<servlet>
    <servlet-name>EmployeeController</servlet-name>
    <servlet-class>cn.sunfengwei.employee.controller.EmployeeController</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>DepartmentController</servlet-name>
    <url-pattern>/department</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>EmployeeController</servlet-name>
    <url-pattern>/EmployeeController</url-pattern>
</servlet-mapping>
<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/onlineShopDataSource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>

6. 測試:

6.1 在jsp中測試,這裡為了省事,使用JSP的標準標記庫與運算式語言。

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<sql:query var="rs" dataSource="jdbc/onlineShopDataSource">
select id,name from department
</sql:query>

<html>
<head>
    <title>DB Test</title>
</head>
<body>

<h2>Results</h2>
<select name="departmentId">
<c:forEach var="row" items="${rs.rows}">
   
    <option value="${row.id}">${row.name}</option>
  
</c:forEach>
</select>
</body>
</html>

6.2 在JavaBean中完成資料來源串連,但有一點大家一定要注意,不能用戶端使用本地方式運行資料來源,因為我們是在Tomcat中配置的,只能在伺服器中運行。

package cn.sunfengwei.employee.database;
/**
* @author 孫豐偉 E-mail: sunfengweimail@163.com
* @version 建立時間:Jun 11, 2008 6:19:20 PM
* @see
*/
import java.sql.*;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class ConnectDB {
private static Connection conn=null;

//
// 使用本地串連
//
public static Connection getConnection()
{
  
   String url="jdbc:sqlserver://localhost:1433;databaseName=onlineShop";
   try {
    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    conn=DriverManager.getConnection(url,"sa","123456");
   } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   return conn;
  
}

//
// 使用資料來源串連
//

public static Connection getConnectionByDataSource() throws Exception
{
    
   InitialContext cxt;
   try {
    cxt = new InitialContext();
    if ( cxt == null ) {
       throw new Exception("Uh oh -- no context!");
     }

     DataSource ds = (DataSource) cxt.lookup( "java:/comp/env/jdbc/onlineShopDataSource" );
     conn=ds.getConnection();
     if ( ds == null ) {
       throw new Exception("Data source not found!");
     }
   } catch (NamingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   return conn;

}
}

7. 在Data Access ObjectsDAO中,與原來的內容相同,這裡不再重複。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.