DEV Community

Cover image for Building an ATM Project with JSP and Servlets in Step-by-Step Guide 2024
Nikhil Soman Sahu
Nikhil Soman Sahu

Posted on

5

Building an ATM Project with JSP and Servlets in Step-by-Step Guide 2024

Creating a full production-ready ATM project involves several components, including servlets, JSP pages, database connectivity, and proper error handling. Below, I'll provide a simplified version of each component along with code snippets. Please note that this is a basic example and may require further enhancement for a real-world production environment.

Database Configuration (DBUtil.java)

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBUtil {
    private static final String URL = "jdbc:mysql://localhost:3306/atm";
    private static final String USERNAME = "your_username";
    private static final String PASSWORD = "your_password";

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USERNAME, PASSWORD);
    }
}
Enter fullscreen mode Exit fullscreen mode

LoginServlet.java

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

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;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String accountNumber = request.getParameter("accountNumber");
        String pin = request.getParameter("pin");

        try (Connection conn = DBUtil.getConnection()) {
            String sql = "SELECT * FROM accounts WHERE account_number = ? AND pin = ?";
            try (PreparedStatement statement = conn.prepareStatement(sql)) {
                statement.setString(1, accountNumber);
                statement.setString(2, pin);
                ResultSet resultSet = statement.executeQuery();

                if (resultSet.next()) {
                    HttpSession session = request.getSession();
                    session.setAttribute("accountNumber", accountNumber);
                    response.sendRedirect("dashboard.jsp");
                } else {
                    response.sendRedirect("login.jsp?error=1");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.sendRedirect("login.jsp?error=2");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

dashboard.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@ page import="javax.servlet.http.HttpSession" %>
<%@ page import="DBUtil" %>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>ATM Dashboard</title>
</head>
<body>
    <h1>Welcome to ATM Dashboard</h1>
    <%
        HttpSession session = request.getSession();
        String accountNumber = (String) session.getAttribute("accountNumber");
        try {
            Connection conn = DBUtil.getConnection();
            String sql = "SELECT * FROM accounts WHERE account_number = ?";
            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setString(1, accountNumber);
            ResultSet resultSet = statement.executeQuery();
            if (resultSet.next()) {
                out.println("Account Number: " + resultSet.getString("account_number") + "<br>");
                out.println("Balance: $" + resultSet.getDouble("balance") + "<br>");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            out.println("Error fetching account details.");
        }
    %>
    <a href="logout.jsp">Logout</a>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

logout.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="javax.servlet.http.HttpSession" %>

<%
    HttpSession session = request.getSession();
    session.invalidate();
    response.sendRedirect("login.jsp");
%>
Enter fullscreen mode Exit fullscreen mode

login.jsp (with error handling)

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
    <h1>Login</h1>
    <%
        String error = request.getParameter("error");
        if (error != null && error.equals("1")) {
            out.println("<p style='color: red;'>Invalid account number or PIN</p>");
        } else if (error != null && error.equals("2")) {
            out.println("<p style='color: red;'>Database connection error</p>");
        }
    %>
    <form action="login" method="post">
        Account Number: <input type="text" name="accountNumber"><br>
        PIN: <input type="password" name="pin"><br>
        <input type="submit" value="Login">
    </form>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

This is a basic setup for an ATM project using JSP and servlets. Make sure to handle exceptions, validate user inputs, and implement security measures before deploying this project into a production environment.

you can visit this github repo for source code - Source Code

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (1)

Collapse
 
nikhilxd profile image
Nikhil Soman Sahu

ATM Application is a web-based application built using Java that utilizes servlet for business logic and JSP for presentation layer. With this application, users can perform all the operations that can be performed on a real ATM machine.

Another Github Repo For you guys

Creditt - Vivek

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay