Tomcat: defines the JNDI resource, accesses the database, and atatjndi
JDBC resources in Tomcat are designed using JNDI. You must configure JDBC resources in Tomcat and learn how to configure JNDI resources. The following describes how to use Tomcat's Resource Service with JDBC resources.
1. Define the JNDI Resource
It can be defined as a global resource or a resource for a Web Context.
Solution 1: Define the JNDI resource in Context:
To define a Resource, use <Resource>. a jdbc Resource is defined below:
<Context><Resource auth=”Container”name=”jdbc/mysql_jdbcTest”type=”javax.sql.DataSource”driverClassName=”com.mysql.jdbc.Driver”username=”cloudlink”password=”cloudlink”maxIdle=”2”maxWait=”5000”url=”jdbc:mysql:192.168.2.92:3306/jdbcTest?useEncoding=UTF-8”maxActive=”4”/></Context>
Solution 2:
Define global JNDI resources, which are defined in <GlobalNamingResource> of tomcat/conf/server. xml.
The following is a global resource definition, which is placed in <GlobalNamingResource>.
<GlobalNamingResource><Resource auth=”Container”name=”jdbc_test_1”type=”javax.sql.DataSource”driverClassName=”com.mysql.jdbc.Driver”username=”cloudlink”password=”cloudlink”maxIdle=”2”maxWait=”5000”url=”jdbc:mysql:192.168.2.92:3306/jdbcTest?useEncoding=UTF-8”maxActive=”4”/></GlobalNamingResource>
Then, link the global resource in <Context>:
<Context> <ResourceLink global=”jdbc_test_1” name=”jdbc/mysql_jdbcTest” type=”javax.sql.DataSource” /></Context>
In this way, a global resource is linked to a Context.
2. Define a reference to a JNDI resource in a Web application
Declare the JNDI resources to be referenced in web. xml.
<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>
After defining a reference to a jndi resource in a web application, the web application can find the corresponding resource based on the reference.
3. Use JNDI resources in Web Applications
public void get(HttpServletRequest request, HttpServletResponse response) throws Exception{ Context context=new InitialContext(); 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 a database and table
Insert data:
insert into User (userid, username, age) values(‘hello1’,’name1’,20);
5. start Tomcat for testing.
Before starting Tomcat, you must add the MySql JDBC driver under Tomcat/lib.