The JDBC resource in Tomcat is designed using Jndi to configure JDBC resources in Tomcat and learn how to configure Jndi resources. The following is a JDBC resource to illustrate how to use Tomcat's resource services.
1. Define JNDI Resources
Can be defined as a global resource, or it can be defined as a resource for a Web context.
Scenario 1: Define the JNDI resource in context:
To define a resource, to use <resource>, define a JDBC resource as follows:
<Context><ResourceAuth= "Container"name= "Jdbc/mysql_jdbctest"type= "Javax.sql.DataSource"Driverclassname= "Com.mysql.jdbc.Driver"username= "Cloudlink"Password= "Cloudlink"Maxidle= "2"maxwait= "the"URL= "Jdbc:mysql:192.168.2.92:3306/jdbctest?useencoding=utf-8"maxactive= "4"/></Context>
Scenario 2:
Defines a global Jndi resource, defined in the <GlobalNamingResource> of Tomcat/conf/server.xml.
The following is a definition of a global resource, which is placed in <GlobalNamingResource>.
<Globalnamingresource><ResourceAuth= "Container"name= "Jdbc_test_1"type= "Javax.sql.DataSource"Driverclassname= "Com.mysql.jdbc.Driver"username= "Cloudlink"Password= "Cloudlink"Maxidle= "2"maxwait= "the"URL= "Jdbc:mysql:192.168.2.92:3306/jdbctest?useencoding=utf-8"maxactive= "4"/></Globalnamingresource>
Then in the <Context> link global resources:
< Context > < Globalname type/> </ Context>
in this way, a global resource is linked to a context.
2. Defining a reference to a Jndi resource in a Web application
In Web. XML, declare which Jndi resources to reference.
<Resource-ref> <Res-ref-name>Jdbc/mysql_jdbctest</Res-ref-name><Res-type>Javax.sql.DataSource</Res-ref-name><Res-auth>Container</Res-ref-name></Resource-ref>
when a reference to a JNDI resource is defined in a Web application, the corresponding resource can be found in the Web application based on that reference.
3. Using Jndi resources in Web applications
Public voidGet (HttpServletRequest request, httpservletresponse response)throwsexception{Context Context=NewInitialContext (); Context Envcontext= (Context) context.lookup ("java:/com/env "); DataSource DS= (DataSource) envcontext.lookup ("jdbc/mysql_jdbctest "); Connection Conn=ds.getconnection (); Statement stmt=conn.createstatement (); String SQL="Select UserID, username, age from User"; ResultSet RS=stmt.executequery (SQL); PrintWriter out=Response.getwriter (); while (Rs.next ()) {out.println (rs.getstring (1) + "\ T" +rs.getstring (2) + "\ T" +rs.getint (3) + "<br>"); } rs.close (); Stmt.close (); Conn.close (); Out.flush (); Out.close ();}
4, create the corresponding database, table
Insert data:
Insert into User Values (' Hello1 ', ' name1 ',);
5. Start Tomcat and test.
Before you start Tomcat, you need to add the JDBC driver for MySQL under Tomcat/lib.
Tomcat: Defining Jndi Resources, accessing the database