【发布时间】:2023-03-06 09:20:01
【问题描述】:
我正在尝试从 JavaBean ProductDataBean.java 中获取 ShowProductCatalog.jsp 中 List (List productList = data.getProductList();) 的值。我收到错误空指针异常。我不知道出了什么问题。请帮忙!
**ShowProductCatalog.jsp**
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import = "java.util.*" import="cart.*,java.net.*,java.text.*"%>
<jsp:useBean id="data" scope="session" class="cart.ProductDataBean" />
<!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=ISO-8859-1">
</head>
<body>
<%
List productList = data.getProductList();
Iterator prodListIterator = productList.iterator();
%>
**ProductDataBean.java**
package cart;
import java.io.*;
import java.sql.*;
import java.util.*;
public class ProductDataBean implements Serializable{
private static Connection connection;
private PreparedStatement addRecord, getRecords;
public ProductDataBean(){
try{
// Step1: Load JDBC Driver
Class.forName("com.mysql.jdbc.Driver");
// Step 2: Define Connection URL
String connURL ="jdbc:mysql://localhost/onlineshop?user=root&password=teck1577130713";
// Step 3: Establish connection to URL
connection = DriverManager.getConnection(connURL);
}catch(Exception e){e.printStackTrace();}
}
public static Connection getConnection(){
return connection;
}
public ArrayList getProductList() throws SQLException{
ArrayList productList = new ArrayList();
Statement statement = connection.createStatement();
ResultSet results = statement.executeQuery("SELECT * FROM products");
while (results.next()){
DVD movie = new DVD();
movie.setMovie(results.getString("movieName"));
movie.setRating(results.getString("movieRate"));
movie.setYear(results.getString("movieYear"));
movie.setPrice(results.getDouble("moviePrice"));
productList.add(movie);
}
return productList;
}
}
【问题讨论】:
-
好的,我意识到我在 getProductList() 中的 ProductDataBean.java 中检索的连接为空。但是如何进行更改以将值放入?
标签: java jsp model-view-controller get connection