Skip to content
Unit 3 Syllabus Note· Web Technologies

Web Technologies

Comprehensive exam revision notes for BCA-303N Unit 3 (Web Servers, Java Servlet Architecture & Session Management). Includes Section A (2M), Section B (5M), and Section C (15M) questions, answers, and diagrams.

Web Technologies

Web Servers, Java Servlet Architecture & Session Management

Core Definitions & Key Concepts

What is a Java Servlet and what container executes it

A Servlet is a Java class that executes on a web/application server to handle client HTTP requests and generate dynamic responses. It runs inside a Servlet Container / Web Container such as Apache Tomcat or Eclipse Jetty.

The Servlet Life Cycle methods

  1. init(ServletConfig config): Called once when the servlet is first instantiated and loaded.
  2. service(ServletRequest req, ServletResponse res): Called for each client request; dispatches to doGet(), doPost(), etc.
  3. destroy(): Called once when the servlet is unloaded to clean up resources.

What is the difference between GenericServlet and HttpServlet

  • GenericServlet: Protocol-independent servlet abstract class implementing Servlet and ServletConfig.
  • HttpServlet: Extends GenericServlet and is specialized for the HTTP protocol, providing lifecycle methods doGet(), doPost(), doPut(), doDelete().

What is the role of the web.xml deployment descriptor

web.xml is the standard configuration file in WEB-INF/ that maps servlet classes to URL patterns (<servlet> and <servlet-mapping>), specifies context parameters, filters, session timeouts, and security constraints.

RequestDispatcher.forward() and HttpServletResponse.sendRedirect()

Dimensionforward()sendRedirect()
Execution LocationServer-sideClient-side (Browser receives 302/303)
Browser Address BarURL does not changeURL changes to the new destination
HTTP RequestsSingle request (attributes preserved)Two separate HTTP requests (attributes lost)
Destination ScopeOnly within same web applicationCan redirect to any external domain

Name the four classic Session Tracking mechanisms in Java Servlets

  1. Cookies (`javax.servlet.http.Cookie`)
  2. HttpSession API
  3. URL Rewriting (appending ;jsessionid=...)
  4. Hidden Form Fields (<input type="hidden">)

How do you obtain an HttpSession in a Servlet without creating a new one if it doesn't exist

By calling request.getSession(false). Passing false returns the existing session or null if none exists; passing true (or default request.getSession()) creates a new session if none exists.

What is a Servlet Filter

A Filter is a pluggable Java component (javax.servlet.Filter) that intercepts requests and responses to perform pre-processing (authentication, logging, compression) and post-processing before reaching the target servlet.

Servlet Thread Model and Thread Safety

A single servlet instance handles multiple concurrent requests in separate threads. Instance variables are shared across all threads; thus, declaring mutable instance variables in a servlet creates severe thread-safety bugs. Developers should use local variables inside doGet()/doPost().

What is the ServletContext object

ServletContext is an application-wide object shared across all servlets in a web application. It stores global parameters and application-scoped attributes (setAttribute(), getAttribute()).

Conceptual & Architectural Analysis

The Complete Servlet Life Cycle Architecture with an ASCII Diagram

System Architecture / Concept DiagramHorizontal Scroll Enabled
[ CLIENT BROWSER ]               [ WEB SERVER / TOMCAT CONTAINER ]
       |                                      |
       | --- 1. HTTP Request (/login) ------> | 
       |                                      | -> 2. Checks if Servlet loaded
       |                                      | -> If NOT loaded:
       |                                      |    a. Loads Servlet Class
       |                                      |    b. Instantiates Servlet object
       |                                      |    c. Calls init(ServletConfig)
       |                                      |
       |                                      | -> 3. Spawns new worker Thread
       |                                      | -> 4. Calls service(req, res)
       |                                      | -> 5. Dispatches to doGet()/doPost()
       | <-- 6. Returns HTTP Response -------- |
       |                                      |
       |                                      | [ On Server Shutdown / Redeploy ]
       |                                      | -> 7. Calls destroy()
  • init() and destroy() execute exactly once in a servlet's lifecycle, whereas service() executes for every incoming request.

