Advanced Java ProgrammingUnit 610 min read
Java Servlets & JSP: APIs, JSP Lifecycle, MVC, and Form Handling
Unit 6 of Advanced Java Programming covers Java Servlets (APIs, lifecycle, session management) and JSP (scriplets, directives, implicit objects, and form processing). Learn how to build dynamic web apps using servlets for backend logic and JSP for presentation, with real-world examples from eSewa, Daraz, and Ncell.
TAKEAWAYS:
- Servlets are Java programs running on a server to handle client requests (e.g., processing Daraz orders).
- JSP embeds Java in HTML using scriplets (
<% ... %>), directives (<%@ ... %>), and implicit objects (request,response). - MVC pattern separates model (Java beans), view (JSP), and controller (Servlet) for scalable web apps.
- Form handling in JSP uses
<form>,action, andmethodattributes to submit data to servlets. - Session management tracks user state via
HttpSession(e.g., eSewa login sessions). - JSP access models (JSP 2.0+) simplify development by auto-generating servlets from JSP pages.
1. Servlets: The Backend Workhorse
Servlets are Java programs that run on a server to handle HTTP requests (GET/POST) and generate dynamic responses. They extend javax.servlet.http.HttpServlet and override doGet()/doPost() methods.
Key Servlet APIs
Servlets rely on APIs for core functionality. Here are four critical ones:
| API | Purpose | Example Use Case |
|---|---|---|
HttpServletRequest |
Accesses client data (headers, parameters, cookies). | Reading a Daraz order form submission. |
HttpServletResponse |
Sends responses (headers, cookies, content). | Redirecting to a payment page after checkout. |
ServletContext |
Shared data across all servlets (e.g., app-wide configurations). | Storing Ncell’s global user login count. |
HttpSession |
Maintains user-specific data across requests (e.g., shopping cart). | Tracking eSewa’s logged-in user’s session. |
Servlet Lifecycle
A servlet’s lifecycle has three phases:
- Initialization:
init()runs once when the servlet is loaded. - Request Handling:
service()dispatches todoGet()/doPost()per request. - Destruction:
destroy()cleans up resources before unloading.
flowchart TD
A["Servlet Loaded"] --> B["init()"]
B --> C["service()"]
C --> D["doGet()/doPost()"]
D --> C
C --> E["destroy()"]Example: Processing a Daraz Order
Scenario: A user submits an order form (product ID, quantity) to a servlet. The servlet validates input and forwards it to a JSP for confirmation.
// OrderServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String productId = request.getParameter("productId");
int quantity = Integer.parseInt(request.getParameter("quantity"));
// Validate
if (quantity <= 0) {
response.sendRedirect("error.jsp");
return;
}
// Forward to confirmation JSP
RequestDispatcher dispatcher = request.getRequestDispatcher("confirm.jsp");
dispatcher.forward(request, response);
}
Trace Table:
| Step | productId |
quantity |
Action |
|---|---|---|---|
| 1 | "DZ123" | 2 | Read form data |
| 2 | "DZ123" | 2 | Validate (pass) |
| 3 | "DZ123" | 2 | Forward to confirm.jsp |
2. JSP: Embedding Java in HTML
JSP (JavaServer Pages) mixes HTML with Java code to create dynamic web pages. Key features:
- Scriplets: Java code snippets (
<% ... %>). - Directives: Page/configuration settings (
<%@ page %>). - Implicit Objects: Predefined objects like
request,response,session. - JSP Access Models: Simplify development by auto-generating servlets.
JSP Syntax Examples
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>eSewa Payment</title></head>
<body>
<h1>Payment Confirmation</h1>
<%-- Scriplet to display user data --%>
<p>User: <%= session.getAttribute("userName") %></p>
<p>Amount: Rs. <%= request.getParameter("amount") %></p>
</body>
</html>
JSP Implicit Objects
| Object | Purpose | Example |
|---|---|---|
request |
Client request data (GET/POST parameters). | request.getParameter("email") |
response |
Send responses back to the client. | response.setHeader("Location", "...") |
session |
Track user-specific data across requests. | session.setAttribute("cart", items) |
application |
Shared data across all users/sessions. | application.setAttribute("count", 0) |
3. Form Handling in JSP
Forms in JSP use HTML <form> tags with action (servlet/JSP to process data) and method (GET/POST).
Example: Ncell Recharge Form
<!-- recharge.jsp -->
<form action="RechargeServlet" method="POST">
<label>Phone Number:</label>
<input type="text" name="phoneNumber" required>
<label>Amount:</label>
<input type="number" name="amount" required>
<button type="submit">Recharge</button>
</form>
Servlet (RechargeServlet.java):
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String phone = request.getParameter("phoneNumber");
double amount = Double.parseDouble(request.getParameter("amount"));
// Process recharge (pseudo-code)
if (validateRecharge(phone, amount)) {
response.sendRedirect("success.jsp?phone=" + phone);
} else {
response.sendRedirect("error.jsp");
}
}
Trace:
| Step | phoneNumber |
amount |
Action |
|---|---|---|---|
| 1 | "98XXXXXXXX" | 500.0 | Form submitted to servlet |
| 2 | "98XXXXXXXX" | 500.0 | Validate (pass) |
| 3 | "98XXXXXXXX" | 500.0 | Redirect to success.jsp |
4. JSP Access Models (JSP 2.0+)
JSP 2.0 introduced access models to simplify development by auto-generating servlets. The two models are:
| Model | Description | Use Case |
|---|---|---|
| Scripting | Traditional JSP with scriplets, expressions, and declarations. | Legacy apps (e.g., old NEPSE systems). |
| Expression | Uses EL (Expression Language) for cleaner syntax (e.g., ${user.name}). |
Modern apps (e.g., Daraz checkout). |
Example (EL in JSP):
<p>Welcome, ${user.name}! Your balance: Rs. ${user.balance}</p>
5. MVC Pattern in Servlets/JSP
The Model-View-Controller (MVC) pattern separates concerns:
- Model: Java beans (e.g.,
User,Order). - View: JSP pages (presentation).
- Controller: Servlets (handles requests, updates model, forwards to view).
Example Workflow (Pathao Ride Booking):
- View:
ride.jsp(user enters pickup/drop locations). - Controller:
RideServletvalidates input and callsRideModel. - Model:
RideModelcalculates fare and stores ride details. - View:
confirm.jspdisplays fare and ride details.
6. Session Management
Sessions track user state across requests using HttpSession. Example: eSewa login.
// LoginServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String username = request.getParameter("username");
HttpSession session = request.getSession();
session.setAttribute("user", username);
response.sendRedirect("dashboard.jsp");
}
JSP (dashboard.jsp):
<p>Welcome, ${sessionScope.user}!</p>
Trace:
| Step | username |
session State |
|---|---|---|
| 1 | "john" | {} |
| 2 | "john" | {"user": "john"} |
| 3 | - | {"user": "john"} (persists) |
In the Real World
eSewa (Nepal)
- Idea Used: Servlets + JSP + Session Management
- How: The backend uses servlets to process payments (e.g.,
PaymentServletvalidates transactions), while JSP pages (payment.jsp,confirm.jsp) handle the UI.HttpSessiontracks logged-in users to prevent duplicate payments.
Daraz (Nepal)
- Idea Used: MVC Pattern + Form Handling
- How: The Model stores product/inventory data, the Controller (
OrderServlet) processes cart submissions, and the View (JSP pages) displays products and order confirmations. Forms submit toOrderServlet, which validates and forwards toconfirm.jsp.
Ncell Recharge Portal
- Idea Used: JSP Implicit Objects + Servlets
- How: The recharge form (
recharge.jsp) uses<form action="RechargeServlet">to submit data. The servlet readsrequest.getParameter("phoneNumber")andrequest.getParameter("amount"), then redirects to a success/error page based on validation.
Exam Tip
Define Key Terms Precisely:
- Scriplets: Java code snippets in JSP (
<% ... %>). - JSP Access Models: Scripting (traditional) vs. Expression (EL-based).
- MVC: Separate model (Java beans), view (JSP), and controller (Servlet).
- Scriplets: Java code snippets in JSP (
Code Examples Are Mandatory:
- Always include a servlet (
doGet()/doPost()) and a JSP snippet in answers. - Trace tables (like the Daraz order example) earn partial marks even if code is missing.
- Always include a servlet (
Common Pitfalls:
- Forgetting to validate form data (e.g., checking
quantity > 0). - Not using
RequestDispatcher.forward()vs.response.sendRedirect()correctly. - Mixing scriptlets with EL without explanation.
- Forgetting to validate form data (e.g., checking
Diagrams Save Marks:
- Draw the servlet lifecycle or MVC flow in exams. Label all components (e.g.,
init(),service(),Model,View). - Show state changes (e.g., session attributes before/after login).
- Draw the servlet lifecycle or MVC flow in exams. Label all components (e.g.,
Real-World Tie-Ins:
- Relate servlets to eSewa payments, JSP to Daraz product pages, and sessions to Ncell login.
- Example: "Like Daraz’s checkout, our
OrderServletvalidates input before forwarding toconfirm.jsp."
Based on the TU BIT syllabus for Advanced Java Programming (BIT401), unit 6.
Discussion
Loading…