//Login Servlet //index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login Page</title> </head> <body> <h2>Login Page</h2> <form action="Logininit" method="post"> <label for="username">Username:</label><br> <input type="text" id="username" name="username" required><br><br> <label for="password">Password:</label><br> <input type="password" id="password" name="password" required><br><br> <input type="submit" value="Login"> </form> </body> </html> //LoginServletInit.java import java.io.IOException; import java.io.PrintWriter; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @WebServlet("/Logininit") public class LoginServletInit extends HttpServlet { private static final long serialVersionUID = 1L; // Define valid credentials directly in the servlet private final String validUsername = "ramesh"; private final String validPassword = "fattah"; public LoginServletInit() { // Default constructor } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); if (validUsername.equals(username) && validPassword.equals(password)) { out.println("<html><body>"); out.println("<h1>Login successful! Welcome, " + username + "</h1>"); out.println("</body></html>"); } else { out.println("<html><body>"); out.println("<h1>Invalid credentials. Please try again.</h1>"); out.println("<a href=\"index.html\">Go back to Login</a>"); out.println("</body></html>"); } out.close(); } }
Preview:
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