运行环境是tomcat+mysql
开发环境是eclipse+lomboz下面是照书上的例程改过的代码,为了让大家更容易看明白,其中//部门就是造成错误的地方:<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>数据库操作</title>
</head>
//连接数据库
<%
String product_name="";Connection con=null;
Statement sm=null;
ResultSet rs=null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url="jdbc:mysql://localhost/mydb";
con=DriverManager.getConnection(url,"root","12345");
sm=con.createStatement();
rs=sm.executeQuery("select * from products");
}catch(Exception e){
e.printStackTrace();
}
%>
//读取数据库记录
//<%
//while(rs.next()){
//product_name=rs.getString("PRODUCT_NAME");
//}
//%>
<%=product_name%>
<body></body>
</html>
如果去掉//
//读取数据库记录
//<%
//while(rs.next()){
//product_name=rs.getString("PRODUCT_NAME");
//}
//%>
此部分造成的错误提示如下:HTTP Status 500 - --------------------------------------------------------------------------------type Exception reportmessage description The server encountered an internal error () that prevented it from fulfilling this request.exception org.apache.jasper.JasperException
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:372)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
root cause java.lang.NullPointerException
org.apache.jsp.index_jsp._jspService(index_jsp.java:70)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:324)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
note The full stack trace of the root cause is available in the Apache Tomcat/5.0.30 logs.
--------------------------------------------------------------------------------Apache Tomcat/5.0.30

解决方案 »

  1.   

    看了你的例子,感觉是没有取到数据库的连接,所以造成一下语句抛出NullPointerExceptionsm=con.createStatement();加上一句System.out.println("con: " + con);在这个语句前,检查一下这个值。
      

  2.   

    如果能执行到这句的话不管有什么样的结果至少会显示出con:
      

  3.   

    Class.forName("com.mysql.jdbc.Driver").newInstance();
    String url="jdbc:mysql://localhost/mydb";
    con=DriverManager.getConnection(url,"root","12345");
    你不会这些驱动名称,路径什么的也是照抄的吧