Connect to Oracle database using connection pool under Tomcat server

  • 2021-10-25 00:08:17
  • OfStack

The following describes the operation of using connection pool to connect to the database under Tomcat server

1: Modify the web. xml file:
 
<?xml version="1.0" encoding="UTF-8"?> 
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> 
<display-name>project</display-name> 
<welcome-file-list> 
<welcome-file>index.html</welcome-file> 
<welcome-file>index.htm</welcome-file> 
<welcome-file>index.jsp</welcome-file> 
<welcome-file>default.html</welcome-file> 
<welcome-file>default.htm</welcome-file> 
<welcome-file>default.jsp</welcome-file> 
</welcome-file-list> 

<resource-ref> 
<description>DBConnection</description> 
<res-ref-name>siniteksirm</res-ref-name> 
<res-type>javax.sql.DataSource</res-type> 
<res-auth>Container</res-auth> 
</resource-ref> 
</web-app> 

Insert between web-app < resource-ref > This code. Specifies the Resource name to use.

2: Modify the context. xml file under tomcat:

Add the following code between Context tags.
 
<Resource name="siniteksirm" auth="Container" 
type="javax.sql.DataSource" 
driverClassName="oracle.jdbc.OracleDriver" 
url="jdbc:oracle:thin:@192.168.1.196:1521:orcl" 
username="paxt" 
password="paxt" 
maxActive="20" 
maxIdle="10" 
maxWait="-1" 
testOnBorrow="true" 
validationQuery="select 1 from dual"/> 

3: Select the database driver for Oracle and add it to the lib package for Tomcat. In this project: Ojdbc14. jar.

4: Provide 1 jsp page:
 
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 
<%@ page import="javax.naming.Context" %> 
<%@ page import="javax.naming.InitialContext" %> 
<%@ page import="java.sql.*" %> 
<%@ page import="javax.sql.DataSource" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>Insert title here</title> 
</head> 
<body> 
<% 
DataSource ds = null; 
try{ 
Context context = new InitialContext(); 
ds = (DataSource)context.lookup("java:comp/env/siniteksirm"); 
Connection conn = ds.getConnection(); 
PreparedStatement pst = conn.prepareStatement("select * from sdc_fundbase where rownum <= 2"); 
ResultSet rs = pst.executeQuery(); 
while(rs.next()){ 
out.println(rs.getString("fund4")); 
out.println("<br/>"); 
} 
if(ds != null){ 
out.println(" Database connection "); 
} 
}catch(Exception e){ 
e.printStackTrace(); 
out.println(" Database connection failed "); 
} 
%> 
</body> 
</html> 

Start Tomcat so that you can access the page.

Related articles: