[code=jscript]<%@ page contentType="text/html" pageEncoding="gbk"%>
<%@ page import="java.sql.*,javax.sql.*,javax.naming.*"%>
<%
String DSNAME="java:comp/env/jdbc/mydatabase" ;
Context ctx = new InitialContext() ;
DataSource ds = (DataSource) ctx.lookup(DSNAME);
Connection conn = ds.getConnection() ;
%>
<%=conn%>
连接成功并关闭
<%
conn.close() ;//将连接放回池中
%>[/code]Tomcat安装目录下的server.xml和web-inf下的web.xml都正确配置了,而且这个jsp页面正常输出了conn连接的路径
但是下面的:[code=java]package sjy.xg.myc.datasource;
import java.sql.*;//Connection
import javax.sql.*;//DataSource
import javax.naming.*;//Context
public class DatabaseConnection{
private Connection conn = null ;
private String DSNAME="java:comp/env/jdbc/mydatabase" ;
public DatabaseConnection() throws Exception{
Context ctx = new InitialContext() ;
DataSource ds = (DataSource) ctx.lookup(DSNAME);
this.conn = ds.getConnection() ;
}
public Connection getConnection(){
return this.conn ;
}
public void close() throws Exception {
if(this.conn != null){
try{
conn.close() ;
}catch(Exception e){
throw e ;
}
}
}
public static void main(String[] args) throws Exception{
Connection conn = new DatabaseConnection().getConnection();
System.out.println("sucess"+conn);
}
}[/code]老出现错误:
Exception in thread "main" javax.naming.NoInitialContextException: Need to specify class name in env
ironment or system property, or as an applet parameter, or in an application resource file: java.na
ming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:645)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:325)
at javax.naming.InitialContext.lookup(InitialContext.java:392)
at sjy.xg.myc.datasource.DatabaseConnection.<init>(DatabaseConnection.java:11)
at sjy.xg.myc.datasource.DatabaseConnection.main(DatabaseConnection.java:30)
怎么解决????? |