User Registration System
Learn the complete flow from JSP form submission to database storage and response handling. This covers parameter handling, validation, OOP structure, and MVC architecture.
System Overview
We'll build a simple user registration system to demonstrate the INSERT operation flow. Users can register with just their username, email, and password to learn the JSP → Servlet → SQL → JSP process.
Complete Registration Flow
Step 1: Database Schema
First, let's create the database table to store user information:
-- Create users table for property rental system
CREATE TABLE users (
user_id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
email VARCHAR(255) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);Step 2: User Model Class
Create a User model class following OOP principles:
package model;
public class User {
private int userId;
private String username;
private String email;
private String password;
private String createdAt;
// Default constructor
public User() {}
// Constructor with parameters
public User(String username, String email, String password) {
this.username = username;
this.email = email;
this.password = password;
}
// Getters and Setters
public int getUserId() { return userId; }
public void setUserId(int userId) { this.userId = userId; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
public String getCreatedAt() { return createdAt; }
public void setCreatedAt(String createdAt) { this.createdAt = createdAt; }
}Step 3: JSP Registration Form
Create the user interface for registration.
Key Focus: Notice the form's action, method, and name attributes that will be used for parameter extraction.
Form Analysis - Parameter Flow
Form Action: action="UserController" - This tells the form where to submit data
Form Method: method="post" - Uses POST method for data submission
Parameter Names: Each input has a name attribute that becomes the parameter name
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<title>User Registration</title>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
.form-group { margin-bottom: 15px; }
label { display: block; margin-bottom: 5px; font-weight: bold; }
input, textarea { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; }
button { background: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; }
button:hover { background: #0056b3; }
.error { color: red; margin-top: 5px; }
.success { color: green; margin-top: 5px; }
</style>
</head>
<body>
<h2>User Registration</h2>
<!-- Display messages from controller -->
<% if (request.getAttribute("errorMessage") != null) { %>
<div class="error"><%= request.getAttribute("errorMessage") %></div>
<% } %>
<% if (request.getAttribute("successMessage") != null) { %>
<div class="success"><%= request.getAttribute("successMessage") %></div>
<% } %>
<!-- FORM SUBMISSION: action="UserController" method="post" -->
<form action="UserController" method="post">
<div class="form-group">
<label for="username">Username:</label>
<!-- PARAMETER: name="username" becomes request.getParameter("username") -->
<input type="text" id="username" name="username" required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<!-- PARAMETER: name="email" becomes request.getParameter("email") -->
<input type="email" id="email" name="email" required>
</div>
<div class="form-group">
<label for="password">Password:</label>
<!-- PARAMETER: name="password" becomes request.getParameter("password") -->
<input type="password" id="password" name="password" required>
</div>
<!-- ACTION PARAMETER: name="action" value="register" for controller routing -->
<button type="submit" name="action" value="register">Register</button>
</form>
</body>
</html>Key Points to Remember
- • Form Action: Points to the servlet that will handle the request
- • Method POST: Sends data securely in the request body
- • Simple Fields: Only username, email, and password for rental system
- • Action Parameter: Helps the controller determine which method to execute
- • Request Attributes: Used to display messages from the controller
Step 4: UserDAO - Data Access Object
Handle database operations with proper error handling.
Key Focus: SQL queries, prepared statements, and object-to-database mapping.
DAO Operations - SQL Queries
1. User Registration: INSERT INTO users (username, email, password) VALUES (?, ?, ?)
2. Object Mapping: Map User object properties to SQL parameters
3. Database Insert: Execute prepared statement and check affected rows
package model_dao;
import database.DBConnection;
import model.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDAO {
// SQL QUERY: Register new user
public static boolean registerUser(User user) throws ClassNotFoundException {
// SQL QUERY: INSERT with simplified parameters
String sql = "INSERT INTO users (username, email, password) VALUES (?, ?, ?)";
try (Connection conn = DBConnection.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
// OBJECT-TO-DATABASE MAPPING: Map User object properties to SQL parameters
stmt.setString(1, user.getUsername()); // username
stmt.setString(2, user.getEmail()); // email
stmt.setString(3, user.getPassword()); // password
// EXECUTION: Execute update and check affected rows
int rowsAffected = stmt.executeUpdate();
return rowsAffected > 0;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
}DAO Key Concepts
- • SQL INSERT: Simple INSERT operation to add new user
- • Prepared Statements: Safe parameter binding to prevent SQL injection
- • Object Mapping: Map User object properties to SQL parameters
- • Database Insert: Execute statement and check if successful
- • Error Handling: Basic exception handling for database operations
Step 5: UserController - Servlet
Handle HTTP requests and coordinate between view and model.
Key Focus: Parameter extraction, OOP object initialization, and request/session handling.
Controller Flow - Parameter to Object
1. Parameter Extraction: request.getParameter("name") gets form data
2. OOP Initialization: new User(...) creates object from parameters
3. DAO Call: Pass the object to DAO for database operations
4. Request Attributes: request.setAttribute() for passing data to JSP
package controller;
import model.User;
import model_dao.UserDAO;
import java.io.IOException;
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;
@WebServlet("/UserController")
public class UserController extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// PARAMETER EXTRACTION: Get action parameter to determine which method to call
String action = request.getParameter("action");
if ("register".equals(action)) {
try {
registerUser(request, response);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
// REQUEST ATTRIBUTE: Set error message for JSP display
request.setAttribute("errorMessage", "Registration failed. Please try again.");
request.getRequestDispatcher("register.jsp").forward(request, response);
}
}
}
private void registerUser(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ClassNotFoundException, SQLException {
// STEP 1: PARAMETER EXTRACTION FROM FORM
// These match the 'name' attributes from the JSP form
String username = request.getParameter("username"); // From: <input name="username">
String email = request.getParameter("email"); // From: <input name="email">
String password = request.getParameter("password"); // From: <input name="password">
// Simple validation - just check if fields are not empty
if (username == null || username.trim().isEmpty() ||
email == null || email.trim().isEmpty() ||
password == null || password.trim().isEmpty()) {
request.setAttribute("errorMessage", "All fields are required.");
request.getRequestDispatcher("register.jsp").forward(request, response);
return;
}
// STEP 2: OOP OBJECT INITIALIZATION
// Create User object using constructor with parameters from form
User user = new User(username.trim(), email.trim(), password.trim());
// STEP 3: DAO CALL - Pass object to DAO for database operations
boolean success = UserDAO.registerUser(user);
if (success) {
// REQUEST ATTRIBUTE: Set success message for JSP
request.setAttribute("successMessage", "Registration successful! You can now login.");
// RESPONSE: Forward to login page
request.getRequestDispatcher("login.jsp").forward(request, response);
} else {
// REQUEST ATTRIBUTE: Set error message for JSP
request.setAttribute("errorMessage", "Registration failed. Please try again.");
// RESPONSE: Forward back to registration page
request.getRequestDispatcher("register.jsp").forward(request, response);
}
}
}Controller Key Concepts
- • Parameter Extraction:
request.getParameter("name")gets form data by name attribute - • OOP Constructor:
new User(...)creates object from extracted parameters - • Request Attributes:
request.setAttribute()passes data to JSP - • Response Handling:
forward()orsendRedirect()for navigation - • DAO Integration: Pass object to DAO for database operations
Step 6: Session & Request Handling
Understanding session concepts, request attributes, and data flow between controller and JSP.
Key Focus: Session management, request.setAttribute(), and response handling.
Session & Request Flow
1. Request Attributes: request.setAttribute() - Pass data to JSP
2. Session Management: request.getSession() - Maintain user state
3. Response Handling: forward() vs sendRedirect()
4. Data Retrieval: JSP accesses data using request.getAttribute()
// ENHANCED CONTROLLER WITH SESSION HANDLING FOR REGISTRATION
private void registerUser(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ClassNotFoundException, SQLException {
// ... parameter extraction and validation ...
// STEP 1: CREATE USER OBJECT (OOP)
User user = new User(username.trim(), email.trim(), password.trim());
// STEP 2: DAO CALL
boolean success = UserDAO.registerUser(user);
if (success) {
// REQUEST ATTRIBUTE: Pass success message to JSP
request.setAttribute("successMessage", "Registration successful! You can now login.");
// SESSION MANAGEMENT: Store user in session after successful registration
request.getSession().setAttribute("user", user);
request.getSession().setAttribute("isLoggedIn", true);
// RESPONSE: Forward to login page (keeps request attributes)
request.getRequestDispatcher("login.jsp").forward(request, response);
} else {
// REQUEST ATTRIBUTE: Pass error message to JSP
request.setAttribute("errorMessage", "Registration failed. Please try again.");
// RESPONSE: Forward back to registration page
request.getRequestDispatcher("register.jsp").forward(request, response);
}
}Session & Request Key Concepts
- • Request Attributes:
request.setAttribute()- Pass data within same request - • Session Attributes:
session.setAttribute()- Store user data after successful registration - • Forward vs Redirect: Forward keeps request, redirect creates new request
- • Registration Flow: Store user data in session after successful registration
- • Data Flow: Controller → Request/Session → JSP → User Interface
Step 7: Database Connection
Create a database connection utility class:
package database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection {
private static final String URL = "jdbc:mysql://localhost:3306/rental_system";
private static final String USERNAME = "root";
private static final String PASSWORD = "your_password";
public static Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
return DriverManager.getConnection(URL, USERNAME, PASSWORD);
}
}Step 8: JSP Data Retrieval & Response Handling
How JSP retrieves data from controller and displays it to users.
Key Focus: request.getAttribute(), session.getAttribute(), and response display.
JSP Data Retrieval Methods
1. Request Attributes: <%= request.getAttribute("name") %> - Data from current request
2. Session Attributes: <%= session.getAttribute("name") %> - Persistent user data
3. Object Access: Cast objects and access properties using getters
4. Conditional Display: Show/hide content based on data availability
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="model.User" %>
<!DOCTYPE html>
<html>
<head>
<title>User Dashboard</title>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
.success { color: green; margin-bottom: 20px; padding: 10px; background: #d4edda; border: 1px solid #c3e6cb; border-radius: 4px; }
.error { color: red; margin-bottom: 20px; padding: 10px; background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 4px; }
.user-info { background: #f8f9fa; padding: 20px; border-radius: 4px; margin: 20px 0; }
.logout-btn { background: #dc3545; color: white; padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer; }
</style>
</head>
<body>
<h2>User Dashboard</h2>
<!-- REQUEST ATTRIBUTE: Display registration messages from controller -->
<% if (request.getAttribute("successMessage") != null) { %>
<div class="success">
<strong>Success:</strong> <%= request.getAttribute("successMessage") %>
</div>
<% } %>
<% if (request.getAttribute("errorMessage") != null) { %>
<div class="error">
<strong>Error:</strong> <%= request.getAttribute("errorMessage") %>
</div>
<% } %>
<!-- SESSION CHECK: Verify user is registered and logged in -->
<%
Boolean isLoggedIn = (Boolean) session.getAttribute("isLoggedIn");
if (isLoggedIn != null && isLoggedIn) {
%>
<!-- SESSION ATTRIBUTE: Get registered user data from session -->
<%
User user = (User) session.getAttribute("user");
%>
<div class="user-info">
<h3>Registration Successful!</h3>
<p><strong>Username:</strong> <%= user.getUsername() %></p>
<p><strong>Email:</strong> <%= user.getEmail() %></p>
<p><strong>Registered:</strong> <%= user.getCreatedAt() %></p>
</div>
<% } else { %>
<!-- REGISTRATION STATUS: User not registered -->
<div class="error">
<strong>Registration Required:</strong> Please complete the registration process.
</div>
<a href="register.jsp">Go to Registration</a>
<% } %>
</body>
</html>JSP Data Retrieval Key Concepts
- • Request Attributes:
<%= request.getAttribute("name") %>- Registration messages from controller - • Session Attributes:
<%= session.getAttribute("name") %>- Registered user data - • Object Casting: Cast User objects to display registration details
- • Null Checks: Always check if attributes exist before using
- • Registration Status: Show content based on registration completion
Complete Flow Explanation
Here's how the complete registration process works:
1. User Fills Registration Form (JSP)
User enters their registration information in the form. The form submits to UserController with action="register".
2. Registration Controller Processing
UserController receives the registration request, extracts parameters, validates input, and creates a User object.
3. Database Registration (DAO)
UserDAO inserts the new user into the database using prepared statements.
4. Database Response to DAO
Database returns success/failure status to DAO, which returns boolean to Controller.
5. Controller Response Handling
Controller sets registration success/error messages as request attributes and forwards to appropriate JSP page.
6. JSP Response to User
JSP displays success message with user details or error message back to the user.
Key Concepts Learned
- • Parameter Extraction - Getting form data using request.getParameter()
- • Basic Validation - Simple check for required fields
- • OOP Structure - Creating User object from form data
- • DAO Pattern - Database insertion through DAO
- • Prepared Statements - Safe SQL execution to prevent SQL injection
- • Database Insert - Simple INSERT operation to store user data
- • Request Attributes - Passing success/error messages to JSP
- • MVC Architecture - Clear separation of concerns
Next Steps
Now that you understand the INSERT operation flow, the next steps will focus on other CRUD operations:
- • SELECT Operations - Retrieve and display user information after login
- • UPDATE Operations - Edit user profile and update information
- • DELETE Operations - Remove user accounts and data
- • Property Management - Complete CRUD for property listings
- • Advanced Features - File uploads, complex relationships, and joins