Advance Java ProgrammingUnit 19 min read
Servlets & JSP: Web Apps, Lifecycle & Scripting
Unit 1 of Advance Java Programming: Introduces Servlets (server-side Java programs) and JSP (dynamic web pages), their lifecycle, scripting elements, and real-world use in e-commerce (Daraz), banking (Ncell), and authentication (eSewa).
TAKEAWAYS:
- Servlets are Java programs that run on the server to handle HTTP requests (e.g., Daraz order processing).
- JSP embeds Java code in HTML to generate dynamic content (e.g., Ncell’s user dashboards).
- The Servlet lifecycle (init → service → destroy) mirrors a web server’s request-response cycle.
- Scripting elements (
<jsp:scriptlet>,<%= %>) and directives (<%@ %>) customize web pages without full Java classes. - Cookies store client-side data (e.g., eSewa session tracking).
- HTTPServletRequest/Response objects bridge HTTP and Java logic (e.g., Pathao’s ride requests).
1. Servlets: Server-Side Java for Web Apps
Servlets are Java programs that extend javax.servlet.http.HttpServlet to process HTTP requests (GET/POST) and generate responses. They run on a Servlet Container (e.g., Tomcat) and handle dynamic content like databases or user sessions.
Key Concepts
- Servlet Container: Manages servlet lifecycle (e.g., Tomcat, Jetty).
- HTTP Methods: Servlets respond to
GET,POST,PUT,DELETE. - Request/Response Objects:
HttpServletRequest: Parses input (e.g., form data).HttpServletResponse: Sends output (e.g., HTML, JSON).
Lifecycle of a Servlet
flowchart TD
A["Servlet Class Loaded"] --> B["init() Called"]
B --> C["service() Handles Requests"]
C -->|"Request Ends"| D["service() Returns"]
D --> E["destroy() Called (Optional)"]init(): Runs once when the servlet starts (e.g., loading database connections).service(): Processes each request (e.g., calculating factorial).destroy(): Cleans up resources (e.g., closing DB connections).
Example: Factorial Servlet
Servlet Code:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
```figure
{"type":"array","values":[1,1,2,6,24,120],"caption":"Factorial values for n = 0 to 5 (stored in an array in the servlet)"}
public class FactorialServlet extends HttpServlet { protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { int n = Integer.parseInt(req.getParameter("num")); int result = factorial(n); res.getWriter().write("Factorial of " + n + " is: " + result); }
private int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
}
**HTML Form (`factorial.html`)**:
```html
<form method="post" action="FactorialServlet">
Enter a number: <input type="text" name="num"><br>
<input type="submit" value="Calculate">
</form>
Trace Table:
| Step | n |
result |
Action |
|---|---|---|---|
Input: n=5 |
5 | - | doPost() called |
factorial(5) |
5 | 120 (5×4×3×2×1) | Recursion unwinds |
2. JSP: Embedding Java in HTML
JSP (JavaServer Pages) mixes Java code with HTML to generate dynamic web pages. It compiles to servlets behind the scenes.
Scripting Elements
| Tag | Example | Use Case |
|---|---|---|
<jsp:scriptlet> |
<jsp:scriptlet>int x=10;</jsp:> |
Embeds Java logic in HTML. |
<%= %> |
<%= "Hello" %> |
Outputs Java expressions directly. |
<% %> |
<% int y=20; %> |
Multi-line Java blocks. |
Directives
| Directive | Example | Purpose |
|---|---|---|
<%@ page %> |
<%@ page contentType="text/html"%> |
Sets MIME type. |
<%@ include %> |
<%@ include file="header.jsp"%> |
Includes another JSP file. |
Example: Greatest of Three Numbers
JSP Page (greatest.jsp):
<%@ page contentType="text/html" %>
<html>
<body>
<form method="post" action="GreatestServlet">
Enter three numbers:
<input type="text" name="num1"><br>
<input type="text" name="num2"><br>
<input type="text" name="num3"><br>
<input type="submit" value="Find Greatest">
</form>
<%!
int max = Math.max(Math.max(Integer.parseInt(request.getParameter("num1")),
Integer.parseInt(request.getParameter("num2"))),
Integer.parseInt(request.getParameter("num3")));
%>
<% if (max != 0) { %>
Greatest number: <%= max %>
<% } %>
</body>
</html>
State After Input:
num1=10, num2=20, num3=15 → max=20
Mermaid Flowchart: JSP Processing
flowchart TD
A["JSP File Requested"] --> B["JSP Engine Parses & Converts to Servlet Code"]
B --> C["Servlet Container Compiles to Bytecode"]
C --> D["Servlet Executes in Container"]
D --> E["Generates HTML Response to Client"]
E --> F["Response Sent to Browser"]3. Servlets vs. JSP
| Feature | Servlet | JSP |
|---|---|---|
| Definition | Pure Java class handling requests | Java embedded in HTML. |
| Extends | HttpServlet |
<%@ page %> directive. |
| Use Case | Complex logic (e.g., DB queries) | Dynamic HTML (e.g., user dashboards). |
| Performance | Faster (compiled once) | Slightly slower (compiled per request). |
Real-World Tie:
- Ncell’s App: Uses Servlets to process user login requests (validates credentials via
HttpServletRequest). - Daraz Orders: JSP dynamically displays product lists based on user searches.
4. Cookies in Servlets
Cookies store client-side data (e.g., session IDs). Servlets create/read cookies via HttpServletResponse/HttpServletRequest.
Example: Setting a Cookie
// In a servlet
Cookie cookie = new Cookie("user", "JohnDoe");
cookie.setMaxAge(60 * 60); // 1 hour
res.addCookie(cookie);
Reading a Cookie:
Cookie[] cookies = req.getCookies();
for (Cookie c : cookies) {
if (c.getName().equals("user")) {
System.out.println("User: " + c.getValue());
}
}
Use Case:
- eSewa: Stores user session tokens in cookies to track logged-in status.
5. HTTPServletRequest/Response
- Request: Parses form data, headers, and cookies.
String name = req.getParameter("username"); - Response: Sends headers (e.g., redirects) and content.
res.sendRedirect("welcome.jsp");
Example: Student Database Storage
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String roll = req.getParameter("roll");
String name = req.getParameter("name");
// Save to DB (e.g., JDBC)
res.sendRedirect("student_list.jsp");
}
In the Real World
Pathao’s Ride Requests:
- Servlets process GPS data from drivers to match riders (e.g.,
doPost()handles location updates). - JSP dynamically updates the app’s map UI with real-time driver locations.
- Servlets process GPS data from drivers to match riders (e.g.,
NEPSE Stock Trades:
- Cookies store user session IDs to track authenticated traders.
- HTTPServletRequest validates API calls for buying/selling stocks.
Khalti’s Payment Gateway:
- Directives in JSP customize checkout pages per user (e.g.,
<%@ include file="payment_form.jsp"%>). - Servlets process payment tokens and update transaction databases.
- Directives in JSP customize checkout pages per user (e.g.,
Worked Example: Daraz Order Queue
Scenario: Daraz’s backend uses a queue (simulated with a List) to process orders FIFO.
List<Order> orderQueue = new ArrayList<>();
orderQueue.add(new Order("User1", "Laptop"));
orderQueue.add(new Order("User2", "Phone"));
Servlet Processing:
protected void doGet(HttpServletRequest req, HttpServletResponse res) {
Order nextOrder = orderQueue.remove(0); // FIFO
res.getWriter().write("Processing: " + nextOrder.product);
}
State After Processing:
Queue: [User2:Phone] → [User1:Laptop] removed → [User2:Phone] processed next.
Exam Tip
- Compare Servlets/JSP: Always include a table (like above) to score full marks.
- Lifecycle: Draw the flowchart (init → service → destroy) and label each method’s role.
- Cookies: Show code snippets for setting and reading cookies.
- JSP Scripting: Use
<%= %>for output and<% %>for logic in examples. - Real-World Link: Tie answers to Ncell, Daraz, or eSewa (e.g., "Like Ncell’s login, servlets validate credentials").
Common Pitfalls:
- Forgetting
extends HttpServletin servlet code. - Mixing
<jsp:scriptlet>with<%= %>(use<%= %>for simple output). - Not initializing
response.getWriter()before writing.
Based on the TU BCA syllabus for Advance Java Programming (CACS354), unit 1.
Discussion
Loading…