[100分]关于配置tomcat+mysql的jdbc连接池问题,给回复正确者200分,先挂100,给有重要提示作用者50分每人。

yangbc 2004-12-27 07:39:29
已经2天了,看了不下1000份资料,还是没解决,只好高价收购一个了.

我的是 tomcat5+mysql4 , 想配置一个jdbc数据库连接池,要求是能连接mysql的默认数据库mysql的user表中的host,user,password这3个子段即可,哪位能按照我说的环境配置成功一个,只要把server.xml和相关的几个xml文件发给我或者贴到这里,解决后即可结贴。

声明一下,不要自己没有经验乱转贴,我想我看的帖子已经够多了。
...全文
199 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
yangbc 2004-12-28
  • 打赏
  • 举报
回复
问题好像已经解决,请jFresH_MaN()(AbsolutelyFresh)(java欣人), j2nix(爱生活爱星辉)关注我的送分贴,这里的100分就先给 j2nix(爱生活爱星辉)吧,我只能开100分贴,看来只好再开3个贴了。
phptong 2004-12-28
  • 打赏
  • 举报
回复


faq.java:
/* jsp与数据库连接:把他放在网站\WEB-INF\classes\china\db 下编译,在叶面中加入
<jsp:useBean id="mdb" class="china.db.faq" scope="page"/>
这行代码,即可。
*/
// Home Page : http://members.fortunecity.com/neshkov/dj.html - Check often for new version!
// Decompiler options: packimports(3)
// Source File Name: faq.java

package china.db;

import java.io.PrintStream;
import java.sql.*;
public class faq
{
String sDBDriver;
String sConnStr;
ResultSet rs;
Statement statement;
Connection conn;
public faq()
{
sDBDriver = "org.gjt.mm.mysql.Driver";
sConnStr = "jdbc:mysql://localhost/abc?user=root&password=&useUnicode=true&characterEncoding=GB2312";//数据库名为abc
conn = null;
rs = null;
try
{
Class.forName(sDBDriver);
try{
conn = DriverManager.getConnection(sConnStr);
} catch(SQLException sqlexception){}
} catch(ClassNotFoundException classnotfoundexception)
{
System.err.println("faq(): " + classnotfoundexception.getMessage());
}
}

public void executeInsert(String s)
{
try
{
statement= conn.createStatement();
int i = statement.executeUpdate(s);
}
catch(SQLException sqlexception)
{
System.err.println("faq.executeUpdate:" + sqlexception.getMessage());
}
}

public ResultSet executeQuery(String s)
{
rs = null;
try
{
statement = conn.createStatement(1004, 1008);
rs = statement.executeQuery(s);
}
catch(SQLException sqlexception)
{
System.err.println("aq.executeQuery: " + sqlexception.getMessage());
}
return rs;
}

public void executeDelete(String s)
{
try
{
statement = conn.createStatement();
statement.executeUpdate(s);
}
catch(SQLException sqlexception)
{
System.err.println("faq.executeDelete: " + sqlexception.getMessage());
}
}

public int executeUpdate(String s)
{
int i = 0;
try
{
statement = conn.createStatement();
i = statement.executeUpdate(s);
}
catch(SQLException sqlexception)
{
System.err.println("faq.executeDelete: " + sqlexception.getMessage());
}
return i;
}

public void Close()
{
try
{
if(rs!=null)
rs.close();
// if(
// statement.close();
if(conn!=null)
conn.close();
}
catch(SQLException sqlexception)
{
System.err.println("faq.executeDelete: " + sqlexception.getMessage());
}
}


}
phptong 2004-12-28
  • 打赏
  • 举报
回复
我这里有两个文件都给你吧,一个是server.xml另一个是jsp与mysql数据库连接的程序(beans的原文件)
Server :(为Tomcat 5)

<Server port="8005" shutdown="SHUTDOWN" debug="0">


<Listener className="org.apache.catalina.mbeans.ServerLifecycleListener"
debug="0"/>
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"
debug="0"/>

<!-- Global JNDI resources -->
<GlobalNamingResources>

<Resource name="UserDatabase" auth="Container"
type="org.apache.catalina.UserDatabase"
description="User database that can be updated and saved">
</Resource>
<ResourceParams name="UserDatabase">
<parameter>
<name>factory</name>
<value>org.apache.catalina.users.MemoryUserDatabaseFactory</value>
</parameter>
<parameter>
<name>pathname</name>
<value>conf/tomcat-users.xml</value>
</parameter>
</ResourceParams>

</GlobalNamingResources>

