7 Servlets And Java Server Pages

Advanced Java Programming · Unit 7 · 8 hrs

Servlets and Java Server pages

Exam-focused notes for Servlets and Java Server pages (Advanced Java Programming, CSC419): what the TU syllabus asks and how it has actually been tested, with 17 solved past questions from this unit.

Servlets and Java Server pages in short

This unit covers server-side Java web development: the web container that hosts servlets, the servlet life cycle and API, reading and processing form data, cookies and sessions, JavaServer Pages as a tag-based alternative to servlets, and a brief survey of the frameworks built on top of both.

Servlets and Java Server pages: notes

Web Container, Introduction to Servlets, Life cycle of servlets, The servlet APIs, Writing Servlet Programs, Reading Form Parameters, Processing Forms, Handling HTTP Request and Response (GET / POST Request), Database Access with Servlets, Handling Cookies and Session

A web container (also called a servlet container, such as Apache Tomcat) is the runtime environment that hosts a web application's servlets and JSPs. When a request arrives from a client, the web server hands it to the web container, which locates the resource that should handle it, runs it, and returns the generated response to the web server for delivery back to the client. The container is responsible for the communication between the web server and servlets/JSPs, for managing a servlet's life cycle and resources, for multithreading support (serving many requests concurrently), and for JSP support.

A servlet is a small Java program that runs on the server side of a web connection, extending the capabilities of a server much as an applet extends the capabilities of a browser. Servlets are not restricted to any one protocol, but Java Servlet technology defines HTTP-specific servlet classes because HTTP is by far the most common use. The javax.servlet and javax.servlet.http packages provide the interfaces and classes needed to write them; every servlet ultimately implements the Servlet interface, which declares its life cycle methods.

The servlet life cycle has three central methods, called by the container rather than by application code directly:

  1. Loading and instantiation: the container's class loader loads the servlet class and creates an instance of it; a container may hold only one instance of a given servlet, reusing it across many requests.
  2. Initialization, init(ServletConfig config): called once, immediately after the servlet is instantiated, to perform one-time setup such as opening a resource the servlet will reuse across requests.
  3. Request processing, service(ServletRequest request, ServletResponse response): called once for every request the container routes to this servlet; for an HttpServlet, this default implementation dispatches to doGet(), doPost(), or another doXxx() method based on the HTTP method used.
  4. Destruction, destroy(): called once, when the container is taking the servlet out of service, to release any resources acquired in init().
  5. After destroy() runs, the servlet instance becomes eligible for garbage collection by the JVM.

The servlet API is split across two packages. javax.servlet provides the protocol-independent framework: the Servlet interface (declaring the life cycle methods), ServletConfig (initialization parameters), ServletRequest and ServletResponse (reading a request and writing a response in a protocol-neutral way), GenericServlet (a base implementation of Servlet and ServletConfig), and ServletException. javax.servlet.http layers HTTP-specific functionality on top: HttpServletRequest and HttpServletResponse (HTTP-flavoured request and response objects), HttpSession (per-user session data), Cookie (client-side state), and HttpServlet (the base class almost every real servlet extends, providing doGet(), doPost(), and the rest).

Writing a servlet program can be done by implementing the Servlet interface directly, by extending GenericServlet, or, in almost every practical case, by extending HttpServlet, because it already provides HTTP-specific methods like doGet() and doPost(). Deploying one on Apache Tomcat means creating the expected directory structure, writing the servlet class, compiling it, describing it in a deployment descriptor, starting the server, and accessing the servlet through its mapped URL.

What this unit covers

  • Web Container, Introduction to Servlets, Life cycle of servlets, The servlet APIs, Writing Servlet Programs, Reading Form Parameters, Processing Forms, Handling HTTP Request and Response (GET / POST Request), Database Access with Servlets, Handling Cookies and Session
  • Servlet vs JSP, JSP Access Model, JSP Syntax (Directions, Declarations, Expression, Scriplets, Comments), JSP Implicit Objects, Object Scope, Processing Forms, Database Access with JSP
  • Introduction to Java Web Frameworks

Web Container, Introduction to Servlets, Life cycle of servlets, The servlet APIs, Writing Servlet Programs, Reading Form Parameters, Processing Forms, Handling HTTP Request and Response

2081 · 5 marks

Explain the life cycle of servlets. [5]

Show solved answer

