1.数据库连接访问方式
JSP里面链接数据库操作如下:
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/bookstore");
Connection conn = ds.getConnection();
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("select * from guestbook order by gst_time desc");
2.异常详细信息
登录到JSP页面时,抛出异常如下:
type Exception report
message javax.servlet.ServletException: org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class ‘‘ for connect URL ‘jdbc:mysql://localhost:3306/bookstore?autoReconnect=true‘
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: javax.servlet.ServletException: org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class ‘‘ for connect URL ‘jdbc:mysql://localhost:3306/bookstore?autoReconnect=true‘ org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:502) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:412) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260) javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
3.通过异常信息,定位问题
通过查看异常信息,发现 driver class为空,说明driver class配置不对
查看server.xml文件,配置如下:
<Context path="/ch12" docBase="I:\Develop\Code\Chapter12" reloadable="true">
<Resource name="jdbc/bookstore" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="root" password="root"
dirverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/bookstore?autoReconnect=true" />
</Context>
通过观察发现,原本应该是“driverClassName”却误写成"dirverClassName"
将修正driverClassName之后,重启Tomcat,JSP网页访问正常
4.Context.lookup参数说明
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/bookstore");
说明:java:comp/env 是固定参数
jdbc/bookstore 对应两个地方:
一个是:server.xml中的Resource name
另一个:web.xml中的resource-ref res-ref-name
详细配置:server.xml
(见上面第3步的异常定位)
<Context path="/ch12" docBase="I:\Develop\Code\Chapter12" reloadable="true">
<Resource name="jdbc/bookstore" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="root" password="root"
dirverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/bookstore?autoReconnect=true" />
</Context>
详细配置:web.xml
<resource-ref>
<description>Mysql JDBC DataSource</description>
<res-ref-name>jdbc/bookstore</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
程序可以换成:
InitialContext context=new InitialContext();
Context evnContext = (Context)initContext.lookup("java:/comp/env");
DataSource dataSource = (DataSource)evnContext.lookup("jdbc/bookstore");
Connection con = dataSource.getConnection();
5.总结
1)掌握通过页面抛出的异常信息,快速定位问题,解决问题
2)掌握JSP的数据库连接方式配置和使用方法