<!-- A "Service" is a collection of one or more "Connectors" that share
a single "Container" (and therefore the web applications visible
within that Container). Normally, that Container is an "Engine",
but this is not required.

Note: A "Service" is not itself a "Container", so you may not
define subcomponents such as "Valves" or "Loggers" at this level.
-->

<!-- Define the Tomcat Stand-Alone Service -->
<Service name="Catalina">


<!-- Define a non-SSL Coyote HTTP/1.1 Connector on port 8080 -->
<Connector port="87"
maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
debug="0" connectionTimeout="20000"
disableUploadTimeout="true" />
<Logger className="org.apache.catalina.logger.FileLogger"
prefix="catalina_log." suffix=".txt"
timestamp="true"/>

<!-- Because this Realm is here, an instance will be shared globally -->

<!-- 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"
debug="0" resourceName="UserDatabase"/>



<!--
When configuring for clustering, you also add in a valve to catch all the requests
coming in, at the end of the request, the session may or may not be replicated.
A session is replicated if and only if all the conditions are met:
1. useDirtyFlag is true or setAttribute or removeAttribute has been called AND
2. a session exists (has been created)
3. the request is not trapped by the "filter" attribute

The filter attribute is to filter out requests that could not modify the session,
hence we don't replicate the session after the end of this request.
The filter is negative, ie, anything you put in the filter, you mean to filter out,
ie, no replication will be done on requests that match one of the filters.
The filter attribute is delimited by ;, so you can't escape out ; even if you wanted to.

filter=".*\.gif;.*\.js;" means that we will not replicate the session after requests with the URI
ending with .gif and .js are intercepted.

The deployer element can be used to deploy apps cluster wide.
Currently the deployment only deploys/undeploys to working members in the cluster
so no WARs are copied upons startup of a broken node.
The deployer watches a directory (watchDir) for WAR files when watchEnabled="true"
When a new war file is added the war gets deployed to the local instance,
and then deployed to the other instances in the cluster.
When a war file is deleted from the watchDir the war is undeployed locally
and cluster wide
-->

<!--
<Cluster className="org.apache.catalina.cluster.tcp.SimpleTcpCluster"
managerClassName="org.apache.catalina.cluster.session.DeltaManager"
expireSessionsOnShutdown="false"
useDirtyFlag="true">

<Membership
className="org.apache.catalina.cluster.mcast.McastService"
mcastAddr="228.0.0.4"
mcastPort="45564"
mcastFrequency="500"
mcastDropTime="3000"/>

<Receiver
className="org.apache.catalina.cluster.tcp.ReplicationListener"
tcpListenAddress="auto"
tcpListenPort="4001"
tcpSelectorTimeout="100"
tcpThreadCount="6"/>

<Sender
className="org.apache.catalina.cluster.tcp.ReplicationTransmitter"
replicationMode="pooled"/>

<Valve className="org.apache.catalina.cluster.tcp.ReplicationValve"
filter=".*\.gif;.*\.js;.*\.jpg;.*\.htm;.*\.html;.*\.txt;"/>

<Deployer className="org.apache.catalina.cluster.deploy.FarmWarDeployer"
tempDir="/tmp/war-temp/"
deployDir="/tmp/war-deploy/"
watchDir="/tmp/war-listen/"
watchEnabled="false"/>
</Cluster>
-->



<!-- Normally, users must authenticate themselves to each web app
individually. Uncomment the following entry if you would like
a user to be authenticated the first time they encounter a
resource protected by a security constraint, and then have that
user identity maintained across *all* web applications contained
in this virtual host. -->
<!--
<Valve className="org.apache.catalina.authenticator.SingleSignOn"
debug="0"/>
-->

<!-- Access log processes all requests for this virtual host. By
default, log files are created in the "logs" directory relative to
$CATALINA_HOME. If you wish, you can specify a different
directory with the "directory" attribute. Specify either a relative
(to $CATALINA_HOME) or absolute path to the desired directory.
-->
<!--
<Valve className="org.apache.catalina.valves.AccessLogValve"
directory="logs" prefix="localhost_access_log." suffix=".txt"
pattern="common" resolveHosts="false"/>
-->

<!-- Logger shared by all Contexts related to this virtual host. By
default (when using FileLogger), log files are created in the "logs"
directory relative to $CATALINA_HOME. If you wish, you can specify
a different directory with the "directory" attribute. Specify either a
relative (to $CATALINA_HOME) or absolute path to the desired
directory.-->
<Logger className="org.apache.catalina.logger.FileLogger"
directory="logs" prefix="localhost_log." suffix=".txt"
timestamp="true"/>

