1. What is a Servlet?

A Servlet is a Java class that runs on a web server. Its job is simple: receive an HTTP request from a browser, process it, and send back an HTTP response.

Think of it like this: when you fill out a login form on a website and click "Submit," that request goes to a Servlet on the server. The Servlet checks your credentials, talks to a database if needed, and sends back either a "Welcome" page or an "Invalid login" page.

Key Concept
Servlet = A Java program that lives on the server and handles HTTP requests/responses.
It runs inside a Servlet Container (like Apache Tomcat), which manages the Servlet's lifecycle.

How a Request Flows

Client (Browser)
     |
     |  HTTP Request (GET /login)
     v
Web Server (Tomcat)
     |
     v
Servlet Container  ← manages servlet lifecycle
     |
     v
Your Servlet  ← your Java code runs here
     |
     |  HTTP Response (HTML page)
     v
Client (Browser)  ← sees the result

CGI vs Servlet

Before Servlets, websites used CGI (Common Gateway Interface) — a separate process for every request. Servlets replaced CGI because they are faster and more efficient.

FeatureCGIServlet
Process per requestNew process each time (heavy)New thread each time (lightweight)
LanguageAny (Perl, C, etc.)Java only
PerformanceSlow — process creation overheadFast — thread reuse, stays in memory
PortabilityPlatform-dependentPlatform-independent (Java)
MemoryHigh — each process has own memoryLow — threads share memory
Exam Tip
"Why are Servlets better than CGI?" is a classic PRA question. Key answer: Servlets use threads (not processes), so they are faster and use less memory.

2. Servlet Lifecycle (ALWAYS ASKED)

The Servlet Container (Tomcat) manages every Servlet through three methods. You do not call these methods — the container calls them automatically.

The Three Lifecycle Methods

// 1. init() — Called ONCE when the servlet is first loaded
public void init() {
    // Setup code: open DB connections, read config, etc.
}

// 2. service() — Called for EVERY request
public void service(HttpServletRequest req, HttpServletResponse res) {
    // Dispatches to doGet() or doPost() based on request type
}

// 3. destroy() — Called ONCE when the servlet is being removed
public void destroy() {
    // Cleanup: close DB connections, release resources
}

Lifecycle Flow

Servlet Class loaded into memory
         |
         v
   init()  ← called ONCE (servlet is born)
         |
         v
  service()  ← called for EVERY request
    |         |
    v         v
 doGet()   doPost()    ← your code handles the request
         |
         v
  destroy()  ← called ONCE (servlet is dying)
         |
         v
Servlet is garbage collected
Remember This
  • init() — called once when servlet is first loaded
  • service() — called for every request (you usually don't override this directly)
  • destroy() — called once before servlet is removed from memory
Exam Tip
The lifecycle order init() → service() → destroy() is asked in almost every PRA exam. The service() method internally calls doGet() or doPost() depending on the HTTP method. You typically override doGet()/doPost(), not service() directly.
Common Mistake
Students confuse the order or think init() is called for every request. It is NOT. init() runs only once. Only service() runs for every request.

3. Servlet API

Servlets use classes and interfaces from two packages. You need to know which classes come from which package.

javax.servlet (Generic)

Class/InterfaceWhat It Does
ServletBase interface — defines init(), service(), destroy()
GenericServletAbstract class that implements Servlet. Protocol-independent.
ServletRequestGeneric request object
ServletResponseGeneric response object
ServletConfigConfig info for one servlet (init-params)
ServletContextShared info for the entire web application
RequestDispatcherFor forwarding/including requests
FilterIntercepts requests before they reach the servlet

javax.servlet.http (HTTP-specific)

Class/InterfaceWhat It Does
HttpServletAbstract class you extend to create HTTP servlets
HttpServletRequestHTTP request — has getParameter(), getSession(), etc.
HttpServletResponseHTTP response — has setContentType(), getWriter(), etc.
HttpSessionStores user session data across requests
CookieSmall data stored on the client browser
Tip
In ILP, you will always extend HttpServlet (not GenericServlet). HttpServlet already handles HTTP-specific details for you.

Important HttpServletRequest Methods

MethodReturnsUse
getParameter("name")StringGet form field value
getAttribute("key")ObjectGet attribute set by another servlet
getSession()HttpSessionGet or create a session
getRequestDispatcher("path")RequestDispatcherGet dispatcher for forward/include
getMethod()StringReturns "GET" or "POST"
getCookies()Cookie[]Get all cookies sent by client
getContextPath()StringReturns the application's context path

Important HttpServletResponse Methods

MethodUse
setContentType("text/html")Tell browser the response is HTML
getWriter()Returns PrintWriter to write response body
sendRedirect("url")Redirect browser to a different URL
addCookie(cookie)Send a cookie to the client
setStatus(code)Set HTTP status code (200, 404, etc.)
setHeader("name", "value")Set a response header

4. Creating a Servlet

Step-by-Step: Your First Servlet

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Step 1: Extend HttpServlet
public class HelloServlet extends HttpServlet {

    // Step 2: Override doGet() to handle GET requests
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // Step 3: Set the content type of the response
        response.setContentType("text/html");

        // Step 4: Get a PrintWriter to write output
        PrintWriter out = response.getWriter();

        // Step 5: Write HTML to the response
        out.println("<html><body>");
        out.println("<h1>Hello from Servlet!</h1>");
        out.println("</body></html>");
    }
}

