I am beginner in using JSP and have a problem with the java.lang.NullPointerException. The problem occurs if I use the following part (the full source is below). If i delete the source the page is loading without any returns. I would be happy if anyone helped me to run the code.
Background information. What should the application do:
This code should perform a SQL SELECT Statement and provide the information which is stored in the MySQL Database.
{ <%@page import="java.sql.*"%>
<% Class.forName("com.mysql.jdbc.Driver");%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<%!
public class Actor{
String URL = "jdbc:mysql://localhost:3306/sakila";
String USERNAME = "root";
String PASSWORD = "admin";
Connection connection = null;
PreparedStatement selectActors = null;
ResultSet resultSet = null;
public Actor(){
try{
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sakila", "root", "MySQL2019.");
selectActors = connection.prepareStatement(
"SELECT actor_id, first_name, last_name FROM actor");
}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();
%>
<table border="1">
<tbody>
<tr>
<td>Actor ID</td>
<td>First Name</td>
<td>Last Name</td>
</tr>
<tr>
<% while (actors.next()) {%>
<td> <%= actors.getInt("actor_id")%> </td>
<td><%= actors.getString("first_name")%> </td>
<td><%= actors.getString("last_name")%> </td>
</tr>
<%}%>
</tbody>
</table>
</body>
</html> }
Problem code:
{<%
Actor actor = new Actor();
ResultSet actors = actor.getActors();
%> }