JNDI的配置

开发环境:jdk1.6+myeclipse6.5+mysql5.0+tomcat6.0.14

1.第一步:在apache-tomcat-6.0.14/conf/context.xml中添加:用于配置JNDI的名字
其中的代码如下:
   <Resource name="jdbc/mysql"
    type="javax.sql.DataSource"
    password="alen"
    driverClassName="com.mysql.jdbc.Driver"
    maxIdle="40"
    maxWait="5000"
    username="root"
    url="jdbc:mysql://localhost:3306/spacedebris"
    maxActive="40"/>

加到<Context> </Context>之间

2.第二步:在项目的web.xml加入代码:
  <resource-ref>
   <description>mysqlDB</description>
   <res-ref-name>jdbc/mysql</res-ref-name>
   <res-type>javax.sql.DataSource</res-type>
   <res-auth>Container</res-auth>
  </resource-ref>

放在<web-app version="2.4" >  </web-app>之间

3.用jsp代码测试:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="java.sql.*,javax.sql.*,javax.naming.*"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'MySqlDSTest.jsp' starting page</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">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->

  </head>
 
  <body>&nbsp;
    <%
     DataSource ds=null;
     try{
      
      InitialContext ctx=new InitialContext();
      ds=(DataSource)ctx.lookup("java:comp/env/jdbc/mysql");
      Connection conn=ds.getConnection(); 
      conn.close();
      out.println("JNDI连接MYSQL测试成功!");
     }catch(Exception ex){
      out.println(ex.getMessage());
     }
      %>
  </body>
</html>


最后效果如下:

JNDI连接MYSQL测试成功!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值