Configuring with web.xml

The web.xml file tells the Servlet Container (Tomcat) which URL maps to which Servlet class.

<!-- web.xml — inside WEB-INF folder -->
<web-app>

    <!-- Step 1: Register the servlet -->
    <servlet>
        <servlet-name>HelloServlet</servlet-name>
        <servlet-class>com.example.HelloServlet</servlet-class>
    </servlet>

    <!-- Step 2: Map a URL pattern to the servlet -->
    <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

</web-app>
How it connects
When someone visits http://localhost:8080/myapp/hello:
1. Tomcat reads web.xml
2. Finds url-pattern /hello → mapped to servlet-name HelloServlet
3. Finds servlet-class com.example.HelloServlet
4. Runs that class's doGet() method
5. Returns the HTML response to the browser

Annotation-Based Configuration (Modern Way)

Instead of writing web.xml, you can use the @WebServlet annotation directly on the class. This is simpler and preferred in newer projects.

import javax.servlet.annotation.WebServlet;

// The annotation replaces the web.xml configuration
@WebServlet("/hello")     // URL pattern — same as url-pattern in web.xml
public class HelloServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        response.getWriter().println("<h1>Hello!</h1>");
    }
}
Exam Tip
Both web.xml and @WebServlet approaches are tested in PRA. Know both. The exam might give you web.xml and ask what URL triggers the servlet, or give you an annotation and ask the same.

5. doGet() vs doPost()

FeaturedoGet() / GETdoPost() / POST
Data locationAppended to URL as query stringSent in request body (hidden)
Data sizeLimited (~2048 chars)Unlimited
VisibilityVisible in URL bar and browser historyNot visible in URL
BookmarkableYesNo
SecurityLess secure (data in URL)More secure (data in body)
CachingCan be cached by browserNot cached
IdempotentYes (same request = same result)No (can cause side effects)
Use caseFetching data (search, view page)Submitting data (login, signup, payment)
Example — GET request URL
http://example.com/search?query=java&page=1
The data (query=java and page=1) is visible right in the URL. Anyone can see it, bookmark it, share it.
// Handling a GET request — e.g., showing a search page
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String query = request.getParameter("query");  // reads from URL
    response.setContentType("text/html");
    response.getWriter().println("You searched for: " + query);
}

// Handling a POST request — e.g., login form submission
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String username = request.getParameter("username");  // reads from body
    String password = request.getParameter("password");
    // Validate and respond...
}
Exam Tip
"When should you use GET vs POST?" — Use GET for reading data (search results, viewing pages) and POST for writing data (form submissions, creating records). If the form sends sensitive data like passwords, always use POST.

6. Request and Response Objects

Every time a request comes in, the Servlet Container creates two objects and passes them to your doGet()/doPost() method:

Reading Form Data

Suppose you have this HTML form:

<!-- HTML form that sends data to the servlet -->
<form action="register" method="post">
    Name:  <input type="text" name="name">
    Email: <input type="email" name="email">
    Age:   <input type="number" name="age">
    <button type="submit">Register</button>
</form>

