Step 1: Create the HTML Login Form
Create an HTML file named login.html
. This file contains a form where users can enter their username and password.
<html>
<head>
<title>Login Form</title>
</head>
<body>
<h2>Login Form</h2>
<form action="login" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
Step 2: Create the Servlet to Handle Login Data
Now, create a new Java class named LoginServlet.java
. This servlet will handle the form submission and retrieve the data.
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Retrieve data from the login form
String username = request.getParameter("username");
String password = request.getParameter("password");
// For demonstration purposes, print the username and password
response.setContentType("text/html");
response.getWriter().println("<h1>Login Successful</h1>");
response.getWriter().println("<p>Username: " + username + "</p>");
response.getWriter().println("<p>Password: " + password + "</p>");
}
}
Step-by-Step Explanation
- HTML Form:
- The
<form>
tag has anaction
attribute set tologin
and amethod
attribute set topost
. This means that when the form is submitted, it will send a POST request to thelogin
URL. - The form contains two input fields: one for the username and one for the password, and a submit button.
- The
- LoginServlet:
- @WebServlet(“/login”): This annotation maps the servlet to the
/login
URL. When the form is submitted, this servlet will handle the request. - doPost Method: This method handles POST requests. It retrieves the username and password from the request using
request.getParameter()
. - Response: The servlet sets the response content type to
text/html
and sends back an HTML response displaying the entered username and password.
- @WebServlet(“/login”): This annotation maps the servlet to the
Step 3: Deploy Your Application
- Place
login.html
in the web directory (e.g.,webapps/your_project_name
if using Tomcat). - Compile and deploy
LoginServlet.java
as part of your web application. - Start your server (Tomcat) and navigate to
http://localhost:8080/your_project_name/login.html
in your web browser.
When you fill out the form and click the login button, the servlet will handle the request, retrieve the data, and display it back to you.