Advanced Programming with JavaUnit 105 min read
Servlets, JSP, and Web Application Architecture
Unit 10 of Advanced Programming with Java covers server-side programming with Servlets (request handling, lifecycle, and configuration) and JSP (scriptlets, directives, and implicit objects), how they interact with HTML/CSS/JS, and their role in MVC architecture. Includes JDBC integration, session management, and deplo
Servlets: The Backbone of Dynamic Web Pages
What is a Servlet?
A Servlet is a Java program that runs on a web server, handling client requests (HTTP) and generating dynamic responses. Unlike static HTML, servlets process data, interact with databases, and manage sessions.
Key Features:
- Extend
javax.servlet.http.HttpServlet. - Handle HTTP methods (
doGet,doPost, etc.). - Run in a servlet container (e.g., Apache Tomcat).
Servlet Lifecycle
stateDiagram-v2
[*] --> Init: load()
Init --> Service: service()
Service --> Destroy: destroy()
Service --> Service: handle requests
Service --> [*]Example: A Simple Servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<h1>Hello, World!</h1>");
}
}
Trace: Servlet Execution
| Step | Action | Output (Response) |
|---|---|---|
| 1 | Client sends GET /hello |
(No output yet) |
| 2 | Tomcat routes to doGet() |
res.setContentType() |
| 3 | PrintWriter writes HTML |
<h1>Hello, World!</h1> |
JSP: Java in HTML Pages
What is JSP?
JavaServer Pages (JSP) embed Java code inside HTML using scriptlets, expressions, and directives. JSP files (.jsp) are compiled to servlets by the container.
JSP Syntax:
<%@ page contentType="text/html" %>
<html>
<head><title>JSP Example</title></head>
<body>
<h1>Current Time: <%= new java.util.Date() %></h1>
</body>
</html>
Implicit Objects in JSP:
| Object | Purpose |
|---|---|
request |
HTTP request data |
response |
HTTP response generation |
session |
User session tracking |
application |
Global application scope |
Servlet vs. JSP: A Comparison
| Feature | Servlet | JSP |
|---|---|---|
| Purpose | Business logic, request handling | Presentation logic (HTML + Java) |
| Syntax | Java code in .java files |
HTML with embedded Java |
| Use Case | Complex processing (e.g., DB) | Simple dynamic pages |
| Performance | Faster (pre-compiled) | Slower (compiled at runtime) |
Real-World Applications
1. eSewa (Nepal)
- Servlets/JSP Role: Handles payment processing (e.g.,
PaymentServletvalidates transactions). - How: When you pay a bill, the request hits a servlet that checks your balance (via JDBC) and updates the database.
2. Khalti Checkout
- JSP Role: Dynamically generates the payment confirmation page with user details.
- Example: After a successful transaction, a JSP renders:
<h2>Thank you, <%= userName %>!</h2> <p>Transaction ID: <%= transactionId %></p>
3. Nepal Stock Exchange (NEPSE) Portal
- Servlets: Fetch real-time stock data from a database and serve it via
StockDataServlet. - JSP: Displays the data in a table with live updates.
MVC Architecture with Servlets/JSP
classDiagram
class Model {
+processData()
}
class View {
+render()
}
class Controller {
+handleRequest()
}
Controller --> Model : forwards request
Model --> Controller : returns data
Controller --> View : sends data
View --> Client : displays outputExample: MVC for a Blog
- Controller (
BlogServlet):protected void doGet(HttpServletRequest req, HttpServletResponse res) { BlogModel model = new BlogModel(); req.setAttribute("posts", model.getPosts()); req.getRequestDispatcher("/view/posts.jsp").forward(req, res); } - View (
posts.jsp):<%@ page import="java.util.List" %> <ul> <% List<Post> posts = (List<Post>) request.getAttribute("posts"); %> <% for (Post p : posts) { %> <li><%= p.getTitle() %></li> <% } %> </ul>
Session Management
How It Works
HttpSessiontracks user state across requests.- Stored in the server’s memory (or a distributed cache).
Example: Shopping Cart
// Servlet: Add item to cart
HttpSession session = req.getSession();
List<String> cart = (List<String>) session.getAttribute("cart");
if (cart == null) cart = new ArrayList<>();
cart.add(itemId);
session.setAttribute("cart", cart);
// JSP: Display cart
<h3>Your Cart (<%= session.getAttribute("cart").size() %> items)</h3>
Exam Tip
- Servlet Lifecycle: Remember
init(),service(), anddestroy()methods. - JSP Implicit Objects: Know
request,response, andsessionfor short-answer questions. - MVC Flow: Draw the diagram and explain how data moves between layers.
- Session Tracking: Use
HttpSessionfor user-specific data (e.g., login status). - Error Handling: Always include
throws ServletException, IOExceptionin servlet methods.
Visual Summary:
flowchart TD
A["Client Request"] --> B["Servlet Container"]
B --> C["Servlet: doGet/doPost"]
C --> D["JSP: Render HTML"]
D --> E["Client Response"]
C --> F["Database/JDBC"]
F --> CBased on the PU BE Computer (PU) syllabus for Advanced Programming with Java (CMP228), unit 10.
Discussion
Loading…