在jsp页面测试已经成功了,在java类里面测试报错: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 at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.lookup(Unknown Source)
at struts2.dao.text.getConnection(text.java:40)
at struts2.dao.text.main(text.java:27)在网上找到了很多类似的问题,但都没有实际解决的,有两种方法
1,加入jndi.properties文件,
2 是加入代码。
具体怎么做啊????java代码:
public static Connection getConnection()
{
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
Connection con=null;
try
{
Context ctx = new InitialContext();
Context envCtx = (Context) ctx.lookup("java:comp/env");
//获取连接池对象 DataSource ds = (DataSource)envCtx.lookup("jdbc/sqlserver");
con=ds.getConnection();
if (ds!=null)
{
con=ds.getConnection(); }
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("ok");
return con; }
先鞋了!!!
at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.lookup(Unknown Source)
at struts2.dao.text.getConnection(text.java:40)
at struts2.dao.text.main(text.java:27)在网上找到了很多类似的问题,但都没有实际解决的,有两种方法
1,加入jndi.properties文件,
2 是加入代码。
具体怎么做啊????java代码:
public static Connection getConnection()
{
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
Connection con=null;
try
{
Context ctx = new InitialContext();
Context envCtx = (Context) ctx.lookup("java:comp/env");
//获取连接池对象 DataSource ds = (DataSource)envCtx.lookup("jdbc/sqlserver");
con=ds.getConnection();
if (ds!=null)
{
con=ds.getConnection(); }
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("ok");
return con; }
先鞋了!!!
Connection conn = null;
Context initCtx = new InitialContext();
if (initCtx == null)
throw new Exception("不能获取Context!");
Context ctx = (Context) initCtx.lookup("java:comp/env");
Object obj = (Object) ctx.lookup("jdbc/sqlserver");//获取连接池对象
DataSource ds = (javax.sql.DataSource) obj; //类型转换
conn = ds.getConnection();
Statement stmt = conn.createStatement();
String sql = "select * from userinfo";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
out.println(rs.getString(1) + "<BR>");
}
rs.close();
stmt.close();
conn.close();
out.println("连接池测试成功");
%>