tomcat配置数据源连接(针对单个web应用)

来源:互联网 发布:程序员累吗 编辑:程序博客网 时间:2024/06/05 09:12

如图简历web应用项目

在META-INF目录下建立context.xml,并配置数据源连接如下:

<?xml version="1.0" encoding="UTF-8"?>
<Context antiResourceLocking="false" privileged="true" useHttpOnly="true" >
  <!--add dataSource-->
<Resource
        name="jdbc/oracle"
        auth="Container"
        type="javax.sql.DataSource"
        maxActive="100"
        maxIdle="30"
        maxWait="10000"
        username="scott"
        password="dean"
        driverClassName="oracle.jdbc.driver.OracleDriver"
        url="jdbc:oracle:thin:@localhost:1521:ORCL"/>
</Context>

在WEB-INF目录下建立web.xml文件如下:

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   version="2.5"> 
<resource-ref>
<description>oracleDBConnection</description>
<res-ref-name>jdbc/oracleDataSource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
   </resource-ref>
</web-app>

同时在WEB-INF目录下建立lib目录,放入oracle数据库驱动jar包:ojdbc14.jar

D:\apache-tomcat-6.0.37\webapps\OraceDataSourceTest在此目录下建立testOracleDataSource.jsp文件

代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 
<% 
String path = request.getContextPath(); 
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> 
<%@ page import="java.sql.*"%> 
<%@ page import="javax.sql.*"%> 
<%@ page import="javax.naming.*"%> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
  <head> 
    <base href="<%=basePath%>"> 
     
    <title>My JSP 'testPool.jsp' starting page</title> 
     
    <meta http-equiv="pragma" c> 
    <meta http-equiv="cache-control" c> 
    <meta http-equiv="expires" c> 
    <meta http-equiv="keywords" c> 
    <meta http-equiv="description" c> 
     
    <!-- 
    <link rel="stylesheet" type="text/css" href="styles.css"> 
    --> 
  </head> 
   
  <body> 
    This is my JSP page. <br> 
    <% 
     Connection conn; 
     Context initCtx=new InitialContext(); 
     javax.sql.DataSource ds =(javax.sql.DataSource)initCtx.lookup("java:/comp/env/jdbc/oracle");
     conn = ds.getConnection(); 
     Statement stmt=conn.createStatement(); 
     PreparedStatement ps=conn.prepareStatement("select * from emp"); 
     ResultSet rs=ps.executeQuery(); 
     while(rs.next()){ 
      out.println(rs.getString(1)+"&nbsp;"+rs.getString(2)+"&nbsp;"+rs.getString(3)+"<br>"); 
     } 
     rs.close(); 
     stmt.close(); 
     out.println("ok"); 
    %> 
  </body> 
</html>

如果要配置全局的数据连接建议在D:\apache-tomcat-6.0.37\conf目录下的server.xml文件的<Context>目录下加入对应的Resource配置数据源,就可以直接在每个项目中用了

0 0
原创粉丝点击