Show JDBC ResultSet in HTML table in JSP page using MVC pattern - NullPointerException
You are getting this error because the init()
method on your UsuarioDAO
is never called and this line
List<Usuario> retorno = usrDAO.list();
returns null
.
Try to usrDAO.init()
before calling the list.
The reason probably because UsuarioDAO
is not a httpServlet
so the init()
method is not running on creation
How do I make a Java ResultSet available in my jsp?
Model (Row):
public class Row {
private String name;
// Add/generate constructor(s), getters and setters.
}
DAO:
public List<Row> list() throws SQLException {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
List<Row> rows = new ArrayList<Row>();
try {
connection = database.getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery(SQL_LIST);
while (resultSet.next()) {
Row row = new Row();
row.setName(resultSet.getString("name"));
// ...
rows.add(row);
}
} 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;
}
Controller (servlet):
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List<Row> rows = someDAO.list();
request.setAttribute("rows", rows);
} catch (SQLException e) {
request.setAttribute("error", "Retrieving rows failed.");
e.printStackTrace();
}
request.getRequestDispatcher("page.jsp").forward(request, response);
}
View (page.jsp):
<c:forEach items="${rows}" var="row">
<c:out value="${row.name}" />
...
</c:forEach>
<c:if test="${not empty error}">Error: ${error}</c:if>
Related Topics
Why Don't Java'S +=, -=, *=, /= Compound Assignment Operators Require Casting
How to Download and Save a File from the Internet Using Java
What Is the Java : Operator Called and What Does It Do
How to Generate a Random Alpha-Numeric String
Variable Might Not Have Been Initialized Error
Java 256-Bit Aes Password-Based Encryption
Is There an Eval() Function in Java
How to Check If a String Is Numeric in Java
Change Private Static Final Field Using Java Reflection
What's the Difference Between Next() and Nextline() Methods from Scanner Class
How to Read a Single Char from the Console in Java (As the User Types It)
How to Use the Tostring Method in Java
How to Get the Insert Id in Jdbc
Create Instance of Generic Type in Java
Why Doesn't Java Allow Overriding of Static Methods
Java_Home and Path Are Set But Java -Version Still Shows the Old One