Issue
I am practicing to create my own JDBC CRUD web app by studying online... However, when I tried to test it, no data is being shown in my index.jsp and I cannot locate the error in my code. I checked/reworked my code over and over, looked at the console for any errors but still nothing happens. It made me hesitate to continue coding for the remaining CRUD ops.
I am having a hard time because I think that I properly passed the listBooks object in the jsp to the servlet, or have I not?
Here is my Controller Servlet:
@WebServlet("/BookServlet")
public class BookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private BookDAO bkDAO;
public void init() {
String jdbcURL = getServletContext().getInitParameter("jdbcURL");
String jdbcUsername = getServletContext().getInitParameter("jdbcUsername");
String jdbcPassword = getServletContext().getInitParameter("jdbcPassword");
bkDAO = new BookDAO(jdbcURL, jdbcUsername, jdbcPassword);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getServletPath();
try {
switch(action) {
case "/new":
showNewForm(request, response);
break;
case "/insert":
insertBook(request, response);
break;
case "/delete":
break;
case "/edit":
break;
case "/update":
break;
default:
bookcollection(request, response);
break;
}
}catch(SQLException e) {
throw new ServletException(e);
}
}
private void bookcollection(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException, ServletException{
//list object from the Data Access Object
List<BookCollectionModel> listBooks = bkDAO.listBooks();
request.setAttribute("listBooks", listBooks);
RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
dispatcher.forward(request, response);
}
private void showNewForm (HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException, ServletException{
RequestDispatcher dispatcher = request.getRequestDispatcher("BookForm.jsp");
dispatcher.forward(request, response);
}
private void insertBook (HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException, ServletException{
int bookID = Integer.parseInt(request.getParameter("bookID"));
String title = request.getParameter("title");
String author = request.getParameter("author");
String publisher = request.getParameter("publisher");
String edition = request.getParameter("edition");
int pages = Integer.parseInt(request.getParameter("pages"));
int year = Integer.parseInt(request.getParameter("year"));
int price = Integer.parseInt(request.getParameter("price"));
BookCollectionModel newBook = new BookCollectionModel(bookID, title, author, publisher, edition, pages, year, price);
bkDAO.insertBook(newBook);
response.sendRedirect("list");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
My Data Access Object Code:
public class BookDAO {
private String jdbcURL;
private String jdbcUsername;
private String jdbcPassword;
private Connection jdbcConnection;
public BookDAO(String jdbcURL, String jdbcUsername, String jdbcPassword) {
this.jdbcURL = jdbcURL;
this.jdbcUsername = jdbcUsername;
this.jdbcPassword = jdbcPassword;
}
protected void connect() throws SQLException{
if(jdbcConnection == null || jdbcConnection.isClosed()) {
try {
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundException e) {
throw new SQLException(e);
}
jdbcConnection = DriverManager.getConnection(jdbcURL, jdbcUsername, jdbcPassword);
}
}
protected void disconnect() throws SQLException{
if(jdbcConnection != null && jdbcConnection.isClosed()) {
jdbcConnection.close();
}
}
public List<BookCollectionModel> listBooks() throws SQLException{
List<BookCollectionModel> listBooks = new ArrayList<>();
String sql = "SELECT * FROM bookinformation ORDER BY title";
//create statement for connection
Statement statement = jdbcConnection.createStatement();
//result set contains the records retrieved on executing the SQL.
ResultSet resultSet = statement.executeQuery(sql);
//looping all the records on the result set
while(resultSet.next()) {
int id = resultSet.getInt("bookID");
String title = resultSet.getString("title");
String author = resultSet.getString("author");
String publisher = resultSet.getString("publisher");
String edition = resultSet.getString("edition");
int pages = resultSet.getInt("pages");
int year = resultSet.getInt("year");
int price = resultSet.getInt("price");
BookCollectionModel books = new BookCollectionModel(id, title, author, publisher, edition, pages, year, price);
listBooks.add(books);
}
resultSet.close();
statement.close();
disconnect();
return listBooks;
}
public boolean insertBook (BookCollectionModel newBook) throws SQLException{
String sql = "INSERT INTO bookinformation (bookID, title, author, publisher, edition, pages, year, price) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
connect();
PreparedStatement statement = jdbcConnection.prepareStatement(sql);
statement.setInt(1, newBook.getBookID());
statement.setString(2, newBook.getTitle());
statement.setString(3, newBook.getAuthor());
statement.setString(4, newBook.getPublisher());
statement.setString(5, newBook.getEdition());
statement.setInt(6, newBook.getPages());
statement.setInt(7, newBook.getYear());
statement.setInt(8, newBook.getPrice());
boolean rowInserted = statement.executeUpdate() > 0;
statement.close();
disconnect();
return rowInserted;
}
}
Here is my index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Book Collection DB</title>
</head>
<body>
<center>
<h1>Book Management</h1>
<h2>
<a href="/BookCollectionJDBC/new">Add New Account</a>
<a href="/BookCollectionJDBC/list">List All Accounts</a>
</h2>
<div align="center">
<table border="1" cellpadding="5">
<caption><h2>List of Books</h2>
<tr>
<th>Book ID</th>
<th>Title</th>
<th>Author</th>
<th>Publisher</th>
<th>Edition</th>
<th>Pages</th>
<th>Year</th>
<th>Price</th>
</tr>
<c:forEach var="books" items="${listBooks}">
<tr>
<td><c:out value="${books.bookID}"></c:out></td>
<td><c:out value="${books.title}"></c:out></td>
<td><c:out value="${books.author}"></c:out></td>
<td><c:out value="${books.publisher}"></c:out></td>
<td><c:out value="${books.edition}"></c:out></td>
<td><c:out value="${books.pages}"></c:out></td>
<td><c:out value="${books.year}"></c:out></td>
<td><c:out value="${books.price}"></c:out></td>
<td>
<a href="/BookCollectionJDBC/edit?id=<c:out value='${books.bookID}'/>">Edit</a>
<a href="/BookCollectionJDBC/delete?id=<c:out value='${books.bookID}'/>">Delete</a>
</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
Here is my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">
<display-name>BookCollectionJDBC</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>jdbcURL</param-name>
<param-value>jdbc:mysql://localhost:3306/bookcollectiondb</param-value>
</context-param>
<context-param>
<param-name>jdbcUsername</param-name>
<param-value>root</param-value>
</context-param>
<context-param>
<param-name>jdbcPassword</param-name>
<param-value>123456</param-value>
</context-param>
<servlet>
<servlet-name>BookServlet</servlet-name>
<servlet-class>com.model.BookServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BookServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Solution
I tried to review programming again with this code...
Code was fine as kameshrsr said. I just missed to call connect() in my Data Access Object Code.
This was my code before:
public List<BookCollectionModel> listBooks() throws SQLException{
List<BookCollectionModel> listBooks = new ArrayList<>();
String sql = "SELECT * FROM bookinformation ORDER BY title";
//create statement for connection
Statement statement = jdbcConnection.createStatement();
//result set contains the records retrieved on executing the SQL.
ResultSet resultSet = statement.executeQuery(sql);
It should be:
public List<BookCollectionModel> listBooks() throws SQLException{
List<BookCollectionModel> listBooks = new ArrayList<>();
String sql = "SELECT * FROM bookinformation ORDER BY title";
connect(); //I missed this part
//create statement for connection
Statement statement = jdbcConnection.createStatement();
//result set contains the records retrieved on executing the SQL.
ResultSet resultSet = statement.executeQuery(sql);
Answered By - mkcvs