Preview:
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%
    // Hard-coded credentials
    String validUsername = "pk";
    String validPassword = "123";
    
    // Variables for handling login state
    boolean loginAttempt = request.getParameter("username") != null && request.getParameter("password") != null;
    boolean loginSuccess = false;
    boolean loginError = false;

    // Check if login form was submitted
    if (loginAttempt) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // Validate credentials
        if (validUsername.equals(username) && validPassword.equals(password)) {
            loginSuccess = true;
        } else {
            loginError = true;
        }
    }
%>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="ISO-8859-1">
    <title>Login Page</title>
</head>
<body>

<% if (!loginAttempt || loginError) { %>
    <!-- Display login form if not logged in or login failed -->
    <h2>Login Page</h2>
    <form action="loginjsp.jsp" method="post">
        Username:
        <input type="text" name="username" required><br><br>
        Password:
        <input type="password" name="password" required><br><br>
        <input type="submit" value="Login">
    </form>

    <!-- Display error message if login failed -->
    <% if (loginError) { %>
        <p style="color: red;">Invalid username or password! Please try again.</p>
    <% } %>

<% } else if (loginSuccess) { %>
    <!-- Display welcome message if login was successful -->
    <h1>Welcome, <%= request.getParameter("username") %>!</h1>
    <%
        // Display current date and time
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        Date date = new Date();
    %>
    <p>Current Date and Time: <%= formatter.format(date) %></p>
<% } %>

</body>
</html>
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter