以往要设置数据库连接池,需要借助于第三方软件。但现在NetBeans所带的Tomcat 5.5.7及Sun Application Server 8均可以直接设置。下面谈谈如何在Tomcat 5.5.7下设置。
1. 下载数据库的专用连接驱动,并将其复制到C:Program Filesetbeans-4.1entERPrise1jakarta-tomcat-5.5.7commonlib文件夹下面。
假设所用数据库是Sybase的Adaptive Server Anywhere,从Sybase官方站点下载JConnect-6_0,从中抽取出jconn3这个驱动,复制到上述文件夹下。
2. 启动Tomcat,在IE输入http://localhost:8084/admin/,以管理员身份登录管理。用户登录的方法可参考第5楼。点击Resources下的Data Sources,在右边Data Source Actions的下拉框中选Create New Data Source,按下表示范填写:
JNDI Name: sybase/poolDB /* 根据喜好填 */
Data Source URL: JDBC:sybase:Tds:<localhost>:<端口号>
/* 数据库的地址,此为jconn3的形式,端口号需查询确认,但一般都是固定的,除非自己更改 */
JDBC Driver Class: com.sybase.jdbc3.jdbc.SybDriver /* jconn3的驱动 */
User Name: dba /* 用户名,默认为dba */
Password: *** /* 密码,默认为sql */
Max. Active Connections: 4 /* 最大活动连接数 */
Max. Ide Connections: 2 /* 最大空闲连接数 */
Max. Wait for Connecton: 5000 /* 等待连接的最大秒数 */
Validation Query: /* 验证字符串,可不填 */
按"Save",再按"Commit Changes",Tomcat在后台将此变化保存到server.XML文件中。"Commit Changes"是最容易忘记的,小心。
3. 以下均转入NetBeans环境中设置。在context.xml修改的内容:
<Context path="/Matrix">
<ResourceLink global="sybase/poolDB" name="sybase/poolDB" type="Javax.sql.DataSource"/>
</Context>
"/Matrix"为此Web应用的根地址,表现为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标签库的范例。
<sql:query var="queryresults" dataSource="sybase/poolDB">
SELECT * FROM customer
</sql:query>
以前习惯了用jbuilder和eclipse,也习惯了它们的那种方便的配置资源的方式。前不久看到网上的一片文章说的是NetBeans的新的功能和它的许多优于其它java集成开发环境的特性,强烈的好奇心驱使我下载并安装了NetBeans。新建了一个web项目测试了一下,真的有许多过人之处。特别是它和页面开发工具Dreamweaver配合,用DW开发页面,NB开发java程序,把两者指向一个共同的目录,修改过页面后只需要刷新就可以在浏览器中直接看到效果了,几乎不用配置什么东西。于是我现在的所有的项目都使用NB。至于其它的优点就不多说了,建议你下载并感受一下那种方便、快捷吧。
由于NB默认的是使用内置的tomcat作为web服务器,手头的一个项目对数据库的操作比较频繁,考虑用数据库连接池技术以减少程序的响应时间。以前都是直接在tomcat的管理员页面中配置数据库连接池,方便而且不容易出错。准备用同样的方法在NB中配置一下,但配置的过程中发现有一些不同之处,现在终于配置成功,写出来供大家参考。下面开始:
启动NetBeans5.5,新建一个web项目,名称任意,新建成功后会有一个自动的index.jsp页面。然后编译并运行项目,这时候会在IDE的下方有一些相关的信息,这些信息也是我们发现错误的有效途径。运行后会自动打开IE,并运行类似如下路径的jsp文件:http://localhost:8084/Try/,现在把路径端口后面的项目名删除,进入Tomcat的默认页面http://localhost:8084/,点击该页面左边的Tomcat Administration链接进入管理员的登录页面。由于Tomcat的安装是包含在NB中的,我们并没有对Tomcat的账户进行配置,所以登录请要先配置Tomcat的tomcat-users.xml文件,它所在文件夹的相对路径是: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的密码登录了。登陆后展开Resources目录,选择Data Sources,单击右边Data Sourec Actions下拉菜单,选择Create New Date Sourec.分别填写其中的属性的值。JNDI Name是连接池的名字,在java程序中要用到;Data Source URL是数据库连接字串,格式为jdbc:mysql://localhost/(数据库名);JDBC Driver Class是你要使用的JDBC连接类。User Name、Password是数据库的用户名和密码;下面的三个分别是数据库最大连接数、数据库最大空闲连接数、数据库最大等待连接限制。最后一个是验证连接用的查询语句,可以不填。设定好后保存,并单击上面的Commit Changes提交。
修改C:\Documents and Settings\你的用户名
\.netbeans\5.5\apache-tomcat-5.5.17_base\conf\Catalina\localhost文件夹下的和你的项目同名的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>");
}
现在就可以在项目中使用这个连接池了,下面给出一个仅供参考的数据库连接池的测试文件,如果要在项目中用的话应该写在一个bean中,数据库的内容在下面给出。测试文件如下:
}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){
}
}
}
%>
数据库中只有一个表,表中有两个字段,其中id是主键,int型。Name,字符型长度30。
好了,现在运行项目,就可以看到数据库中的信息了。
项目的部署:项目开发完成当然要部署到服务器上,由于NB已经为我们完成了大量的工作,只需要把数据库备份,把NB的dist文件夹下的项目名.war文件拷贝到服务器上,在服务器的Tomcat的server.xml文件任意指定一个虚拟目录就可以了(不要忘了先配置连接池!),数据库还原后,就一切OK了。
在NB运行时使用的tomcat-users.xml并不是程序目录下的那个文件,而是在C盘下的某个目录下,具体名字不记得了,自己搜索就是了
把mysql驱动包分别放到%TOMCAT_HOME%/lib 和你的应用的WEB-INF\lib文件夹下面
1、修改%TOMCAT_HOME%/conf/server.xml,添加如下内容(部分参数请本地化):
<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、修改对应应用的web.xml,在</web-app>前添加如下内容:
<ResourceLink name="jdbc/query" global="jdbc/query" type="javax.sql.DataSourcer"/>
重启tomcat,大功搞成!
应用实例如下:
<%@ 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中lookup数据源。
ds = (DataSource)envCtx.lookup("jdbc/query");
if(ds!=null)
{
out.println("已经获得DataSource!");
out.println("<br>");
Connection conn = ds.getConnection();
Statement stmt=conn.createStatement();
ResultSet rst=stmt.executeQuery("select * from cs_order");//从一个已存在的表中读取数据
out.println("以下是从数据库中读取出来的数据:<br>");
while(rst.next()){
out.println("<br>");
out.println(rst.getString(8));}
}
}
catch(Exception ne)
{
out.println("出现如下错误:<br>");
out.println(ne);
}
%>
</body>
</html>
-------------------------------------------------------------------------------------------
参考:
1.MySQL数据库版本:mysql-5.0.27
2.TomCat版本:6.0
3.数据库驱动程序:mysql-connector-java-XXX
4.Server.xml文件内容:
<!-- 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文件内容:
<?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,这个文件夹的名字是和Server.xml中的<Context path="/MingPian" docBase="MingPian"
debug="5" reloadable="true" crossContext="true">目录对应的,否则连接不上.
如果程序的目录为空,则这里的<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 官方简体中文版:http://www.cr173.com/soft/10288.html