Tomcat6.0 and later versions configure JNDI, just modify the conf context. xml file, in the Tomcat directory lib add common-dbcp.jar and database jar package
<? XML version = '1. 0' encoding = 'utf-8'?>
<Context>
<Watchedresource> WEB-INF/Web. xml </watchedresource>
<! -- Add configuration and configure external data sources -->
<Resource Name = "JDBC/db2source"
Auth = "Container"
Type = "javax. SQL. datasource"
Url = "JDBC: sqlserver: // 192.168.0.119; databasename = XXXXX"
Username = "sa"
Password = "XXXXX ."
Driverclassname = "com. Microsoft. sqlserver. JDBC. sqlserverdriver"
Maxidle = "3"
Maxwait = "-1"
Maxactive = "50"/>
</Context>
Parameter introduction:
Name: Set the name (JNDI) for the data source)
Auth: who manages the data source
Type: Type
Maxactive: Maximum number of activated connections in the connection pool
Maxidle: Maximum number of reserved (idle) connections in the connection pool
Maxwait: Maximum waiting time (in seconds) for the client in the queue pool)
Test code (a new web project cannot be tested in the main method ):
<% @ Page Language = "Java" contenttype = "text/html; charset = UTF-8" pageencoding = "UTF-8" %>
<% @ Page Language = "Java" %>
<% @ Page import = "Java. util. *" %>
<% @ Page import = "Java. SQL. *" %>
<% @ Page import = "javax. SQL. *" %>
<% @ Page import = "javax. Naming. *" %>
<! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en">
<HTML>
<Head>
<Title> Configure JNDI </title>
<Meta http-equiv = "Pragma" content = "no-Cache">
<Meta http-equiv = "cache-control" content = "no-Cache">
<Meta http-equiv = "expires" content = "0">
<Meta http-equiv = "keywords" content = "keyword1, keyword2, keyword3">
<Meta http-equiv = "Description" content = "this is my page">
</Head>
<Body>
Tomcat6.0 + configure JNDI (common-dbcp.jar, sqljdbc4.jar)
<%
Connection conn = NULL;
Preparedstatement PS = NULL;
Resultset rs = NULL;
Try {
Context CTX = new initialcontext ();
Context envcontext = (context) CTX. Lookup ("Java:/COMP/ENV ");
Datasource DS = (datasource) envcontext. Lookup ("JDBC/db2source ");
Conn = Ds. getconnection ();
If (conn = NULL ){
System. Out. println ("the connection has not been obtained successfully ...........");
} Else {
System. Out. println ("Get connection ............");
}
String SQL = "select * From systemusers ";
PS = conn. preparestatement (SQL );
Rs = ps.exe cutequery ();
While (Rs. Next ()){
System. Out. println ("==================== name:" + Rs. getstring ("username "));
Out. println ("==================== name:" + Rs. getstring ("username") + "\ r ");
}
} Catch (exception e ){
E. printstacktrace ();
} Finally {
Try {
If (Conn! = NULL ){
Conn. Close ();
}
If (PS! = NULL ){
PS. Close ();
}
If (RS! = NULL ){
Rs. Close ();
}
} Catch (sqlexception e ){
E. printstacktrace ();
}
}
%>
</Body>
</Html>