以往要設(shè)置數(shù)據(jù)庫(kù)連接池,需要借助于第三方軟件。但現(xiàn)在NetBeans所帶的Tomcat 5.5.7及Sun Application Server 8均可以直接設(shè)置。下面談?wù)勅绾卧赥omcat 5.5.7下設(shè)置。
1. 下載數(shù)據(jù)庫(kù)的專用連接驅(qū)動(dòng),并將其復(fù)制到C:Program Filesetbeans-4.1entERPrise1jakarta-tomcat-5.5.7commonlib文件夾下面。
假設(shè)所用數(shù)據(jù)庫(kù)是Sybase的Adaptive Server Anywhere,從Sybase官方站點(diǎn)下載JConnect-6_0,從中抽取出jconn3這個(gè)驅(qū)動(dòng),復(fù)制到上述文件夾下。
2. 啟動(dòng)Tomcat,在IE輸入http://localhost:8084/admin/,以管理員身份登錄管理。用戶登錄的方法可參考第5樓。點(diǎn)擊Resources下的Data Sources,在右邊Data Source Actions的下拉框中選Create New Data Source,按下表示范填寫(xiě):
JNDI Name: sybase/poolDB /* 根據(jù)喜好填 */
Data Source URL: JDBC:sybase:Tds:<localhost>:<端口號(hào)>
/* 數(shù)據(jù)庫(kù)的地址,此為jconn3的形式,端口號(hào)需查詢確認(rèn),但一般都是固定的,除非自己更改 */
JDBC Driver Class: com.sybase.jdbc3.jdbc.SybDriver /* jconn3的驅(qū)動(dòng) */
User Name: dba /* 用戶名,默認(rèn)為dba */
Password: *** /* 密碼,默認(rèn)為sql */
Max. Active Connections: 4 /* 最大活動(dòng)連接數(shù) */
Max. Ide Connections: 2 /* 最大空閑連接數(shù) */
Max. Wait for Connecton: 5000 /* 等待連接的最大秒數(shù) */
Validation Query: /* 驗(yàn)證字符串,可不填 */
按"Save",再按"Commit Changes",Tomcat在后臺(tái)將此變化保存到server.XML文件中。"Commit Changes"是最容易忘記的,小心。
3. 以下均轉(zhuǎn)入NetBeans環(huán)境中設(shè)置。在context.xml修改的內(nèi)容:
<Context path="/Matrix">
<ResourceLink global="sybase/poolDB" name="sybase/poolDB" type="Javax.sql.DataSource"/>
</Context>
"/Matrix"為此Web應(yīng)用的根地址,表現(xiàn)為http://localhost:8084/Matrix。
4. 在web.xml中加入:
<resource-ref>
<description>Sybase Database Connection Pool</description>
<res-ref-name>sybase/poolDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
5. 好了,可以使用連接池了。以下代碼為在JSP文件中使用JSTL標(biāo)簽庫(kù)的范例。
<sql:query var="queryresults" dataSource="sybase/poolDB">
SELECT * FROM customer
</sql:query>
以前習(xí)慣了用jbuilder和eclipse,也習(xí)慣了它們的那種方便的配置資源的方式。前不久看到網(wǎng)上的一片文章說(shuō)的是NetBeans的新的功能和它的許多優(yōu)于其它java集成開(kāi)發(fā)環(huán)境的特性,強(qiáng)烈的好奇心驅(qū)使我下載并安裝了NetBeans。新建了一個(gè)web項(xiàng)目測(cè)試了一下,真的有許多過(guò)人之處。特別是它和頁(yè)面開(kāi)發(fā)工具Dreamweaver配合,用DW開(kāi)發(fā)頁(yè)面,NB開(kāi)發(fā)java程序,把兩者指向一個(gè)共同的目錄,修改過(guò)頁(yè)面后只需要刷新就可以在瀏覽器中直接看到效果了,幾乎不用配置什么東西。于是我現(xiàn)在的所有的項(xiàng)目都使用NB。至于其它的優(yōu)點(diǎn)就不多說(shuō)了,建議你下載并感受一下那種方便、快捷吧。
由于NB默認(rèn)的是使用內(nèi)置的tomcat作為web服務(wù)器,手頭的一個(gè)項(xiàng)目對(duì)數(shù)據(jù)庫(kù)的操作比較頻繁,考慮用數(shù)據(jù)庫(kù)連接池技術(shù)以減少程序的響應(yīng)時(shí)間。以前都是直接在tomcat的管理員頁(yè)面中配置數(shù)據(jù)庫(kù)連接池,方便而且不容易出錯(cuò)。準(zhǔn)備用同樣的方法在NB中配置一下,但配置的過(guò)程中發(fā)現(xiàn)有一些不同之處,現(xiàn)在終于配置成功,寫(xiě)出來(lái)供大家參考。下面開(kāi)始:
啟動(dòng)NetBeans5.5,新建一個(gè)web項(xiàng)目,名稱任意,新建成功后會(huì)有一個(gè)自動(dòng)的index.jsp頁(yè)面。然后編譯并運(yùn)行項(xiàng)目,這時(shí)候會(huì)在IDE的下方有一些相關(guān)的信息,這些信息也是我們發(fā)現(xiàn)錯(cuò)誤的有效途徑。運(yùn)行后會(huì)自動(dòng)打開(kāi)IE,并運(yùn)行類似如下路徑的jsp文件:http://localhost:8084/Try/,現(xiàn)在把路徑端口后面的項(xiàng)目名刪除,進(jìn)入Tomcat的默認(rèn)頁(yè)面http://localhost:8084/,點(diǎn)擊該頁(yè)面左邊的Tomcat Administration鏈接進(jìn)入管理員的登錄頁(yè)面。由于Tomcat的安裝是包含在NB中的,我們并沒(méi)有對(duì)Tomcat的賬戶進(jìn)行配置,所以登錄請(qǐng)要先配置Tomcat的tomcat-users.xml文件,它所在文件夾的相對(duì)路徑是:netbeans-5.5\enterprise3\apache-tomcat-5.5.17\conf。把該文件修改如下:
<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
<role rolename="tomcat"/>
<role rolename="admin"/>//新建
<role rolename="role1"/>
<user username="both" password="tomcat" roles="tomcat,role1"/>
<user username="tomcat" password="tomcat" roles="tomcat"/>
<user username="admin" password="123123" roles="admin"/>//新建
<user username="role1" password="tomcat" roles="role1"/>
</tomcat-users>
修改后就可以用admin的用戶名,123123的密碼登錄了。登陸后展開(kāi)Resources目錄,選擇Data Sources,單擊右邊Data Sourec Actions下拉菜單,選擇Create New Date Sourec.分別填寫(xiě)其中的屬性的值。JNDI Name是連接池的名字,在java程序中要用到;Data Source URL是數(shù)據(jù)庫(kù)連接字串,格式為jdbc:mysql://localhost/(數(shù)據(jù)庫(kù)名);JDBC Driver Class是你要使用的JDBC連接類。User Name、Password是數(shù)據(jù)庫(kù)的用戶名和密碼;下面的三個(gè)分別是數(shù)據(jù)庫(kù)最大連接數(shù)、數(shù)據(jù)庫(kù)最大空閑連接數(shù)、數(shù)據(jù)庫(kù)最大等待連接限制。最后一個(gè)是驗(yàn)證連接用的查詢語(yǔ)句,可以不填。設(shè)定好后保存,并單擊上面的Commit Changes提交。
修改C:\Documents and Settings\你的用戶名
\.netbeans\5.5\apache-tomcat-5.5.17_base\conf\Catalina\localhost文件夾下的和你的項(xiàng)目同名的xml文件,修改后如下:
<?xml version="1.0" encoding="UTF-8"?>
<Context
docBase="D:/my_nb/Try/build/web">
<ResourceLink global="jdbc/myehow" name="jdbc/myehow" type=
"javax.sql.DataSource"/>//定義要使用的連接池
</Context>
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@page import="java.sql.*" %>
<%@page import="javax.sql.*" %>
<%@page import="javax.naming.*" %>
<%
Connection con=null;
Statement stm=null;
ResultSet rs=null;
try{
InitialContext ctx=new InitialContext();
DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbc/myehow");
con=ds.getConnection();
stm=con.createStatement();
rs=stm.executeQuery("select * from ehow");
while(rs.next()){
String name=rs.getString(2);
out.println(name);
out.print("<br>");
}
現(xiàn)在就可以在項(xiàng)目中使用這個(gè)連接池了,下面給出一個(gè)僅供參考的數(shù)據(jù)庫(kù)連接池的測(cè)試文件,如果要在項(xiàng)目中用的話應(yīng)該寫(xiě)在一個(gè)bean中,數(shù)據(jù)庫(kù)的內(nèi)容在下面給出。測(cè)試文件如下:
}catch(Exception e){
out.print(e.getMessage());
e.printStackTrace();
}finally{
if(rs!=null){
try{
rs.close();
}catch(SQLException e){
}
}
if(stm!=null){
try{
stm.close();
}catch(SQLException e){
}
}
if(con!=null){
try{
con.close();
}catch(SQLException e){
}
}
}
%>
數(shù)據(jù)庫(kù)中只有一個(gè)表,表中有兩個(gè)字段,其中id是主鍵,int型。Name,字符型長(zhǎng)度30。
好了,現(xiàn)在運(yùn)行項(xiàng)目,就可以看到數(shù)據(jù)庫(kù)中的信息了。
項(xiàng)目的部署:項(xiàng)目開(kāi)發(fā)完成當(dāng)然要部署到服務(wù)器上,由于NB已經(jīng)為我們完成了大量的工作,只需要把數(shù)據(jù)庫(kù)備份,把NB的dist文件夾下的項(xiàng)目名.war文件拷貝到服務(wù)器上,在服務(wù)器的Tomcat的server.xml文件任意指定一個(gè)虛擬目錄就可以了(不要忘了先配置連接池。,數(shù)據(jù)庫(kù)還原后,就一切OK了。
在NB運(yùn)行時(shí)使用的tomcat-users.xml并不是程序目錄下的那個(gè)文件,而是在C盤下的某個(gè)目錄下,具體名字不記得了,自己搜索就是了
把mysql驅(qū)動(dòng)包分別放到%TOMCAT_HOME%/lib 和你的應(yīng)用的WEB-INF\lib文件夾下面
1、修改%TOMCAT_HOME%/conf/server.xml,添加如下內(nèi)容(部分參數(shù)請(qǐng)本地化):
<Context path="/web" docBase="web" debug="0" reloadable="true" crossContext="true">
<Resource name="jdbc/query" auth="Container" type="javax.sql.DataSource" driverClassName="org.gjt.mm.mysql.Driver"
maxIdle="20" maxWait="5000" username="username" password="password" url="jdbc:mysql://localhost:3306/DataBaseName"
maxActive="100" removeAbandoned="true" removeAbandonedTimeout="60" logAbandoned="true"/>
</Context>
2、修改對(duì)應(yīng)應(yīng)用的web.xml,在</web-app>前添加如下內(nèi)容:
<ResourceLink name="jdbc/query" global="jdbc/query" type="javax.sql.DataSourcer"/>
重啟tomcat,大功搞成!
應(yīng)用實(shí)例如下:
<%@ page contentType="text/html; charset=gb2312" %>
<%@ page import="javax.naming.Context" %>
<%@ page import="javax.sql.DataSource"%>
<%@ page import="javax.naming.InitialContext"%>
<%@ page import="java.sql.*"%>
<html>
<body>
123
<%
DataSource ds = null;
try{
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
//從Context中l(wèi)ookup數(shù)據(jù)源。
ds = (DataSource)envCtx.lookup("jdbc/query");
if(ds!=null)
{
out.println("已經(jīng)獲得DataSource!");
out.println("<br>");
Connection conn = ds.getConnection();
Statement stmt=conn.createStatement();
ResultSet rst=stmt.executeQuery("select * from cs_order");//從一個(gè)已存在的表中讀取數(shù)據(jù)
out.println("以下是從數(shù)據(jù)庫(kù)中讀取出來(lái)的數(shù)據(jù):<br>");
while(rst.next()){
out.println("<br>");
out.println(rst.getString(8));}
}
}
catch(Exception ne)
{
out.println("出現(xiàn)如下錯(cuò)誤:<br>");
out.println(ne);
}
%>
</body>
</html>
-------------------------------------------------------------------------------------------
參考:
1.MySQL數(shù)據(jù)庫(kù)版本:mysql-5.0.27
2.TomCat版本:6.0
3.數(shù)據(jù)庫(kù)驅(qū)動(dòng)程序:mysql-connector-java-XXX
4.Server.xml文件內(nèi)容:
<!-- Note: A "Server" is not itself a "Container", so you may not
define subcomponents such as "Valves" at this level.
Documentation at /docs/config/server.html
-->
<Server port="8005" shutdown="SHUTDOWN">
<!--APR library loader. Documentation at /docs/apr.html -->
<Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
<!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
<Listener className="org.apache.catalina.core.JasperListener" />
<!-- JMX Support for the Tomcat server. Documentation at /docs/non-existent.html -->
<Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
<!-- Global JNDI resources
Documentation at /docs/jndi-resources-howto.html
-->
<GlobalNamingResources>
<!-- Editable user database that can also be used by
UserDatabaseRealm to authenticate users
-->
<Resource name="UserDatabase" auth="Container"
type="org.apache.catalina.UserDatabase"
description="User database that can be updated and saved"
factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
pathname="conf/tomcat-users.xml" />
</GlobalNamingResources>
<!-- A "Service" is a collection of one or more "Connectors" that share
a single "Container" Note: A "Service" is not itself a "Container",
so you may not define subcomponents such as "Valves" at this level.
Documentation at /docs/config/service.html
-->
<Service name="Catalina">
<!-- A "Connector" represents an endpoint by which requests are received
and responses are returned. Documentation at :
Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
Java AJP Connector: /docs/config/ajp.html
APR (HTTP/AJP) Connector: /docs/apr.html
Define a non-SSL HTTP/1.1 Connector on port 8080
-->
<Connector port="8080" protocol="HTTP/1.1"
maxThreads="150" connectionTimeout="20000"
redirectPort="8443" />
<!-- Define a SSL HTTP/1.1 Connector on port 8443
This connector uses the JSSE configuration, when using APR, the
connector should be using the OpenSSL style configuration
described in the APR documentation -->
<!--
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS" />
-->
<!-- Define an AJP 1.3 Connector on port 8009 -->
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
<!-- An Engine represents the entry point (within Catalina) that processes
every request. The Engine implementation for Tomcat stand alone
analyzes the HTTP headers included with the request, and passes them
on to the appropriate Host (virtual host).
Documentation at /docs/config/engine.html -->
<!-- You should set jvmRoute to support load-balancing via AJP ie :
<Engine name="Standalone" defaultHost="localhost" jvmRoute="jvm1">
-->
<Engine name="Catalina" defaultHost="localhost">
<!--For clustering, please take a look at documentation at:
/docs/cluster-howto.html (simple how to)
/docs/config/cluster.html (reference documentation) -->
<!--
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
-->
<!-- The request dumper valve dumps useful debugging information about
the request and response data received and sent by Tomcat.
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.valves.RequestDumperValve"/>
-->
<!-- This Realm uses the UserDatabase configured in the global JNDI
resources under the key "UserDatabase". Any edits
that are performed against this UserDatabase are immediately
available for use by the Realm. -->
<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
resourceName="UserDatabase"/>
<!-- Define the default virtual host
Note: XML Schema validation will not work with Xerces 2.2.
-->
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true"
xmlValidation="false" xmlNamespaceAware="false">
<!-- SingleSignOn valve, share authentication between web applications
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.authenticator.SingleSignOn" />
-->
<!-- Access log processes all example.
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.valves.FastCommonAccessLogValve" directory="logs"
prefix="localhost_access_log." suffix=".txt" pattern="common" resolveHosts="false"/>
-->
<!-- JNDI Setting -->
<Context path="/MingPian" docBase="MingPian"
debug="5" reloadable="true" crossContext="true">
<!-- maxActive: Maximum number of dB connections in pool. Make sure you
configure your mysqld max_connections large enough to handle
all of your db connections. Set to 0 for no limit.
-->
<!-- maxIdle: Maximum number of idle dB connections to retain in pool.
Set to -1 for no limit. See also the DBCP documentation on this
and the minEvictableIdleTimeMillis configuration parameter.
-->
<!-- maxWait: Maximum time to wait for a dB connection to become available
in ms, in this example 10 seconds. An Exception is thrown if
this timeout is exceeded. Set to -1 to wait indefinitely.
-->
<!-- username and password: MySQL dB username and password for dB connections -->
<!-- driverClassName: Class name for the old mm.mysql JDBC driver is
org.gjt.mm.mysql.Driver - we recommend using Connector/J though.
Class name for the official MySQL Connector/J driver is com.mysql.jdbc.Driver.
-->
<!-- url: The JDBC connection url for connecting to your MySQL dB.
The autoReconnect=true argument to the url makes sure that the
mm.mysql JDBC Driver will automatically reconnect if mysqld closed the
connection. mysqld by default closes idle connections after 8 hours.
-->
<Resource name="jdbc/TestDB" 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/dbname?autoReconnect=true"/>
</Context>
</Host>
</Engine>
</Service>
</Server>
5:程序目錄下web.xml文件內(nèi)容:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
<description>MySQL Test App</description>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
6:程序目錄為:MingPian,這個(gè)文件夾的名字是和Server.xml中的<Context path="/MingPian" docBase="MingPian"
debug="5" reloadable="true" crossContext="true">目錄對(duì)應(yīng)的,否則連接不上.
如果程序的目錄為空,則這里的<Context path "/" docBase-"" debug="5" reloadable="true" crossContext="true">
我的電腦上Context.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<Context crossContext="true" debug="0" docBase="web" path="/DataWeb" reloadable="true">
<Resource auth="Container" driverClassName="org.gjt.mm.mysql.Driver" logAbandoned="true" maxActive="2" maxIdle="4" maxWait="5000" name="mysql/poolDB" password="123456" removeAbandoned="true" removeAbandonedTimeout="60" type="javax.sql.DataSource" url="jdbc:mysql://localhost:3306/sample" username="root"/>
</Context>
Web.xml文件
<resource-ref>
<description>jdbc:mysql://localhost:3306/sample [root on Default schema]</description>
<res-ref-name>mysql/poolDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
NetBeans IDE V6.9 官方簡(jiǎn)體中文版:http://innovatechautomation.com/soft/10288.html