</Host>

</Engine>

</Service>

</Server>


j2nix 2004-12-28
  • 打赏
  • 举报
回复
就是Tomcat有三种域(Realm)验证方式:内存域、JDBC域、DataSource域。
也就是三种查找用户名和口令的三种途径。
cly33 2004-12-27
  • 打赏
  • 举报
回复
g
jFresH_MaN 2004-12-27
  • 打赏
  • 举报
回复
<Context>放在<service>里面的<Engine>里面的<Host>标记里面
我试过的,不会又问题
yangbc 2004-12-27
  • 打赏
  • 举报
回复
还有:什么叫“用DataSource域的server.xml”?我看我的server.xml里没有datasource这个域阿
yangbc 2004-12-27
  • 打赏
  • 举报
回复
我的邮箱: kuku_147@sohu.com
yangbc 2004-12-27
  • 打赏
  • 举报
回复
我想说一下,contex不是要放到host里么,如果直接放到service下,好像不行吧
如果大家方便,可以把文件发到我的邮箱里,我觉得文件我能看的更全一些,
最好大家能按我说的要求搭建一个成功的环境,然后把配置资料给我就行了
j2nix 2004-12-27
  • 打赏
  • 举报
回复
用DataSource域的server.xml
<!-- DataSource for DataSourceRealm ,add the following into GlobalNamingResources in server.xml-->
<Resource name="jdbc/tomcatusers"
auth="Container"
type="javax.sql.DataSource" />

<ResourceParams name="jdbc/tomcatusers">
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>

<parameter>
<name>maxActive</name>
<value>100</value>
</parameter>

<parameter>
<name>maxIdle</name>
<value>30</value>
</parameter>

<parameter>
<name>maxWait</name>
<value>10000</value>
</parameter>

<parameter>
<name>username</name>
<value>dbuser</value>
</parameter>
<parameter>
<name>password</name>
<value>1234</value>
</parameter>

<parameter>
<name>driverClassName</name>
<value>com.mysql.jdbc.Driver</value>
</parameter>

<parameter>
<name>url</name>
<value>jdbc:mysql://localhost:3306/tomcatusers?autoReconnect=true</value>
</parameter>
</ResourceParams>
j2nix 2004-12-27
  • 打赏
  • 举报
回复
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app PUBLIC
'-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN'
'http://java.sun.com/j2ee/dtds/web-app_2_3.dtd'>

<web-app>

<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>mypack.DispatcherServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/dispatcher</url-pattern>
</servlet-mapping>

<taglib>
<taglib-uri>/mytaglib</taglib-uri>
<taglib-location>/WEB-INF/mytaglib.tld</taglib-location>
</taglib>