Compare Cookies vs HttpSession for Session State Management in Java

AttributeCookiesHttpSession
Storage LocationClient Browser (Text file)Server Memory / Heap
Data CapacityMax 4 KB per cookieServer memory dependent (Megabytes)
Data TypesStrings onlyAny Java Object (Serializable)
SecurityVulnerable to client tamperingSecure (client holds only 32-char session ID)
Traffic OverheadTransmitted with every HTTP headerOnly Session ID cookie is transmitted

The Structure and Configuration of web.xml for Servlet Mapping

System Architecture / Concept DiagramHorizontal Scroll Enabled
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="3.1">
  
  <!-- Servlet Definition -->
  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.mjpru.bca.LoginController</servlet-class>
    <init-param>
      <param-name>maxAttempts</param-name>
      <param-value>3</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <!-- URL Mapping -->
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/auth/login</url-pattern>
  </servlet-mapping>

  <!-- Global Context Parameter -->
  <context-param>
    <param-name>universityName</param-name>
    <param-value>MJP Rohilkhand University</param-value>
  </context-param>
</web-app>

Servlet Filters and their Interception Pipeline (doFilter)

A Filter implements javax.servlet.Filter with methods init(), doFilter(), and destroy().

System Architecture / Concept DiagramHorizontal Scroll Enabled
Request ---> [ Filter 1: Auth ] ---> [ Filter 2: Logging ] ---> [ Target Servlet ]
                                                                       |
Response <-- [ Filter 1: Auth ] <--- [ Filter 2: Logging ] <-----------+
  • Inside doFilter(req, res, chain), pre-processing code executes, then chain.doFilter(req, res) passes control to the next filter/servlet, followed by post-processing code.

URL Rewriting for Session Tracking when Cookies are Disabled

If the client disables cookies, the session ID cannot be sent via Cookie: JSESSIONID=....

  • Solution: Servlets use URL Rewriting by wrapping all hyperlink and redirect URLs in:
  • response.encodeURL("target.jsp") \to outputs target.jsp;jsessionid=3A84BC...
  • response.encodeRedirectURL("profile.jsp")
  • The servlet container intercepts the ;jsessionid path parameter and associates it with the caller's HttpSession.

In-Depth Analysis & Implementation

Develop a Complete Enterprise Java Servlet Demonstrating Session Tracking, Authentication, and Cookies

System Architecture / Concept DiagramHorizontal Scroll Enabled
package com.mjpru.bca;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/PortalServlet")
public class PortalServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        // Retrieve existing session without creating a new one
        HttpSession session = request.getSession(false);

        if (session == null || session.getAttribute("user_name") == null) {
            // User is not logged in
            response.sendRedirect("login.html");
            return;
        }

        String userName = (String) session.getAttribute("user_name");
        Integer visitCount = (Integer) session.getAttribute("visit_count");
        if (visitCount == null) visitCount = 1;
        else visitCount++;
        session.setAttribute("visit_count", visitCount);

        out.println("<!DOCTYPE html>");
        out.println("<html><head><title>BCA Student Portal</title></head><body>");
        out.println("<h1>Welcome back, " + userName + "!</h1>");
        out.println("<p>Session ID: <code>" + session.getId() + "</code></p>");
        out.println("<p>Session Creation Time: " + new java.util.Date(session.getCreationTime()) + "</p>");
        out.println("<p>Total Visits This Session: <strong>" + visitCount + "</strong></p>");
        out.println("<p><a href='PortalServlet?action=logout'>Logout</a></p>");
        out.println("</body></html>");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String user = request.getParameter("username");
        String pass = request.getParameter("password");

        // Simplified credentials verification
        if ("mjpru_student".equals(user) && "pass123".equals(pass)) {
            // Establish Session
            HttpSession session = request.getSession(true);
            session.setAttribute("user_name", user);
            session.setMaxInactiveInterval(15 * 60); // 15 minutes timeout

            // Add a Persistent Cookie for User Preference
            Cookie userPrefCookie = new Cookie("remember_user", user);
            userPrefCookie.setMaxAge(7 * 24 * 60 * 60); // 7 days expiration
            userPrefCookie.setHttpOnly(true); // Protect against XSS theft
            response.addCookie(userPrefCookie);

            response.sendRedirect("PortalServlet");
        } else {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<h3 style='color:red;'>Invalid Username or Password!</h3>");
            out.println("<a href='login.html'>Try Again</a>");
        }
    }
}

