<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Account Details</title>
</head>
<body>
<h1>Account Details</h1>
<form method="post" action="addAccount.jsp">
Account Number: <input type="text" name="accountNumber" /><br>
Account Type: <input type="text" name="accountType" /><br>
Balance: <input type="text" name="balance" /><br>
<input type="submit" value="Add Account" />
</form>
<%-- Connect to database --%>
<%
String dbUrl = getServletContext().getInitParameter("db.url");
String dbUsername = getServletContext().getInitParameter("db.username");
String dbPassword = getServletContext().getInitParameter("db.password");
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
} catch (ClassNotFoundException | SQLException e) {
out.println("Failed to connect to database.");
e.printStackTrace();
return;
}
// Add account to database
String accountNumber = request.getParameter("accountNumber");
String accountType = request.getParameter("accountType");
double balance = Double.parseDouble(request.getParameter("balance"));
String sql = "INSERT INTO accounts (account_number, account_type, balance) VALUES (?, ?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, accountNumber);
statement.setString(2, accountType);
statement.setDouble(3, balance);
int rowsInserted = statement.executeUpdate();
statement.close();
if (rowsInserted > 0) {
out.println("Account added successfully.");
} else {
out.println("Failed to add account.");
}
// Display accounts from database
sql = "SELECT * FROM accounts";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sql);
out.println("<h2>Accounts</h2>");
out.println("<table border='1'>");
out.println("<tr><th>Account Number</th><th>Account Type</th><th>Balance</th></tr>");
while (rs.next()) {
String accNo = rs.getString("account_number");
String accType = rs.getString("account_type");
double accBal = rs.getDouble("balance");
out.println("<tr><td>" + accNo + "</td><td>" + accType + "</td><td>" + accBal + "</td></tr>");
}
out.println("</table>");
rs.close();
stmt.close();
connection.close();
%>
</body>
</html>
No comments:
Post a Comment