<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<%@ page import="java.util.ArrayList"%>
<%@ page import="java.util.List"%>
<%@ page import="book.mgmt.entities.Book"%>
<%@ page import="book.mgmt.entities.Cart"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Payment</title>
<link href="css/style.css" type="text/css" rel="stylesheet">
<style>
body {
font-family: 'Arial', sans-serif;
background-color: #f4f4f9;
margin: 0;
padding: 0;
}
.header {
background-color: #ff7200;
color: #ffffff;
padding: 15px;
text-align: center;
font-size: 35px;
font-weight: bold;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
position: relative;
}
.header .button-home {
position: absolute;
top: 50%;
left: 20px;
transform: translateY(-50%);
background-color: #28a745;
color: #ffffff;
padding: 10px 15px;
border: none;
border-radius: 6px;
cursor: pointer;
text-decoration: none;
font-size: 14px;
transition: background-color 0.3s ease;
}
.header .button-home:hover {
background-color: #218838;
}
.container {
max-width: 1200px;
margin: 20px auto;
padding: 20px;
background-color: #ffffff;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
table {
width: 100%;
border-collapse: collapse;
margin-bottom: 20px;
}
th, td {
border: 1px solid #ddd;
padding: 12px;
text-align: center;
}
th {
background-color: #ff7200;
color: white;
font-size: 18px;
font-weight: bold;
}
td {
font-size: 16px;
}
.total-price {
font-size: 18px;
font-weight: bold;
margin: 20px 0;
}
.card-details, .address-section {
margin-top: 20px;
padding: 20px;
background-color: #f9f9f9;
border-radius: 8px;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}
.card-details h3, .address-section h3 {
margin-bottom: 15px;
font-size: 20px;
color: #ff7200;
}
.card-details label, .address-section label {
font-size: 16px;
font-weight: bold;
display: block;
margin-bottom: 5px;
}
.card-details input[type="text"], .address-section input[type="text"] {
width: calc(100% - 22px);
padding: 10px;
font-size: 16px;
border: 1px solid #ddd;
border-radius: 4px;
margin-bottom: 10px;
}
.payment-section {
margin-top: 20px;
}
.payment-section input[type="text"] {
width: calc(100% - 22px);
padding: 10px;
font-size: 16px;
border: 1px solid #ddd;
border-radius: 4px;
margin-bottom: 10px;
}
.payment-section label {
font-size: 16px;
font-weight: bold;
display: block;
margin-bottom: 5px;
}
.payment-section .button {
background-color: #007bff;
color: #ffffff;
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s ease;
}
.payment-section .button:hover {
background-color: #0056b3;
}
.error-message {
color: #dc3545;
font-size: 16px;
margin-top: 10px;
}
.quantity-controls {
display: flex;
align-items: center;
gap: 10px;
}
.quantity-controls button {
background-color: #007bff;
color: #ffffff;
padding: 5px 10px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
}
.quantity-controls button:hover {
background-color: #0056b3;
}
.quantity-input {
width: 60px;
text-align: center;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 16px;
}
.empty-cart {
font-size: 18px;
color: #333;
text-align: center;
padding: 20px;
}
</style>
</head>
<body>
<div class="header">
Payment Details
<a href="Customerhome.jsp" class="button-home">< Back to Home</a>
</div>
<div class="container">
<%
HttpSession session1 = request.getSession();
List<Cart> shoppingCart = (List<Cart>)
session1.getAttribute("shoppingCart");
double totalPrice = 0.0;
if (shoppingCart == null) {
shoppingCart = new ArrayList<>();
} else {
for (Cart cart : shoppingCart) {
Book book = cart.getBook();
totalPrice += book.getPrice() * cart.getQuantity();
}
}
%>
<h2>Order Summary</h2>
<% if (shoppingCart != null && !shoppingCart.isEmpty()) { %>
<form id="payment-form" action="PaymentServlet1" method="post"
onsubmit="return validateForm()">
<table>
<thead>
<tr>
<th>Barcode</th>
<th>Name</th>
<th>Quantity</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<% for (Cart cart : shoppingCart) {
Book book = cart.getBook();
double bookPrice = book.getPrice();
int quantity = cart.getQuantity();
%>
<tr>
<td><%= book.getBarcode() %></td>
<td><%= book.getName() %></td>
<td>
<div class="quantity-controls">
<button type="button" onclick="updateQuantity('<%=
book.getId() %>', -1)">-</button>
<input type="text" id="quantity_<%= book.getId()
%>" class="quantity-input" value="<%= quantity %>" readonly>
<button type="button" onclick="updateQuantity('<%=
book.getId() %>', 1)">+</button>
</div>
</td>
<td>₹ <span id="price_<%= book.getId() %>" data-
price="<%= bookPrice %>"><%= String.format("%.2f", bookPrice * quantity)
%></span></td>
</tr>
<% } %>
</tbody>
</table>
<div class="total-price">Total Price: ₹ <span id="total-price"><
%= String.format("%.2f", totalPrice) %></span></div>
<div id="message" class="error-message"></div>
<div class="card-details">
<h3>Enter Payment Details</h3>
<label for="cardNumber">Card Number:</label>
<input type="text" id="cardNumber" name="cardNumber"
placeholder="1234 5678 9876 5432">
<label for="expiryDate">Expiry Date:</label>
<input type="text" id="expiryDate" name="expiryDate"
placeholder="MM/YY">
<label for="cvv">CVV:</label>
<input type="text" id="cvv" name="cvv" placeholder="123">
</div>
<div class="address-section">
<h3>Shipping Address</h3>
<label for="fullName">Full Name:</label>
<input type="text" id="fullName" name="fullName" placeholder="Full
Name">
<label for="address">Address:</label>
<input type="text" id="address" name="address"
placeholder="Address">
<label for="state">Select State:</label>
<input type="text" id="state" name="state" placeholder="Select
State">
<label for="pincode">Pincode:</label>
<input type="text" id="pincode" name="pincode"
placeholder="Pincode">
<label for="phoneNumber">Phone Number:</label>
<input type="text" id="phoneNumber" name="phoneNumber"
placeholder="Phone Number">
</div>
<div class="payment-section">
<label for="totalAmount">Amount to Pay:</label>
<input type="text" id="totalAmount" name="totalAmount"
value="₹ <%= String.format("%.2f", totalPrice) %>" readonly>
<button type="submit" class="button">Confirm Payment</button>
</div>
</form>
<% } else { %>
<div class="empty-cart">
Your cart is empty. Please add some items to the cart before proceeding
to payment.
</div>
<% } %>
</div>
<script>
function updateQuantity(bookId, change) {
var quantityInput = document.getElementById('quantity_' + bookId);
var quantity = parseInt(quantityInput.value) + change;
if (quantity >= 1) {
quantityInput.value = quantity;
var priceElement = document.getElementById('price_' + bookId);
var pricePerUnit = parseFloat(priceElement.getAttribute('data-price'));
priceElement.textContent = (pricePerUnit * quantity).toFixed(2);
updateTotalPrice();
}
}
function updateTotalPrice() {
var totalPrice = 0;
var priceElements = document.querySelectorAll('[id^="price_"]');
priceElements.forEach(function(element) {
totalPrice += parseFloat(element.textContent);
});
document.getElementById('total-price').textContent =
totalPrice.toFixed(2);
// Update the Amount to Pay field with the total price
document.getElementById('totalAmount').value = "₹ " +
totalPrice.toFixed(2);
}
function validateForm() {
const cardNumber = document.getElementById('cardNumber').value;
const expiryDate = document.getElementById('expiryDate').value;
const cvv = document.getElementById('cvv').value;
const fullName = document.getElementById('fullName').value;
const address = document.getElementById('address').value;
const state = document.getElementById('state').value;
const pincode = document.getElementById('pincode').value;
const phoneNumber = document.getElementById('phoneNumber').value;
const messageElement = document.getElementById('message');
let isValid = true;
messageElement.textContent = '';
if (!cardNumber.match(/^\d{4} \d{4} \d{4} \d{4}$/)) {
messageElement.textContent += 'Card number is invalid. ';
isValid = false;
}
if (!expiryDate.match(/^\d{2}\/\d{2}$/)) {
messageElement.textContent += 'Expiry date is invalid. ';
isValid = false;
}
if (!cvv.match(/^\d{3}$/)) {
messageElement.textContent += 'CVV is invalid. ';
isValid = false;
}
if (fullName.trim() === '') {
messageElement.textContent += 'Full Name is required. ';
isValid = false;
}
if (address.trim() === '') {
messageElement.textContent += 'Address is required. ';
isValid = false;
}
if (state.trim() === '') {
messageElement.textContent += 'State is required. ';
isValid = false;
}
if (pincode.trim() === '' || !pincode.match(/^\d{6}$/)) {
messageElement.textContent += 'Pincode is required and must be 6
digits. ';
isValid = false;
}
if (phoneNumber.trim() === '' || !phoneNumber.match(/^\d{10}$/)) {
messageElement.textContent += 'Phone number is required and must be
10 digits. ';
isValid = false;
}
return isValid;
}
</script>
</body>
</html>
SERVLET _--
package book.mgmt.controllers;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import book.mgmt.entities.Cart;
import book.mgmt.utils.DbUtils;
@WebServlet("/PaymentServlet1")
public class PaymentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
// Get payment details from the request
String cardNumber = request.getParameter("cardNumber");
String expiryDate = request.getParameter("expiryDate");
String cvv = request.getParameter("cvv");
String fullName = request.getParameter("fullName");
String address = request.getParameter("address");
String pincode = request.getParameter("pincode");
String phoneNumber = request.getParameter("phoneNumber");
// Validate inputs
if (cardNumber == null || expiryDate == null || cvv == null || fullName ==
null || address == null || pincode == null || phoneNumber == null ||
cardNumber.isEmpty() || expiryDate.isEmpty() || cvv.isEmpty() ||
fullName.isEmpty() || address.isEmpty() || pincode.isEmpty() ||
phoneNumber.isEmpty()) {
request.setAttribute("errorMessage", "All fields are required!");
request.getRequestDispatcher("payment.jsp").forward(request, response);
return;
}
// Validate format of inputs
if (!cardNumber.matches("\\d{16}") || !expiryDate.matches("(0[1-9]|1[0-
2])/\\d{2}") || !cvv.matches("\\d{3}") || !pincode.matches("\\d{6}") || !
phoneNumber.matches("\\d{10}")) {
request.setAttribute("errorMessage", "Invalid input format!");
request.getRequestDispatcher("payment.jsp").forward(request, response);
return;
}
// Get shopping cart from session
List<Cart> shoppingCart = (List<Cart>)
session.getAttribute("shoppingCart");
if (shoppingCart == null || shoppingCart.isEmpty()) {
request.setAttribute("errorMessage", "Your cart is empty!");
request.getRequestDispatcher("payment.jsp").forward(request, response);
return;
}
// Calculate total amount
BigDecimal totalAmount = BigDecimal.ZERO;
List<String> bookNames = new ArrayList<>();
List<String> barcodes = new ArrayList<>();
try (Connection conn = DbUtils.getConnection()) {
conn.setAutoCommit(false);
// Save order details
String orderQuery = "INSERT INTO Orders (fullName, address, pincode,
phoneNumber, cardNumber, expiryDate, cvv, barcode, bookName, quantity, price,
status, orderDate) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement psOrder = conn.prepareStatement(orderQuery)) {
String updateQuery = "UPDATE Inventory SET quantity = quantity - ?
WHERE barcode = ?";
try (PreparedStatement psUpdate =
conn.prepareStatement(updateQuery)) {
for (Cart cart : shoppingCart) {
psOrder.setString(1, fullName);
psOrder.setString(2, address);
psOrder.setString(3, pincode);
psOrder.setString(4, phoneNumber);
psOrder.setString(5, cardNumber); // Encrypt/hash in
production
psOrder.setString(6, expiryDate);
psOrder.setString(7, cvv); // Encrypt/hash in production
psOrder.setString(8, cart.getBook().getBarcode());
psOrder.setString(9, cart.getBook().getName());
psOrder.setInt(10, cart.getQuantity()); // Set the quantity
for each book
BigDecimal price =
BigDecimal.valueOf(cart.getBook().getPrice());
psOrder.setBigDecimal(11, price);
psOrder.setString(12, "Success");
psOrder.setTimestamp(13, new
java.sql.Timestamp(System.currentTimeMillis()));
psOrder.addBatch();
// Update quantity in the inventory
psUpdate.setInt(1, cart.getQuantity());
psUpdate.setString(2, cart.getBook().getBarcode());
psUpdate.addBatch();
// Calculate total amount
totalAmount =
totalAmount.add(price.multiply(BigDecimal.valueOf(cart.getQuantity())));
// Store book name and barcode for the success page
bookNames.add(cart.getBook().getName());
barcodes.add(cart.getBook().getBarcode());
}
psOrder.executeBatch();
psUpdate.executeBatch();
}
}
conn.commit();
session.removeAttribute("shoppingCart"); // Clear cart after successful
payment
// Set attributes for JSP
request.setAttribute("fullName", fullName);
request.setAttribute("address", address);
request.setAttribute("pincode", pincode);
request.setAttribute("phoneNumber", phoneNumber);
request.setAttribute("bookNames", bookNames);
request.setAttribute("barcodes", barcodes);
request.setAttribute("totalAmount", totalAmount);
// Forward to success page
request.getRequestDispatcher("Success.jsp").forward(request, response);
} catch (SQLException e) {
e.printStackTrace(); // Log error details
request.setAttribute("errorMessage", "Payment processing failed! " +
e.getMessage());
request.getRequestDispatcher("payment.jsp").forward(request, response);
}
}
}