Life Cycle of a Servlet

Introduction

A Servlet is a small Java program that executes on the server side of a Web connection and dynamically extends the functionality of a web server. All servlets must implement the Servlet interface, which defines the life-cycle methods. The servlet life cycle is managed by the Servlet Engine (Container).


Stages of the Servlet Life Cycle

The Servlet Life Cycle has 5 stages in general. Three methods are central to the life cycle: init(), service(), and destroy().


Stage 1: Loading and Instantiation

  • The class loader is responsible for loading the servlet class from the file system or network.
  • After loading, the servlet engine creates an instance of the servlet class.
  • The servlet instance is created only once in the servlet life cycle.
  • The servlet engine can instantiate more than one servlet instance if needed (e.g., for load balancing).

Stage 2: Initialization (init())

  • After instantiation, the servlet container calls the init() method.
  • This method is called only once during the entire life of the servlet.
  • It is used to perform one-time initialization tasks such as opening database connections, loading configuration parameters, etc.
  • Signature:
public void init(ServletConfig config) throws ServletException

Stage 3: Request Handling (service())

  • Once initialized, the servlet is ready to handle client requests.
  • For each incoming request, the servlet container calls the service() method.
  • The service() method determines the type of HTTP request (GET, POST, PUT, DELETE, etc.) and dispatches it to the appropriate handler method (doGet(), doPost(), etc.).
  • This method is called multiple times, once per request.
  • Signature:
public void service(ServletRequest req, ServletResponse res)
    throws ServletException, IOException

Stage 4: Destroying (destroy())

  • When the servlet container decides to remove the servlet (e.g., server shutdown or redeployment), it calls the destroy() method.
  • This method is called only once, at the end of the servlet's life.
  • It is used to perform cleanup tasks such as closing database connections, releasing resources, etc.
  • Signature:
public void destroy()

Stage 5: Garbage Collection

  • After destroy() is called, the servlet instance becomes eligible for garbage collection.
  • The JVM's garbage collector reclaims the memory occupied by the servlet object.

Diagram of Servlet Life Cycle

Client Request
      |
      v
[1. Load & Instantiate Servlet Class]
      |
      v
[2. init()  --> Called ONCE]
      |
      v
[3. service() --> Called per request]
   /    \
doGet() doPost() ...
      |
      v
[4. destroy() --> Called ONCE]
      |
      v
[5. Garbage Collection]

Summary Table

StageMethodCalled
Loading & Instantiation(by class loader)Once
Initializationinit()Once
Request Handlingservice()Per request
Destructiondestroy()Once
Garbage Collection(by JVM)Once

Note: The packages java.x.servlet and java.x.servlet.http provide the interfaces and classes required to implement these life-cycle methods. A server such as Apache Tomcat or GlassFish is needed to run servlets.

Open this answer on its own page →

2078 · 10 marks

Explain life-cycle of servlet in detail. Create a simple servlet that reads and displays data from HTML form. Assume form with two fields username and password.[10]

The servlet life cycle defines how a servlet is loaded, initialized, used, and destroyed by the servlet container (e.g., Apache Tomcat). It is managed entirely by the servlet container. --- - When the servlet container starts (or when the first request arrives), it loads the servlet class into me...

Open this answer on its own page →

2077 · 5 marks

Explain the life cycle of a servlet. [5]

