JSP代码

时间:2017-04-17 13:56:34

标签: java jsp exception error-handling

在我的智慧结束后,我在这里发帖提问。 我得到" java.lang.NullPointerException"开发小型JSP Web应用程序时出错。 请帮我修理一下。

下面我提到我的代码:

<body>
    <%!
        public class Actor{
        String URL = "jdbc:mysql://localhost:3306/henry_books";
        String USERNAME = "root";
        String PASSWORD = "adminroot";

        Connection connection = null;
        PreparedStatement selectActors = null;
        ResultSet resultSet = null;
        public Actor(){
        try{
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            selectActors = connection.prepareStatement("SELECT * FROM author");

            }catch(SQLException e){
                e.printStackTrace();
            }
        }
        public ResultSet getActors(){
            try{
                resultSet = selectActors.executeQuery();
            }catch(SQLException e){
                e.printStackTrace();
            }
            return resultSet;
         }
        }
    %>
    <%
        Actor actor = new Actor();
        ResultSet actors = actor.getActors();
        while(actors.next()){
            %>
            <span><%= actors.getInt("authorNum")%></span>  
        <% }
    %>
</body>

在ResultSet上获取错误actors = actor.getActors();线 错误:

  org.apache.jasper.JasperException: 

在第48行处理JSP页面/book_app/web/index.jsp时发生异常

45:         %>
46:         <%
47:             Actor actor = new Actor();
48:             ResultSet actors = actor.getActors();
49:             while(actors.next()){
50:                 %>
51:                 <span><%= actors.getInt("authorNum")%></span>  


Stacktrace:    
root cause

java.lang.NullPointerException
org.apache.jsp.book_005fapp.web.index_jsp$Actor.getActors(index_jsp.java:39)
org.apache.jsp.book_005fapp.web.index_jsp._jspService(index_jsp.java:109)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)

1 个答案:

答案 0 :(得分:0)

在建立连接之前添加Driver类,并确保在lib文件夹中添加了mysql-connector.jar文件。

public Actor(){
    try{
        Class.forName("com.mysql.jdbc.Driver");  //Add this line
        connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        selectActors = connection.prepareStatement("SELECT * FROM author");

        }catch(SQLException e){
            e.printStackTrace();
        }
    }

Refer this for details