Here's how the Servlet reads that data:

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // getParameter() reads the value of the form field by its "name" attribute
        String name  = request.getParameter("name");   // "name" matches name="name"
        String email = request.getParameter("email");  // "email" matches name="email"
        String age   = request.getParameter("age");    // Always returns String!

        // If you need age as int, parse it
        int ageNum = Integer.parseInt(age);

        // Set response content type
        response.setContentType("text/html");

        // Get the writer and send HTML back
        PrintWriter out = response.getWriter();
        out.println("<h1>Welcome, " + name + "!</h1>");
        out.println("<p>Email: " + email + "</p>");
        out.println("<p>Age: " + ageNum + "</p>");
    }
}
Important
getParameter() always returns a String, even for number inputs. You must use Integer.parseInt() or Double.parseDouble() to convert if you need a number.
Request vs Response Summary
Request = what the client sends TO the server (form data, cookies, headers).
Response = what the server sends BACK to the client (HTML page, redirect, cookies).

7. RequestDispatcher — forward() vs sendRedirect()

Two ways to move the user from one page/servlet to another. They look similar but behave very differently.

forward() — Server-side

// forward(): the server internally sends the request to another resource
// The browser URL does NOT change
RequestDispatcher rd = request.getRequestDispatcher("welcome.jsp");
rd.forward(request, response);    // same request & response objects are passed

sendRedirect() — Client-side

// sendRedirect(): tells the browser to make a NEW request to a different URL
// The browser URL DOES change
response.sendRedirect("welcome.jsp");    // browser sends a brand new request

include() — Include another resource's output

// include(): adds another resource's output to the current response
// Useful for including headers, footers, etc.
RequestDispatcher rd = request.getRequestDispatcher("header.jsp");
rd.include(request, response);    // output is added to current response

Comparison Table (HIGH PRIORITY for exam)