A servlet is a small Java program that executes on the server side of a web connection and dynamically extends the functionality of a web server. All servlets must implement the Servlet interface, which defines the life-cycle methods. The servlet life cycle is managed by the Servlet Engine (Conta...

Open this answer on its own page →

2076 · 10 marks

Define servlet. Discuss life cycle of servlet. Differentiate servlet with JSP. Write a simple JSP file to display 'IOST' 20 times.[10]

--- A servlet is a small program that executes on the server side of a Web connection. Just as applets dynamically extend the functionality of a web browser, servlets dynamically extend the capabilities of a web server. It is a Java programming model used to extend the capabilities of servers tha...

Open this answer on its own page →

2076 · 5 marks

How do you handle HTTP request (GET) using servlet? [5]

A Servlet handles HTTP GET requests by overriding the doGet() method provided by the HttpServlet class. When a client sends a GET request (e.g., by submitting an HTML form with method="GET" or typing a URL), the web container invokes the doGet() method of the corresponding servlet. Note: GET meth...

Open this answer on its own page →

2076 · 5 marks

Write short notes on: a. Servlet API b. RMI vs CORBA [2.5+2.5]

--- The Servlet API is a set of Java classes and interfaces provided in the javax.servlet and javax.servlet.http packages that define the contract between a servlet and the servlet container (e.g., Apache Tomcat). Component Type Description --------- Servlet Interface Root interface; defines init...

Open this answer on its own page →

2075 · 10 marks

Describe the process to deploy the servlet. Write a program to a JSP web form to take input of a student and submit it to second JSP file which may simply print the values of form submission.[10]

--- There are six steps to write and deploy a Servlet program (using Apache Tomcat server): --- Create the required folder structure inside the Tomcat webapps directory: - WEB-INF/classes/ contains compiled .class files - WEB-INF/web.xml is the deployment descriptor - WEB-INF/lib/ contains any re...

Open this answer on its own page →

2075 · 5 marks

Explain the significance of cookies and sessions with suitable example. [5]

A cookie is a small piece of data (key-value pair) stored on the client's browser by the web server. It is used to remember information about the user across multiple HTTP requests, since HTTP is a stateless protocol. - Remembers user preferences (language, theme) - Tracks user login status - Sto...

Open this answer on its own page →

Servlet vs JSP, JSP Access Model, JSP Syntax

2081 · 5 marks

Write a program in JSP to display the string taken in one page in another page. [5]

Show solved answer

JSP Program to Display String from One Page to Another Page

Concept

This program uses two JSP pages:

  • Page 1 (input.jsp): Contains an HTML form with a text field where the user enters a string.
  • Page 2 (display.jsp): Receives the string via HTTP request and displays it.

The string is passed from one page to another using the HTML form's action attribute and retrieved using JSP's built-in request.getParameter() method.


Page 1: input.jsp

<%-- input.jsp : Takes string input from the user --%>
<html>
  <head>
    <title>Input Page</title>
  </head>
  <body>
    <h2>Enter a String</h2>

    <form action="display.jsp" method="post">
      Enter String:
      <input type="text" name="userString" />
        
      <input type="submit" value="Submit" />
    </form>

  </body>
</html>

Explanation:

ElementPurpose
action="display.jsp"Sends form data to display.jsp
method="post"Sends data via HTTP POST method
name="userString"Name used to retrieve value in next page

Page 2: display.jsp

<%-- display.jsp : Displays the string received from input.jsp --%>
<html>
  <head>
    <title>Display Page</title>
  </head>
  <body>
    <h2>Received String</h2>

    <%
      // Retrieve the string sent from input.jsp
      String str = request.getParameter("userString");

      // Check if string is not null or empty
      if (str != null && !str.isEmpty()) {
    %>
        <p>The string entered is: <strong><%= str %></strong></p>
    <%
      } else {
    %>
        <p>No string was entered.</p>
    <%
      }
    %>

    <a href="input.jsp">Go Back</a>

  </body>
</html>

Explanation:

CodePurpose
request.getParameter("userString")Retrieves the value of the text field named userString from Page 1
<%= str %>JSP expression tag to display the value on the page
Null checkPrevents errors if no input is provided

Output

Page 1 (input.jsp):

Enter a String
Enter String: [  Hello TU  ]   [Submit]

Page 2 (display.jsp) after clicking Submit:

Received String
The string entered is: Hello TU

[Go Back]

Key Points to Remember

  • request is a built-in JSP implicit object of type HttpServletRequest.
  • request.getParameter("name") returns the value as a String.
  • method="post" is preferred over method="get" to avoid showing data in the URL.
  • JSP scriptlet tags <% %> are used for Java code and <%= %> for output expressions.
Open this answer on its own page →

2080 · 10 marks

How does JSP differ from Servlet and show the life cycle of Servlet? How do you create and read the cookies and session using JSP? Illustrate with an example.[10]

--- Feature Servlet JSP (JavaServer Pages) --------- Nature Java class that generates HTML HTML page that embeds Java code Extension .java (compiled to .class) .jsp (auto-compiled by container) Writing Style HTML written inside out.println() statements Java code written inside <% % tags Compilati...

Open this answer on its own page →

2080 · 5 marks

What do you mean by JSP implicit objects? Discuss Java Mail API. [5]

Show solved answer

JSP Implicit Objects and Java Mail API


Part 1: JSP Implicit Objects

JSP implicit objects are pre-defined objects that the JSP container automatically makes available to every JSP page without requiring the developer to explicitly declare or instantiate them. These objects can be used directly inside JSP scriptlets and expressions.

Note: Unlike Servlets, JSP has implicit objects while Servlet does not.

The commonly used JSP implicit objects are:

ObjectTypeDescription
requestHttpServletRequestRepresents the client HTTP request
responseHttpServletResponseRepresents the HTTP response to the client
outJspWriterUsed to write output to the response
sessionHttpSessionManages session data for a user
applicationServletContextShared data across the entire application
configServletConfigServlet configuration information
pageContextPageContextProvides access to all JSP namespaces
pageObjectRefers to the current JSP page instance (like this)
exceptionThrowableAvailable in error pages to handle exceptions

These objects simplify JSP development by removing the need for boilerplate code.


Part 2: Java Mail API

Definition

The JavaMail API is an API used to compose, write, and read electronic messages (emails). It provides a protocol-independent and platform-independent framework for sending and receiving emails.

Core Packages

  • java.mail
  • java.mail.activation

Setup Requirements

  • For J2EE 1.3 (Enterprise Edition): No additional setup required.
  • For J2SE 1.1+ (Standard Edition): Must download and install:
    • JavaMail API
    • Java Activation Framework

Sending an Email (3 Steps)

Step 1: Get the Session Object Stores all host information such as host name, username, password, etc.

Properties properties = new Properties();
Session session = Session.getDefaultInstance(properties, null);

Step 2: Compose the Message MimeMessage class is mostly used for composing the email.

MimeMessage message = new MimeMessage(session);

Step 3: Send the Message Transport class provides the method to send the message.

Transport.send(message);

Receiving an Email (Steps)

  1. Get the session object.
  2. Create the POP3 store object and connect with the POP server.
  3. Create the folder object and open it.
  4. Retrieve the messages from the folder into an array and print them.
  5. Close the store and folder objects.

Summary

FeatureDetail
PurposeSend and receive emails
NatureProtocol-independent, Platform-independent
Key ClassesSession, MimeMessage, Transport
Protocol Used (Receive)POP3
Core Packagejava.mail
Open this answer on its own page →

2079 · 10 marks

Define JSP. What are the benefits of using JSP? Create a HTML file with two text fields to first name and last name. Create a JSP file that reads data from the HTML form and display full name.[10]

Show solved answer

JSP: Definition, Benefits, and Form Handling


1. Definition of JSP

JavaServer Pages (JSP) is a server-side technology used to create dynamic, platform-independent web pages. JSP allows developers to embed Java code directly into HTML pages using special JSP tags. When a JSP page is requested by a client, the server processes the Java code, generates an HTML response, and sends it back to the browser.

JSP is built on top of Servlet technology. Internally, a JSP page is automatically translated into a Servlet by the JSP engine (container) before execution.

Syntax of JSP Scriptlet:

<% Java code here %>

2. Benefits of Using JSP

BenefitDescription
Separation of ConcernsHTML (presentation) and Java (logic) can be written separately, making code cleaner and easier to maintain.
Easy to UseDevelopers familiar with HTML can embed Java code without writing full Servlet classes.
Platform IndependentJSP runs on any platform that supports a Java-compatible web server (e.g., Apache Tomcat).
ReusabilityJSP supports JavaBeans and custom tag libraries, promoting code reuse.
Automatic Servlet TranslationThe JSP container automatically converts JSP into a Servlet, so the developer does not need to write boilerplate Servlet code manually.
Implicit ObjectsJSP provides built-in implicit objects such as request, response, out, session, etc., which simplify development.
Integration with Java EEJSP integrates easily with JDBC, EJB, and other Java EE technologies for building enterprise applications.
Better MaintainabilitySince HTML and Java are written in the same file with clear separation using tags, updating the UI does not require recompiling Servlet classes.

3. HTML File with Two Text Fields (First Name and Last Name)

File Name: index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Full Name Form</title>
  </head>
  <body>
    <h2>Enter Your Name</h2>

    <!-- Form submits data to the JSP file using POST method -->
    <form action="displayName.jsp" method="post">

      <label for="firstName">First Name:</label>
      <input type="text" id="firstName" name="firstName" placeholder="Enter first name" />
        

      <label for="lastName">Last Name:</label>
      <input type="text" id="lastName" name="lastName" placeholder="Enter last name" />
        

      <input type="submit" value="Submit" />

    </form>
  </body>
</html>

Explanation:

  • The form uses method="post" to send data securely.
  • The action="displayName.jsp" attribute directs the form data to the JSP file for processing.
  • Two text fields are created with name="firstName" and name="lastName", which are used as parameter names in JSP.

4. JSP File that Reads Form Data and Displays Full Name

File Name: displayName.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
  <head>
    <title>Display Full Name</title>
  </head>
  <body>
    <h2>Full Name Display</h2>

    <%
      // Read the form parameters sent from index.html
      // request is an implicit object in JSP (similar to HttpServletRequest in Servlet)
      String firstName = request.getParameter("firstName");
      String lastName  = request.getParameter("lastName");

      // Combine first name and last name to form the full name
      String fullName = firstName + " " + lastName;
    %>

    <!-- Display the full name in the HTML response -->
    <p><strong>First Name:</strong> <%= firstName %></p>
    <p><strong>Last Name:</strong>  <%= lastName  %></p>
    <p><strong>Full Name:</strong>  <%= fullName  %></p>

  </body>
</html>

Explanation of Key Elements:

ElementPurpose
<%@ page ... %>Page directive that sets language and encoding for the JSP page.
<% ... %>Scriptlet tag used to write Java code inside JSP.
<%= ... %>Expression tag used to output a Java variable value directly into HTML.
request.getParameter("firstName")Reads the value of the firstName field submitted from the HTML form. This is the same method used in Servlets.
request.getParameter("lastName")Reads the value of the lastName field submitted from the HTML form.

5. Flow of Execution

User fills index.html
        |
        v
Browser sends POST request to displayName.jsp
        |
        v
JSP Container translates JSP to Servlet (internally)
        |
        v
request.getParameter() reads firstName and lastName
        |
        v
Full name is constructed and displayed in browser

Summary

  • JSP is a server-side technology for building dynamic web pages by embedding Java into HTML.
  • It simplifies web development compared to pure Servlets by avoiding excessive out.println() statements.
  • The request.getParameter() implicit method in JSP works exactly like in Servlets to read HTML form data.
  • The HTML form sends data via POST to the JSP file, which processes and displays the full name.
Open this answer on its own page →

2079 · 5 marks

Compare JSP with servlet. What are different implicit objects in JSP? [5]

--- Feature Servlet JSP --------- Nature Pure Java code Tag-based approach HTML Writing HTML is written inside Java (Servlet) code Java code is written inside HTML Speed Faster than JSP Slower than Servlet Ease of Coding Writing code is harder Writing code is easier Protocol Support Can accept al...

Open this answer on its own page →

2078 · 5 marks

What is servlet? Write a simple JSP file to display 'Tribhuvan University' five times. [5]

--- A Servlet is a Java program that runs on the server side and is used to handle client requests and generate dynamic web content (typically HTML) as a response. Key points about Servlet: - It is a Java class that extends HttpServlet - It runs inside a Servlet Container (e.g., Apache Tomcat) - ...

Open this answer on its own page →

2077 · 5 marks

How forms can be created and processed using JSP? Make it clear with your own assumptions. [5]

JSP (JavaServer Pages) allows embedding Java code inside HTML pages. Forms can be created using standard HTML <form tags within a JSP page and processed by reading the submitted data using JSP's built-in request object. --- Object Purpose ------ request Retrieves form data sent by the client requ...

Open this answer on its own page →

Introduction to Java Web Frameworks

2077 · 5 marks

Write short notes on: a. JAVA beans and JAR file b. MVC design pattern [2.5+2.5]

--- A JavaBean is a reusable software component written in Java that follows specific conventions. It is essentially a Java class that encapsulates multiple objects into a single object (the bean). Key Conventions / Properties of a JavaBean: - The class must be public and implement the java.io.Se...

Open this answer on its own page →

2076 · 5 marks

Discuss MVC design pattern with example. [5]

MVC (Model-View-Controller) is a software architectural/design pattern that separates an application into three interconnected components. This separation helps in organizing code, improving maintainability, and allowing independent development of each component. --- - Represents the data and bus...

Open this answer on its own page →