The RequestDispatcher Architecture: forward() vs include() with Flow Diagrams and Context Attribute Passing

Request Dispatcher Mechanics

System Architecture / Concept DiagramHorizontal Scroll Enabled
[ FORWARD MECHANISM ]
Client ---> [ Servlet A ]
                 | (request.setAttribute("key", data))
                 |-- RequestDispatcher.forward(req, res) --> [ Servlet B / JSP ]
                                                                    |
Client <------------------- Generates Final Response ---------------+ (Servlet A halts)

[ INCLUDE MECHANISM ]
Client ---> [ Servlet A ]
                 |
                 |-- RequestDispatcher.include(req, res) --> [ Header / Footer JSP ]
                 |                                                  |
                 | <------- Appends partial content to buffer ------+
                 |
Client <---------+ Generates Combined Response

Key Differences:

  1. `forward()`: Transfers execution permanently to another resource. The calling servlet must not have committed the response buffer. Ideal for MVC controllers forwarding to View JSPs.
  2. `include()`: Incorporates the output of a secondary resource into the main response (e.g., reusable headers, banners, copyright footers).

Detail the Implementation of an Authentication and Logging Servlet Filter

Java
1package com.mjpru.bca.filters;
2
3import java.io.IOException;
4import javax.servlet.*;
5import javax.servlet.annotation.WebFilter;
6import javax.servlet.http.HttpServletRequest;
7import javax.servlet.http.HttpServletResponse;
8import javax.servlet.http.HttpSession;
9
10@WebFilter("/secure/*") // Intercepts all requests under /secure/
11public class SecurityFilter implements Filter {
12
13 @Override
14 public void init(FilterConfig filterConfig) throws ServletException {
15 System.out.println("SecurityFilter initialized successfully.");
16 }
17
18 @Override
19 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
20 throws IOException, ServletException {
21 HttpServletRequest req = (HttpServletRequest) request;
22 HttpServletResponse res = (HttpServletResponse) response;
23
24 long startTime = System.currentTimeMillis();
25 System.out.println("[LOG] Request received: " + req.getMethod() + " " + req.getRequestURI());
26
27 HttpSession session = req.getSession(false);
28 boolean loggedIn = (session != null && session.getAttribute("user_name") != null);
29
30 if (!loggedIn) {
31 System.out.println("[WARN] Unauthorized access attempt intercepted!");
32 res.sendRedirect(req.getContextPath() + "/login.html");
33 return; // Halt chain
34 }
35
36 // Pass request to next filter or destination servlet
37 chain.doFilter(request, response);
38
39 long duration = System.currentTimeMillis() - startTime;
40 System.out.println("[LOG] Request completed in " + duration + " ms.");
41 }
42
43 @Override
44 public void destroy() {
45 System.out.println("SecurityFilter destroyed.");
46 }
47}

Important Exam Points & Quick Revision

Examiners frequently ask: Servlet Life Cycle with diagram (10 marks Section C), forward vs sendRedirect, and Session tracking techniques.

Your reading progress
0%

100% left on this page — finishing it closes the gap for Web Servers, Java Servlet Architecture & Session Management.

Weak topic hint

Web Servers, Java Servlet Architecture & Session Management still counts as a weak topic until you finish this note and answer its questions.

Practise this unit
What Should You Do Next?

Test Your Understanding

Now that you've read through these notes, practice unit MCQs to identify weak points and solidify your learning before exams.