(1) "C:/Program Files/apache-tomcat-5.5.25/conf/Catalina/localhost/testDBConnection.xml"
<?xml version='1.0' encoding='utf-8'?>
<Context crossContext="true" docBase="c:/eclipse/workspace/testDBConnection" path="/testDBConnection" workDir="C:/eclipse/workspace/testDBConnection/work">
<Resource name="jdbc/test" auth="Container" type="javax.sql.DataSource"
username="root" password="123456"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/test"
maxActive="20" maxIdle="10" maxWait="10000" />
</Context>
(2)web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<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">
<servlet>
<servlet-name>SelectCityServlet</servlet-name>
<servlet-class>com.stephen.servlet.SelectCityServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>testJsp</servlet-name>
<jsp-file>/index1.jsp</jsp-file>
<init-param>
<param-name>email</param-name>
<param-value>[email protected]</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>RefreshModelListServlet</servlet-name>
<servlet-class>com.stephen.servlet.RefreshModelListServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>DynamicUpdateServlet</servlet-name>
<servlet-class>com.stephen.servlet.DynamicUpdateServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SelectCityServlet</servlet-name>
<url-pattern>/SelectCityServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>testJsp</servlet-name>
<url-pattern>/index1.jsp</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>RefreshModelListServlet</servlet-name>
<url-pattern>/RefreshModelListServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>DynamicUpdateServlet</servlet-name>
<url-pattern>/DynamicUpdateServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<context-param>
<param-name>email</param-name>
<param-value>[email protected]</param-value>
</context-param>
<listener>
<listener-class>com.Listener.MyServletContextListener</listener-class>
</listener>
<!--forbid scriptlet :true <jsp-config> element is limited to 1 occurance-->
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<el-ignored>false</el-ignored>
<scripting-invalid>false</scripting-invalid>
</jsp-property-group>
</jsp-config>
<!--forbid expression language :true
<jsp-config>
<jsp-property-group>
<url-pattern>*jsp</url-pattern>
<el-ignored>false</el-ignored>
</jsp-property-group>
</jsp-config>-->
<welcome-file-list>
<welcome-file>index1.jsp</welcome-file>
<!--<welcome-file>jsp/handleit.jsp</welcome-file>-->
</welcome-file-list>
<error-page>
<error-code>404</error-code>
<location>/404Notfound.jsp</location>
</error-page>
<resource-ref>
<res-ref-name>jdbc/test</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
(3)DbAccessor.java
package com.db;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
/*
* 作成日: 2009/05/04
*
*/
/**
* @author hx0331
*
*/
public class DbAccessor
{
public static DataSource getResult()
{
DataSource result = null;
Context initContext = null;
try
{
initContext = new InitialContext();
result = (DataSource) initContext.lookup("java:comp/env/jdbc/test");
// Context envContext =
// (Context)initContext.lookup("java:comp/env");
// // 找到DataSource
// result = (DataSource)envContext.lookup("jdbc/mysql");
}
catch (NamingException e)
{
e.printStackTrace();
}
finally
{
if (initContext != null)
{
try
{
initContext.close();
}
catch (NamingException e1)
{
e1.printStackTrace();
}
}
}
return result;
}
public static Connection getConnection()
{
Connection conn = null;
try
{
conn = getResult().getConnection();
}
catch (SQLException e)
{
e.printStackTrace();
}
return conn;
}
public static void rollback(Connection conn)
{
try
{
conn.rollback();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
(4)sqlMaker.java
/*
* 作成日: 2009/05/19
*/
package com.db;
/**
* @author hx0331
*
*/
public class sqlMaker
{
public static String getNameByStuID()
{
StringBuffer sb = new StringBuffer();
sb.append("select *");
sb.append(" from a");
sb.append(" where stuID=?");
return sb.toString();
}
}
(5)SelectCityServlet.java
package com.stephen.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.db.DbAccessor;
import com.db.sqlMaker;
public class SelectCityServlet extends HttpServlet
{
public SelectCityServlet()
{
super();
}
public void destroy()
{
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
String state = request.getParameter("state");
StringBuffer sb = new StringBuffer("<state>");
//this.getServletConfig().getInitParameter("aa");
//this.getServletConfig().getServletContext().getInitParameter("aa");
//this.getServletContext().getInitParameter("dd");
//this.
Connection conn = DbAccessor.getConnection();
if ("zj".equals(state))
{
try
{
if (conn != null)
{
conn.setAutoCommit(false);
PreparedStatement statement = conn.prepareStatement(sqlMaker.getNameByStuID(), ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
statement.setString(1, "111");
ResultSet rs = statement.executeQuery();
while (rs.next())
{
sb.append("<city>");
sb.append(rs.getString("Name"));
sb.append("</city>");
}
conn.commit();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
try
{
conn.rollback();
conn.setAutoCommit(true);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
else if ("zs".equals(state))
{
sb.append("<city>");
sb.append("nanjing");
sb.append("</city>");
sb.append("<city>");
sb.append("yangzhou");
sb.append("</city>");
sb.append("<city>");
sb.append("suzhou");
sb.append("</city>");
}
sb.append("</state>");
PrintWriter out = response.getWriter();
out.write(sb.toString());
out.close();
}
}
(6)index.jsp
<html>
<head>
<title>MyHtml.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
</head>
<script type="text/javascript">
function getResult(stateVal)
{
var url = "SelectCityServlet?state="+stateVal;
if (window.XMLHttpRequest)
{
req = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if(req)
{
req.open("GET",url, true);
req.onreadystatechange = complete;
req.send(null);
}
}
function complete()
{
if (req.readyState == 4)
{
if (req.status == 200)
{
var city = req.responseXML.getElementsByTagName("city");
<!--file://alert(city.length);-->
var str=new Array();
for(var i=0;i<city.length;i++)
{
str[i]=city[i].firstChild.data;
}
<!--file://alert(document.getElementById("city"));-->
buildSelect(str,document.getElementById("city"));
}
}
}
function buildSelect(str,sel)
{
sel.options.length=0;
for(var i=0;i<str.length;i++)
{
sel.options[sel.options.length]=new Option(str[i],str[i])
}
}
</script>
<body>
<select name="state" onChange="getResult(this.value)">
<option value="">Select</option>>
<option value="zj">ZEHJIANG</option>>
<option value="zs">JIANGSU</option>>
</select>
<select id="city">
<option value="">CITY</option>
</select>
</body>
</html>
-------------------------------------------------------------------------------2011-08-01追加
补充方法2
修改D:\java\tomcat5.0_test\conf\server.xml
<?xml version='1.0' encoding='utf-8'?>
<Server>
<Listener className="org.apache.catalina.mbeans.ServerLifecycleListener"/>
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
<GlobalNamingResources>
<Environment name="simpleValue" type="java.lang.Integer" value="30"/>
<Resource auth="Container" description="User database that can be updated and saved" name="UserDatabase" type="org.apache.catalina.UserDatabase"/>
<Resource name="DS_SERVER" type="javax.sql.DataSource"/>
<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>
<ResourceParams name="DS_SERVER">
<parameter>
<name>maxWait</name>
<value>5000</value>
</parameter>
<parameter>
<name>maxActive</name>
<value>4</value>
</parameter>
<parameter>
<!--<name>password</name>
<value>useroper</value>-->
<name>password</name>
<value>test</value>
</parameter>
<parameter>
<name>url</name>
<!--<value>jdbc:sybase:Tds:127.0.0.1:8888?charset=eucgb</value>-->
<value>jdbc:oracle:thin:@localhost:1521:test</value>
</parameter>
<parameter>
<name>driverClassName</name>
<!--<value>com.sybase.jdbc2.jdbc.SybDriver</value>-->
<value>oracle.jdbc.OracleDriver</value>
</parameter>
<parameter>
<name>maxIdle</name>
<value>2</value>
</parameter>
<parameter>
<name>username</name>
<value>test</value>
</parameter>
</ResourceParams>
</GlobalNamingResources>
<Service name="Catalina">
<Connector acceptCount="100" connectionTimeout="20000" disableUploadTimeout="true" port="8080" redirectPort="8443" maxSpareThreads="75" maxThreads="150" minSpareThreads="25" useBodyEncodingForURI="true" URIEncoding="GBK">
</Connector>
<Connector port="8009" protocol="AJP/1.3" protocolHandlerClassName="org.apache.jk.server.JkCoyoteHandler" redirectPort="8443">
</Connector>
<Engine defaultHost="localhost" name="Catalina">
<Host appBase="webapps" name="localhost">
<Logger className="org.apache.catalina.logger.FileLogger" prefix="localhost_log." suffix=".txt" timestamp="true"/>
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="access." suffix=".log" pattern="common" resolveHosts="false"/>
<Context docBase="D:/workspace/management/webapps" path="/management" reloadable="true">
<ResourceLink global="DS_SERVER" name="DS_SERVER" type="javax.sql.DataSource"/>
</Context>
</Host>
<Logger className="org.apache.catalina.logger.FileLogger" prefix="catalina_log." suffix=".txt" timestamp="true"/>
<Realm className="org.apache.catalina.realm.UserDatabaseRealm"/>
</Engine>
</Service>
</Server>
以上配置,就可以配置好了,jndi数据库数据源了。