Featureforward()sendRedirect()
Happens onServer sideClient side (browser)
URL in browserDoes NOT changeChanges to new URL
Request objectSame request is passedNew request is created
SpeedFaster (no extra round trip)Slower (browser → server → browser → server)
Data sharingRequest attributes are availableRequest attributes are lost
Can go toSame web application onlyAny URL (even external sites)
HTTP statusNo redirect status sent302 status sent to browser
Exam Favorite
"What is the difference between forward() and sendRedirect()?" appears in almost every PRA paper. Memorize the table above. The key points: forward keeps the same request (URL doesn't change), sendRedirect creates a new request (URL changes).
When to use which
forward() — After processing a form, show a result JSP page (internal navigation).
sendRedirect() — After login, redirect to dashboard. After logout, redirect to login page. Redirecting to an external website.

8. Session Management (IMPORTANT)

Why Do We Need Sessions?

HTTP is stateless. This means the server does not remember you between requests. Every request is treated as a brand new one. But in a real app (like a shopping cart), the server needs to remember who you are across multiple pages.

Session management solves this. There are four ways to track users:

Method 1: HttpSession (Most Common)

// CREATING/GETTING a session
HttpSession session = request.getSession();  // creates new if none exists

// STORING data in the session
session.setAttribute("username", "Darshan");  // key-value pair
session.setAttribute("role", "admin");

// READING data from the session (in another servlet/page)
String user = (String) session.getAttribute("username");  // returns Object, must cast

// REMOVING a specific attribute
session.removeAttribute("role");

// DESTROYING the entire session (logout)
session.invalidate();    // session is gone, user is logged out
How HttpSession Works Internally
1. First request: server creates a session with a unique ID (e.g., JSESSIONID=abc123)
2. Server sends this ID to the browser as a cookie
3. Every subsequent request: browser automatically sends the cookie back
4. Server reads the ID, finds the matching session, and knows who you are

Method 2: Cookies

// CREATING and sending a cookie to the browser
Cookie cookie = new Cookie("username", "Darshan");  // name-value pair
cookie.setMaxAge(60 * 60);        // expires in 1 hour (seconds)
response.addCookie(cookie);         // sends it to the browser

// READING cookies from the request
Cookie[] cookies = request.getCookies();  // returns array of all cookies
if (cookies != null) {
    for (Cookie c : cookies) {
        if (c.getName().equals("username")) {
            String user = c.getValue();   // "Darshan"
        }
    }
}

// DELETING a cookie — set maxAge to 0
Cookie deleteCookie = new Cookie("username", "");
deleteCookie.setMaxAge(0);           // 0 = delete immediately
response.addCookie(deleteCookie);

Method 3: URL Rewriting

When cookies are disabled, the session ID is added to the URL.

// URL rewriting — appends session ID to the URL
String encodedURL = response.encodeURL("nextpage.jsp");
// Result: nextpage.jsp;jsessionid=abc123
out.println("<a href='" + encodedURL + "'>Next Page</a>");

Method 4: Hidden Form Fields

<!-- Hidden field carries data that the user cannot see -->
<form action="nextServlet" method="post">
    <input type="hidden" name="userId" value="12345">
    <button type="submit">Continue</button>
</form>

Comparison of All Four Methods

MethodStored OnWorks Without Cookies?SecurityUse Case
HttpSessionServerNo (uses cookie for session ID)Most secureLogin sessions, shopping carts
CookiesClient (browser)N/A (it IS cookies)Less secure (can be tampered)Remember me, preferences
URL RewritingURLYesLeast secure (visible in URL)Fallback when cookies disabled
Hidden Form FieldsHTML formYesModerateMulti-step forms
Exam Tip
"List session tracking techniques in Servlets" — answer all four: HttpSession, Cookies, URL Rewriting, Hidden Form Fields. Most common follow-up: "Which is most commonly used?" — HttpSession.

9. Filters

A Filter intercepts requests before they reach the Servlet and responses after the Servlet processes them. Think of it as a security guard at the door.

Use Cases

Filter Lifecycle

Same pattern as Servlet: init()doFilter()destroy()

import javax.servlet.*;
import java.io.*;

public class LoggingFilter implements Filter {

    // Called once when filter is loaded
    public void init(FilterConfig config) {
        System.out.println("Filter initialized");
    }

    // Called for every matching request
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain)
            throws IOException, ServletException {

        // Code here runs BEFORE the servlet
        System.out.println("Request received at: " + new java.util.Date());

        // Pass the request to the next filter or servlet
        chain.doFilter(request, response);  // THIS LINE IS CRITICAL

        // Code here runs AFTER the servlet has processed the request
        System.out.println("Response sent");
    }

    // Called once when filter is destroyed
    public void destroy() {
        System.out.println("Filter destroyed");
    }
}
Critical
If you forget to call chain.doFilter(request, response), the request will NEVER reach the servlet. The user will see a blank page. Always call it unless you intentionally want to block the request (e.g., unauthorized user).

Configuring a Filter in web.xml

