9.
Design a login page using servlets and validate the username and password by
comparing the details stored in the database. CREATE DATABASE UserDB;
1. Database Setup (MySQL):
CREATE DATABASE UserDB;
USE UserDB;
CREATE TABLE users (
username VARCHAR(50) PRIMARY KEY,
password VARCHAR(50) NOT NULL
);
2. index.html (Login Form):
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login</h2>
<form action="LoginServlet" 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>
</body>
</html>
3. LoginServlet.java (Servlet Code):
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class LoginServlet extends HttpServlet {
static final String JDBC_URL = "jdbc:mysql://localhost:3306/UserDB";
static final String DB_USER = "root"; // your MySQL username
static final String DB_PASS = "password"; // your MySQL password
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Set content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Read form fields
String username = request.getParameter("username");
String password = request.getParameter("password");
try {
// Load Driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Connect to database
Connection conn = DriverManager.getConnection(JDBC_URL, DB_USER,
DB_PASS);
// Prepare statement
String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2, password);
// Execute query
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
out.println("<h2>Login Successful! Welcome " + username + "</h2>");
} else {
out.println("<h2>Login Failed! Invalid username or password.</h2>");
}
conn.close();
} catch (Exception e) {
out.println("<h3>Error: " + e.getMessage() + "</h3>");
}
}
}
4. web.xml (Deployment Descriptor):
<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="3.0">
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:
Scenario Output
Correct credentials Login Successful! Welcome [username]
Wrong credentials Login Failed! Invalid username or password.
Database not connected Error: [error details]