CMP228 Advanced Programming with Java

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., PaymentServlet validates 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 output

Example: MVC for a Blog

  1. 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);
    }
    
  2. 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

  • HttpSession tracks 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

  1. Servlet Lifecycle: Remember init(), service(), and destroy() methods.
  2. JSP Implicit Objects: Know request, response, and session for short-answer questions.
  3. MVC Flow: Draw the diagram and explain how data moves between layers.
  4. Session Tracking: Use HttpSession for user-specific data (e.g., login status).
  5. Error Handling: Always include throws ServletException, IOException in 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 --> C

Based on the PU BE Computer (PU) syllabus for Advanced Programming with Java (CMP228), unit 10.

Discussion

Loading…