我的测试页test.jsp,应该没什么问题
<%@ page contentType="text/html; charset=GBK"%>
<%@ page import="java.sql.*,javax.sql.DataSource,javax.naming.*"%>
<html>
<head><title>test.jsp</title></head>
<body bgcolor="#ffffff">
<h1>test Tomcat</h1>
<%
try
{
Context initCtx=new InitialContext();
DataSource ds = (DataSource)initCtx.lookup("java:comp/env/jdbc/MySql_ResSys");
Connection conn=ds.getConnection();
out.println("data from database:<br>");
Statement stmt=conn.createStatement();
ResultSet rs =stmt.executeQuery("select id, name from testdata");
while(rs.next())
{
out.println(rs.getInt("id"));
out.println(rs.getString("name"));
}
rs.close();
stmt.close();
}
catch(Exception e)
{
e.printStackTrace();
}
%>
</body>
</html>
当启动时出现以下错误:
HttpConnector[8080] Starting background thread
javax.naming.NamingException: Cannot create resource instance
at org.apache.naming.factory.ResourceFactory.getObjectInstance(ResourceFactory.java:167)
at javax.naming.spi.NamingManager.getObjectInstance(NamingManager.java:301)
at org.apache.naming.NamingContext.lookup(NamingContext.java:834)
at org.apache.naming.NamingContext.lookup(NamingContext.java:181)
at org.apache.naming.NamingContext.lookup(NamingContext.java:822)
at org.apache.naming.NamingContext.lookup(NamingContext.java:181)
at org.apache.naming.NamingContext.lookup(NamingContext.java:822)
at org.apache.naming.NamingContext.lookup(NamingContext.java:181)
at org.apache.naming.NamingContext.lookup(NamingContext.java:822)
at org.apache.naming.NamingContext.lookup(NamingContext.java:194)
at org.apache.naming.SelectorContext.lookup(SelectorContext.java:183)
at javax.naming.InitialContext.lookup(InitialContext.java:347)
at org.apache.jsp.testjsp3$jsp._jspService(testjsp3$jsp.java:69)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:107)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at org.apache.jasper.servlet.JspServlet$JspServletWrapper.service(JspServlet.java:201)
是何原因?
javax.naming.NamingException: Cannot create resource instance
------解决方法--------------------------------------------------------
应该是DataSource ds = (DataSource)initCtx.lookup("java:comp/env/jdbc/MySql_ResSys");
报出的异常,说明JNDI没有lookup到。
你的server8080.xml配置文件Context docBase="" path=""是否写对?不能有重复path等
------解决方法--------------------------------------------------------
你要使用res-ref-name
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
lookup("java:comp/env/jdbc/TestDB");