Assignment 5
Assignment 5
USE bookdb;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Database credentials
String jdbcURL = "jdbc:mysql://localhost:3306/bookdb";
String dbUser = "root";
String dbPassword = "your_password"; // Replace with your MySQL password
try {
Class.forName("com.mysql.cj.jdbc.Driver"); // Load MySQL JDBC driver
Connection conn = DriverManager.getConnection(jdbcURL, dbUser, dbPassword);
out.println("<tr><th>ID</th><th>Title</th><th>Author</th><th>Price</th><th>Quantity</th></tr
>");
while (rs.next()) {
out.println("<tr>");
out.println("<td>" + rs.getInt("book_id") + "</td>");
out.println("<td>" + rs.getString("book_title") + "</td>");
out.println("<td>" + rs.getString("book_author") + "</td>");
out.println("<td>" + rs.getFloat("book_price") + "</td>");
out.println("<td>" + rs.getInt("quantity") + "</td>");
out.println("</tr>");
}
out.println("</table>");
out.println("</body></html>");
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
out.println("<h3>Error: " + e.getMessage() + "</h3>");
} finally {
out.close();
}
}
}
1. Place the servlet code in your servlet container (e.g., Apache Tomcat) inside the
src folder.
2. Compile it using a Java compiler.
3. Add the MySQL Connector JAR (mysql-connector-java-8.x.x.jar) to your
lib folder.
4. Deploy the project on your server.
5. Access via browser:
http://localhost:8080/your_project_name/viewbooks