tomcat6.0
server.xml
<Context path="/" docBase="InvoicingMS" debug="0" reloadable="true" >
         <Resource name="jdbc/invoJndi" 
auth="Container" 
type="javax.sql.DataSource" 
driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver"  url="jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=pubs" 
username="sa" 
password="2008" 
maxIdle="30" 
maxWait="10000" 
 />
 </Context>catalina->localhost下的InvoicingMS.xml<Context path="/" docBase="InvoicingMS" debug="0" reloadable="true"> 
<Resource name="jdbc/invoJndi" 
auth="Container" 
type="javax.sql.DataSource" 
driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver" 
url="jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=pubs" 
username="sa" 
password="2008" 
maxIdle="30" 
maxWait="10000" 
 /><ResourceLink name="jdbc/invoJndi" global="jdbc/invoJndi" type="javax.sql.DataSource"/> web-info web.xml
<resource-ref>
    <description>DB Connection</description>
    <res-ref-name>jdbc/invoJndi</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    </resource-ref>测试类package com.lv.db;import java.sql.Connection;import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;/**
 * @author lvwenqiang
 * 获取数据源
 */
public class DbUtils {

private static InitialContext ctx = null;
private static DataSource dataSource = null;
private static Connection conn=null;

static{
try {
try {
ctx = new InitialContext();
} catch (NamingException e) {
e.printStackTrace();
}         
try {
dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/invoJndi");
} catch (NamingException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}

static Connection getConn(){
try{
conn=dataSource.getConnection();
}catch(Exception e){
e.printStackTrace();
}
return conn;
}

static void close(){
if(conn!=null){
try{
conn.close();
}catch(Exception e){
e.printStackTrace();
}  
conn=null;
}
}

public static void main(String[] args){
getConn();
}
}
报错信息
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial

解决方案 »

  1.   

    context前需要先初始化。却指定入口地址。System.setProperty(x,y)的,里面两个常量忘了。自己查一下吧……
      

  2.   

    你的Context没有找到服务器,你应该用一个Hashtable表来告诉Context你的服务器在什么地方.

     Hashtable env=new Hashtable();
            env.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
            env.put(Context.PROVIDER_URL,"t3://localhost:7001");            Context ctx = new InitialContext(env); from :http://zhidao.baidu.com/question/11727714.html
      

  3.   

    因为Context不知道你的服务器在哪所以你可以把现实数据代码写到页面,或者学习#14楼的也OK
      

  4.   

    4楼说的对,不过你那个答案是weblogic服务器的确不能用主函数运行
    大家看下面这个例子,它就没用main函数
    http://www.ieee.org.cn/dispbbs.asp?boardID=41&ID=48188有关这方面的一个很好的例子
    http://www.javaeye.com/topic/245596谢谢楼上的七位