gpt4 book ai didi

java - JSP代码中的java.lang.NullPointerException

转载 作者:行者123 更新时间:2023-12-03 08:50:04 25 4
gpt4 key购买 nike

机智结束后,我在这里发布问题。
开发小型JSP Web应用程序时出现“java.lang.NullPointerException”错误。
请帮我修复它。

在下面,我提到我的代码:

<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)

最佳答案

在建立连接之前添加驱动程序类,并确保已在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

关于java - JSP代码中的java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43452916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com