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.
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 answerHide 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
| Stage | Method | Called |
|---|---|---|
| Loading & Instantiation | (by class loader) | Once |
| Initialization | init() | Once |
| Request Handling | service() | Per request |
| Destruction | destroy() | Once |
| Garbage Collection | (by JVM) | Once |
Note: The packages
java.x.servletandjava.x.servlet.httpprovide the interfaces and classes required to implement these life-cycle methods. A server such as Apache Tomcat or GlassFish is needed to run servlets.
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]
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]
2076 · 5 marks
How do you handle HTTP request (GET) using servlet? [5]
2076 · 5 marks
Write short notes on: a. Servlet API b. RMI vs CORBA [2.5+2.5]
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]
2075 · 5 marks
Explain the significance of cookies and sessions with suitable example. [5]
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 answerHide 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:
| Element | Purpose |
|---|---|
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:
| Code | Purpose |
|---|---|
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 check | Prevents 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
requestis a built-in JSP implicit object of typeHttpServletRequest.request.getParameter("name")returns the value as a String.method="post"is preferred overmethod="get"to avoid showing data in the URL.- JSP scriptlet tags
<% %>are used for Java code and<%= %>for output expressions.
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]
2080 · 5 marks
What do you mean by JSP implicit objects? Discuss Java Mail API. [5]
Show solved answerHide 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:
| Object | Type | Description |
|---|---|---|
request | HttpServletRequest | Represents the client HTTP request |
response | HttpServletResponse | Represents the HTTP response to the client |
out | JspWriter | Used to write output to the response |
session | HttpSession | Manages session data for a user |
application | ServletContext | Shared data across the entire application |
config | ServletConfig | Servlet configuration information |
pageContext | PageContext | Provides access to all JSP namespaces |
page | Object | Refers to the current JSP page instance (like this) |
exception | Throwable | Available 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.mailjava.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)
- Get the session object.
- Create the POP3 store object and connect with the POP server.
- Create the folder object and open it.
- Retrieve the messages from the folder into an array and print them.
- Close the store and folder objects.
Summary
| Feature | Detail |
|---|---|
| Purpose | Send and receive emails |
| Nature | Protocol-independent, Platform-independent |
| Key Classes | Session, MimeMessage, Transport |
| Protocol Used (Receive) | POP3 |
| Core Package | java.mail |
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 answerHide 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
| Benefit | Description |
|---|---|
| Separation of Concerns | HTML (presentation) and Java (logic) can be written separately, making code cleaner and easier to maintain. |
| Easy to Use | Developers familiar with HTML can embed Java code without writing full Servlet classes. |
| Platform Independent | JSP runs on any platform that supports a Java-compatible web server (e.g., Apache Tomcat). |
| Reusability | JSP supports JavaBeans and custom tag libraries, promoting code reuse. |
| Automatic Servlet Translation | The JSP container automatically converts JSP into a Servlet, so the developer does not need to write boilerplate Servlet code manually. |
| Implicit Objects | JSP provides built-in implicit objects such as request, response, out, session, etc., which simplify development. |
| Integration with Java EE | JSP integrates easily with JDBC, EJB, and other Java EE technologies for building enterprise applications. |
| Better Maintainability | Since 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"andname="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:
| Element | Purpose |
|---|---|
<%@ 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.
2079 · 5 marks
Compare JSP with servlet. What are different implicit objects in JSP? [5]
2078 · 5 marks
What is servlet? Write a simple JSP file to display 'Tribhuvan University' five times. [5]
2077 · 5 marks
How forms can be created and processed using JSP? Make it clear with your own assumptions. [5]
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]
Make Unit 7 stick
Practice CSC419 with flashcards & quizzes