我已按照BalusC的回复来解决我的问题
How do I make a Java ResultSet available in my jsp?
现在,当我运行page.jsp时,我收到此错误
org.apache.jasper.JasperException: javax.el.PropertyNotFoundException: Property 'name' not readable on type java.lang.String
请您建议解决方案。
我也跟着下面没有运气。
javax.el.PropertyNotFoundException: using JSTL in JSP
page.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html" pageEncoding="UTF-8" import="java.util.List"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<c:forEach items="${rows}" var="row">
<c:out value="${row.name}" />
</c:forEach>
<c:if test="${not empty error}">Error: ${error}</c:if>
</body>
</html>
Controller.java
public class Controller extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
List<Row> rows = Row.list();
//request.getSession().setAttribute("rows", rows);
request.setAttribute("rows", rows);
} catch (SQLException e) {
request.setAttribute("error", "Retrieving rows failed.");
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
finally {System.out.print("servlet");}
request.getRequestDispatcher("page.jsp").forward(request, response);
}
}
Row.java
import javax.naming.*;
import javax.sql.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class Row {
private String name;
private String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static List<Row> list() throws SQLException {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
List<Row> rows = new ArrayList<Row>();
try {
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource)
envCtx.lookup("jdbc/TestDB");
connection = ds.getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery("select id, name from account");
while (resultSet.next()) {
Row row = new Row();
row.setName(resultSet.getString("name"));
rows.add(row);
}
} catch(Exception e) {
e.printStackTrace();
}
finally {
if (resultSet != null) try { resultSet.close(); }
catch (SQLException logOrIgnore) {}
if (statement != null) try { statement.close(); }
catch (SQLException logOrIgnore) {}
if (connection != null) try { connection.close(); }
catch (SQLException logOrIgnore) {}
}
return rows;
}
}
非常感谢 穆罕默德
答案 0 :(得分:1)
您的getter
是private
private String getName() {
return name;
}
不可见
将其更改为public
public String getName() {
return name;
}