<filter>
    <filter-name>LoggingFilter</filter-name>
    <filter-class>com.example.LoggingFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>LoggingFilter</filter-name>
    <url-pattern>/*</url-pattern>    <!-- applies to ALL URLs -->
</filter-mapping>

10. Listeners

Listeners "listen" for events in the web application — like when the app starts, a session is created, or an attribute changes. You write code that runs automatically when these events happen.

Common Listeners

ListenerListens ForMethods
ServletContextListenerApp startup and shutdowncontextInitialized(), contextDestroyed()
HttpSessionListenerSession created/destroyedsessionCreated(), sessionDestroyed()
ServletRequestListenerRequest created/destroyedrequestInitialized(), requestDestroyed()
HttpSessionAttributeListenerSession attribute added/removed/replacedattributeAdded(), attributeRemoved(), attributeReplaced()
import javax.servlet.*;
import javax.servlet.annotation.WebListener;

@WebListener       // annotation-based registration
public class AppStartListener implements ServletContextListener {

    // Runs when the web application STARTS
    public void contextInitialized(ServletContextEvent event) {
        System.out.println("Application started!");
        // Good place to: load config, initialize DB connection pool, etc.
    }

    // Runs when the web application STOPS
    public void contextDestroyed(ServletContextEvent event) {
        System.out.println("Application stopped!");
        // Good place to: close connections, cleanup resources
    }
}
When to use Listeners
ServletContextListener — run code when the app starts (load config) or stops (cleanup).
HttpSessionListener — track how many users are currently logged in by counting active sessions.

11. web.xml Configuration

The web.xml file is the deployment descriptor. It lives inside the WEB-INF folder and tells Tomcat how to configure your web application.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="4.0">

    <!-- 1. SERVLET REGISTRATION -->
    <servlet>
        <servlet-name>MyServlet</servlet-name>
        <servlet-class>com.example.MyServlet</servlet-class>

        <!-- Init parameters — specific to this servlet -->
        <init-param>
            <param-name>dbURL</param-name>
            <param-value>jdbc:mysql://localhost:3306/mydb</param-value>
        </init-param>
    </servlet>

    <!-- 2. URL MAPPING -->
    <servlet-mapping>
        <servlet-name>MyServlet</servlet-name>
        <url-pattern>/myservlet</url-pattern>
    </servlet-mapping>

    <!-- 3. CONTEXT PARAMETERS — shared across ALL servlets -->
    <context-param>
        <param-name>appName</param-name>
        <param-value>My Web App</param-value>
    </context-param>

    <!-- 4. WELCOME FILE — default page when visiting root URL -->
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <!-- 5. ERROR PAGE — custom error pages -->
    <error-page>
        <error-code>404</error-code>
        <location>/error404.html</location>
    </error-page>
    <error-page>
        <error-code>500</error-code>
        <location>/error500.html</location>
    </error-page>

</web-app>

init-param vs context-param

Featureinit-paramcontext-param
ScopeSpecific to one servletShared across entire application
Defined inside<servlet> tagDirectly inside <web-app> tag
Access viagetServletConfig().getInitParameter("name")getServletContext().getInitParameter("name")
Use caseDB URL for a specific servletApp name, admin email — shared info
Exam Tip
"How do you read an init-param in a servlet?" — getServletConfig().getInitParameter("paramName")
"How do you read a context-param?" — getServletContext().getInitParameter("paramName")
Notice: both use getInitParameter(), but one uses ServletConfig and the other uses ServletContext.

12. Servlet vs JSP

FeatureServletJSP
What it isJava class with HTML inside Java codeHTML page with Java code inside
Good forProcessing logic (controllers)Displaying output (views)
ModificationRequires recompilationAuto-compiled by container
MVC roleControllerView
InternallyStays as a ServletGets converted TO a Servlet by the container
Key Fact
Every JSP page is internally compiled into a Servlet by the container. JSP is just a convenient way to write the "view" part without doing out.println() for every line of HTML.
// Servlet way — writing HTML inside Java (messy for large pages)
out.println("<html><body>");
out.println("<h1>Hello, " + name + "</h1>");
out.println("</body></html>");

// JSP way — writing Java inside HTML (much cleaner for pages)
// <html><body>
// <h1>Hello, <%= name %></h1>
// </body></html>

13. Practice Questions

Question 1
What is the correct order of the Servlet lifecycle?
  1. service() → init() → destroy()
  2. init() → destroy() → service()
  3. init() → service() → destroy()
  4. destroy() → init() → service()
C) init() → service() → destroy(). init() is called once when the servlet loads, service() for every request, destroy() once when unloading.
Question 2
Which method is called for every HTTP request received by a servlet?
  1. init()
  2. destroy()
  3. service()
  4. doGet()
C) service(). The service() method is called for every request. It then internally dispatches to doGet() or doPost() based on the request type.
Question 3
What is the difference between forward() and sendRedirect()?
  1. forward() changes the URL, sendRedirect() does not
  2. forward() is client-side, sendRedirect() is server-side
  3. forward() keeps the same request, sendRedirect() creates a new request
  4. There is no difference
C) forward() keeps the same request object and URL doesn't change (server-side). sendRedirect() tells the browser to make a new request, URL changes (client-side).
Question 4
Which of the following is NOT a session tracking technique in Servlets?
  1. HttpSession
  2. Cookies
  3. URL Rewriting
  4. JDBC Connection
D) JDBC Connection. JDBC is for database access, not session tracking. The four session tracking techniques are: HttpSession, Cookies, URL Rewriting, and Hidden Form Fields.
Question 5
What does request.getParameter("name") return?
  1. An int value
  2. A String value
  3. An Object
  4. A boolean
B) A String value. getParameter() always returns a String, even if the form field is a number. You need to use Integer.parseInt() to convert it.
Question 6
In which HTTP method is data sent as part of the URL?
  1. POST
  2. GET
  3. PUT
  4. DELETE
B) GET. In GET requests, data is appended to the URL as a query string (e.g., /search?q=java). POST sends data in the request body, hidden from the URL.
Question 7
What happens if you do not call chain.doFilter() in a Filter?
  1. The filter is skipped
  2. The request reaches the servlet normally
  3. The request never reaches the servlet
  4. An exception is thrown
C) The request never reaches the servlet. chain.doFilter() is what passes the request along to the next filter or the servlet. Without it, the chain is broken.
Question 8
Which annotation is used to map a servlet to a URL pattern without web.xml?
  1. @ServletMapping
  2. @WebServlet
  3. @HttpServlet
  4. @URLPattern
B) @WebServlet. Example: @WebServlet("/hello") maps the servlet to the /hello URL pattern. This replaces the servlet and servlet-mapping tags in web.xml.
Question 9
How do you destroy/invalidate a user session in a Servlet?
  1. session.close()
  2. session.destroy()
  3. session.invalidate()
  4. session.end()
C) session.invalidate(). This method destroys the session and removes all attributes stored in it. Commonly used for logout functionality.
Question 10
Which method of HttpServletResponse is used to send the browser to a different URL?
  1. response.forward("url")
  2. response.sendRedirect("url")
  3. response.redirect("url")
  4. response.dispatch("url")
B) response.sendRedirect("url"). This sends a 302 redirect to the browser, which then makes a new GET request to the specified URL.
Question 11
What is the purpose of the <welcome-file-list> in web.xml?
  1. Lists all servlets in the application
  2. Specifies default pages to load when visiting the root URL
  3. Lists all filter mappings
  4. Specifies error pages
B) Specifies default pages. When a user visits http://localhost:8080/myapp/ (no specific page), the container looks for the files listed in welcome-file-list in order.
Question 12
What is the difference between init-param and context-param in web.xml?
  1. init-param is for the entire app, context-param is for one servlet
  2. init-param is for one servlet, context-param is for the entire app
  3. They are the same thing
  4. init-param is for filters only
B) init-param is specific to one servlet (defined inside the <servlet> tag). context-param is shared across the entire application (defined directly in <web-app>).
Question 13
Why are Servlets better than CGI?
  1. Servlets use C++ which is faster
  2. Servlets create a new process for each request
  3. Servlets use threads instead of processes, so they are faster and use less memory
  4. CGI and Servlets have the same performance
C) Servlets use threads (lightweight) instead of processes (heavy). A thread shares memory with other threads, so the server uses less memory and can handle more concurrent requests.
Question 14
Which interface must a class implement to act as a Servlet Filter?
  1. javax.servlet.Servlet
  2. javax.servlet.Filter
  3. javax.servlet.FilterChain
  4. javax.servlet.http.HttpFilter
B) javax.servlet.Filter. The Filter interface requires implementing three methods: init(), doFilter(), and destroy().
Question 15
What does a JSP page get converted to internally?
  1. A static HTML file
  2. A JavaScript file
  3. A Servlet
  4. A PHP script
C) A Servlet. The JSP container (like Tomcat) compiles every JSP page into a Servlet class behind the scenes. JSP is essentially syntactic sugar for Servlets.
Question 16
Which method of HttpServletRequest is used to get the HttpSession object?
  1. request.createSession()
  2. request.getSession()
  3. request.session()
  4. request.getHttpSession()
B) request.getSession(). If a session already exists, it returns the existing one. If not, it creates a new session. You can pass false — getSession(false) — to return null instead of creating a new one.
Question 17
Which listener is used to detect when a web application starts or shuts down?
  1. HttpSessionListener
  2. ServletRequestListener
  3. ServletContextListener
  4. HttpSessionAttributeListener
C) ServletContextListener. It has two methods: contextInitialized() runs when the app starts, and contextDestroyed() runs when the app shuts down.
Question 18
In forward(), does the URL in the browser change?
  1. Yes, it changes to the forwarded URL
  2. No, it stays the same as the original request URL
  3. It depends on the server configuration
  4. It shows a blank URL
B) No, the URL stays the same. forward() is server-side — the browser never knows the request was forwarded internally. Only sendRedirect() changes the URL because it tells the browser to make a new request.