<security-constraint>
<display-name>HelloApp Configuration Security Constraint</display-name>
<web-resource-collection>
<web-resource-name>Protected Area</web-resource-name>
<!-- Define the context-relative URL(s) to be protected -->
<url-pattern>/* </url-pattern>
</web-resource-collection>
<auth-constraint>
<!-- Anyone with one of the listed roles may access this area -->
<role-name>guest</role-name>
<role-name>friend</role-name>
</auth-constraint>
</security-constraint>

<!-- BASIC authentication -->
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>HelloApp realm</realm-name>
</login-config>


<!-- FORM authentication -->
<!--
<login-config>
<auth-method>FORM</auth-method>
<realm-name>HelloApp realm</realm-name>
<form-login-config>
<form-login-page>/usercheck.jsp</form-login-page>
<form-error-page>/error.jsp</form-error-page>
</form-login-config>
</login-config>
-->

<!-- DIGEST authentication -->
<!--
<login-config>
<auth-method>DIGEST</auth-method>
<realm-name>HelloApp realm</realm-name>
</login-config>
-->

<security-role>
<description>
The role that is required to log in to the helloapp Application
</description>
<role-name>guest</role-name>
<role-name>friend</role-name>
</security-role>


</web-app>
j2nix 2004-12-27
  • 打赏
  • 举报
回复
楼主很明显是碰到了Tomcat中“安全域”的问题了,我这正好有之方面的例子,看来很对症。

tomcatusers.sql
create database tomcatusers;
use tomcatusers;

create table users(
user_name varchar(15) not null primary key,
user_pass varchar(15) not null
);

create table user_roles(
user_name varchar(15) not null,
role_name varchar(15) not null,
primary key(user_name,role_name)
);

insert into users values("xiaowang","1234");
insert into users values("xiaoming","1234");

insert into user_roles values("xiaowang","friend");
insert into user_roles values("xiaoming","guest");
jFresH_MaN 2004-12-27
  • 打赏
  • 举报
回复
假设使用的数据库是mysql,实验例子在TOMCAT_HOME/webapps/DBTest目录中

A.将mysql的JDBC连接库mm.mysql-2.0.9-bin.jar放入TOMCAT_HOME/common/lib中

B.配置TOMCAT_HOME/conf/serer.xml文件在<Service>段中加入一个Context:
<Context path="/DBTest" docBase="DBTest"
debug="5" reloadable="true" crossContext="true">
</Context>
这是DBTest的根路径,这是为了在DBTest中使用做准备.

C.在上面加入的<Context>段加入
<Resource name="jdbc/TestDB"
auth="Container"
type="javax.sql.DataSource"/>

<ResourceParams name="jdbc/TestDB">
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>

<!-- 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.
-->
<parameter>
<name>maxActive</name>
<value>100</value>
</parameter>

<!-- Maximum number of idle dB connections to retain in pool.
Set to 0 for no limit.
-->
<parameter>
<name>maxIdle</name>
<value>30</value>
</parameter>

<!-- 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.
-->
<parameter>
<name>maxWait</name>
<value>10000</value>
</parameter>

<!-- MySQL dB username and password for dB connections -->
<parameter>
<name>username</name>
<value>test</value>
</parameter>
<parameter>
<name>password</name>
<value>test</value>
</parameter>

<!-- Class name for mm.mysql JDBC driver -->
<parameter>
<name>driverClassName</name>
<value>org.gjt.mm.mysql.Driver</value>
</parameter>

<!-- The JDBC connection url for connecting to your MySQL dB.-->
<parameter>
<name>url</name>
<value>jdbc:mysql://localhost:3306/test</value>
</parameter>
</ResourceParams>

这里每一个小段都有英文注解,是Tomcat提供的,我们可以将按照Sample加入,主要修改的是driverClassName,
url,和用户帐号;需要强调的是"jdbc/TestDB"就是JDNI要查找的Name.

D. 在JSPh或servlet中使用JNDI查找服务
下面是在JSP文件中关于JNDI使用的代码(文件名记为UserHandleDB.jsp)
需要注意的是JNDI NAME要在前面加上"java:comp/env/"

<%@ page language="java"%>
<%@ page import="java.util.*" %>
<%@ page import="java.sql.*" %>
<%@ page import="javax.sql.*" %>
<%@ page import="javax.naming.*" %>

<%
String jndi_name="java:comp/env/jdbc/TestDB";
String select_user_sql="select userid,name,birthday, email from emp";
String colnames[][]={{"User ID","Name","Birth day","EMail"},
{"userid","name","birthday","email"}};
Vector userSet=new Vector();
Vector columnSet=new Vector();

for(int i=0;i<colnames[0].length;i++){
columnSet.add(colnames[0][i]);
}
userSet.add(columnSet);

Context ctx = new InitialContext();
if(ctx == null )
throw new Exception("No Context");

DataSource ds = (DataSource)ctx.lookup(jndi_name);

Connection conn = ds.getConnection();

try {
PreparedStatement psPreparedStatement=conn.prepareStatement(select_user_sql);
ResultSet resultSet = psPreparedStatement.executeQuery();
while(resultSet.next()){
columnSet=new Vector();
for(int i=0;i<colnames[1].length;i++){
columnSet.add(resultSet.getString(colnames[1][i]));
}
userSet.add(columnSet);
}
}catch(SQLException e) {
e.printStackTrace();
}finally {
conn.close();
%>


E. 引用UserHandleDB.jsp(记为ViewTable.jsp)
<html>
<head>
<title>Test Database </title>
<body >
<%@ include file="UserHandleDB.jsp" %>
<table border="1" >
<%
for(int i=0;i<userSet.size();i++){
Vector colSet=(Vector)userSet.get(i);
out.print("<tr>");
for(int j=0;j<colSet.size();j++){
String col=(String)colSet.get(j);
out.print("<td>"+col+"</td>");
}
out.print("</tr>");
}
%>
</table>
</body>
</html>

F. 在web.xml中加入
<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>
这里的jdbc/TestDb要和C中Resource段的name匹配

G. 观察结果
首先确定数据库已经启动,接着启动Tomcat,如果Tomcat启动异常,可能的原因是数据库的JDBC库没有加载
最后打开浏览器,访问 http://localhost:8080/DBTest/ViewTable.jsp就可以看到结果

67,512

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