MySQL DB server used. Database name: library
, table name: book
.
table contains the following columns with given type and order:
title(varchar),
author(varchar),
book_id(int)- primary key,
count (int),
favs (int).
I want to view all the records of this table using ArrayList
in servlet
and JSP
.
Here are my codes:
ViewBook (servlet)
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.*;
import p1.*;
public class ViewBook extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException
{
PrintWriter out=res.getWriter();
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3307/library", "root", "admin");
PreparedStatement ps=con.prepareStatement("select * from book");
ResultSet rs=ps.executeQuery();
ArrayList<Book> books=new ArrayList<Book>();
while(rs.next())
{
Book b= new Book();
b.bookID=rs.getInt(3);
b.bookTitle=rs.getString(1);
b.bookAuthor=rs.getString(2);
b.bookCopies=rs.getInt(4);
b.bookFavs=rs.getInt(5);
books.add(b);
}
req.setAttribute("bookslist",books);
con.close();
RequestDispatcher rd=req.getRequestDispatcher("/view_book.jsp");
rd.forward(req,res);
}
catch(Exception e)
{
out.println(e);
}
}
}
Package p1 contains the following class:
Book.java
package p1;
public class Book
{
public int bookFavs,bookID, bookCopies;
public String bookTitle;
public String bookAuthor;
}
The JSP to which the request is dispatched- view_book.jsp:
<html>
<body>
<head>
<title>
View Books
</title>
</head>
<body>
<table border=2>
<tr>
<th>Book ID</th>
<th>Title</th>
<th>Author</th>
<th>No. of copies AVAILABLE</th>
<th>Number of favourites</th>
</tr>
<%
ArrayList<Book> dbooks=(ArrayList)request.getAttribute("bookslist");
Iterator it=dbooks.iterator();
while(it.hasNext())
{
Book b=(Book)it.next();
%>
<tr>
<td><%=b.bookID%></td>
<td><%=b.bookTitle%></td>
<td><%=b.bookAuthor%></td>
<td><%=b.bookCopies%></td>
<td><%=b.bookFavs%></td>
</tr>
<%
}
%>
</table>
</body>
</html>
The servlet and JSP aren't working. I know it's a vague question. Please point the blunders made. And solutions if possible!