0% found this document useful (0 votes)
8 views45 pages

Understanding Java Servlets and JSP

A Servlet is a Java program that acts as a middle layer between client requests and server-side resources, primarily used for building dynamic web applications. The Servlet life cycle includes phases such as loading, initialization, request handling, and destruction, with key methods like init(), service(), and destroy(). JSP, built on top of Servlets, simplifies dynamic web page creation by allowing Java code to be embedded in HTML, and it has its own life cycle phases including translation, compilation, and execution.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views45 pages

Understanding Java Servlets and JSP

A Servlet is a Java program that acts as a middle layer between client requests and server-side resources, primarily used for building dynamic web applications. The Servlet life cycle includes phases such as loading, initialization, request handling, and destruction, with key methods like init(), service(), and destroy(). JSP, built on top of Servlets, simplifies dynamic web page creation by allowing Java code to be embedded in HTML, and it has its own life cycle phases including translation, compilation, and execution.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1. What is Servlet?

A Servlet is a Java program that runs on a server and acts as a


middle layer between:
• Client (browser) requests, and
• Server-side resources (like databases or files).
It is part of the Java EE (Jakarta EE) platform and is mainly used for
building dynamic web applications.

2. Servlet Architecture Overview


When a client sends a request (like clicking a button or submitting a
form):
1. Browser (Client) → sends an HTTP request
2. Web Server (Tomcat, Jetty, etc.) → forwards it to the Servlet
Container
3. Servlet Container → executes the Servlet class
4. Servlet → generates a response (HTML, JSON, etc.)
5. Response → goes back to the browser

3. Servlet Life Cycle


A servlet’s life is managed by the Servlet Container (like Apache
Tomcat).
The Servlet Life Cycle consists of 5 phases
Phase Method Description

Servlet is loaded into


1. Loading and
init() memory and initialized
Instantiation
(only once).

Called once when the


2. Initialization init(ServletConfig config) servlet is first loaded; used
to initialize resources.

3. Request service(ServletRequest req, Called every time a


Handling ServletResponse res) request comes in.

Called once before the


4. Destruction destroy() servlet is destroyed or
unloaded.

5. Garbage JVM removes servlet



Collection object from memory.
4. Important Servlet Methods

Method Description

init() Initializes servlet when first loaded.

service() Handles requests and responses.

doGet() Handles HTTP GET requests (like typing a URL).

doPost() Handles HTTP POST requests (like form submission).

destroy() Cleans up resources before servlet is destroyed.


7. JSP (Java Server Pages)
JSP is used to write dynamic web pages easily using HTML + Java
code.
It’s built on top of Servlets.
Servlet JSP

Java code inside HTML (logic HTML with Java code inside (view
first) first)

Harder to write UI Easier for front-end pages

Best for backend logic Best for presentation layer

8. JSP Life Cycle

JSP is internally converted into a Servlet by the server.

Phase Description

1. Translation JSP is translated into a servlet (.java file).

2. Compilation Servlet is compiled into a .class file.

3. Initialization jspInit() method is called once.

4. Execution _jspService() method called for each request.

5. Destruction jspDestroy() method called before unloading.


10. Servlet vs JSP (Summary Table)

Feature Servlet JSP

Syntax Java code HTML-like

Best For Logic Presentation

Manual (in Automatic (server converts JSP to


Compilation
class) servlet)

Extension .java .jsp

Easy for UI?


Advanced Java
Servlet :-
What is Servlet ?
➢ A Servlet is a Java program that runs on a web server.
➢ It is used to create dynamic web content.
➢ It acts as a middle layer between the client request and the server.
➢ It connects the browser with server-side resources like databases or applications.

Why Use Servlet ?


➢ To create dynamic web pages using Java.
➢ To handle client requests and server responses efficiently.
➢ To build secure, robust, and platform-independent web applications.
➢ To improve performance compared to traditional CGI (Common Gateway Interface).
➢ To easily connect with databases and other backend systems.
➢ To take advantage of reusability and scalability in web development.

How it Works ?
➢ The client (usually a web browser) sends a request to the web server.
➢ The web server passes the request to the Servlet container (like Tomcat).
➢ The Servlet container loads the required Servlet class.
➢ The Servlet processes the request (e.g., reads data, interacts with a database).
➢ The Servlet generates a response (usually HTML).
➢ The web server sends the response back to the client browser.

Life Cycle of Servlet :-


The Servlet life cycle consists of four main stages:
1. Loading and Instantiation

➢ The servlet class is loaded into memory by the container.


➢ Then, an instance of the servlet is created.

2. Initialization (init() method)

➢ The container calls the init() method once.


➢ It is used to initialize the servlet before handling requests.

3. Request Handling (service() method)

➢ The service() method is called for every client request.


➢ It processes the request and sends back a response.

4. Destruction (destroy() method)

➢ The destroy() method is called once before the servlet is unloaded.


➢ It is used to release resources or perform cleanup.

5. Garbage Collection

➢ After destruction, the servlet object is no longer needed.


➢ It becomes eligible for garbage collection by the JVM.

Servlet Life Cycle Methods :-


There are three life cycle methods of a Servlet:
1. init()
2. service()
3. destroy()
1. init() :-

➢ This method is called only once when the servlet is first loaded.
➢ It is used for initializing resources like database connections or configuration settings.

2. service() :-

➢ This method is called each time a client request is received.


➢ It is responsible for processing requests and generating responses.

3. destroy() :-

➢ This method is called once when the servlet is being removed from memory.
➢ It is used to release resources and perform cleanup tasks.
Java Server Page ( JSP ) :-
What is JSP ?
➢ JSP is a server-side technology used to create dynamic web content.
➢ It allows Java code to be embedded directly into HTML pages.
➢ JSP pages are executed on the server to generate dynamic responses for clients.
➢ It is an extension of the Servlet technology, making web development easier and
faster.

Why Use JSP ?


➢ To create dynamic web pages easily.
➢ Simpler and faster than servlets.
➢ Separates design from business logic.
➢ Supports reusable components.
➢ Automatically compiled and platform-independent.

How it Works ?
➢ The client sends a request for a .jsp page.
➢ The web server passes the request to the JSP engine.
➢ The JSP page is converted into a Servlet by the container.
➢ The Servlet is then compiled and executed to generate HTML output.
➢ The response is sent back to the client browser.

Life Cycle of JSP :-


The JSP life cycle consists of five main phases:
➢ The life cycle of JSP includes several phases from creation to destruction.
➢ The JSP page is first created and then translated into a servlet.
➢ The servlet lifecycle manages its execution and response handling.
➢ The entire process is handled automatically by the JSP engine.

1. Translation Phase
➢ The JSP file is translated into a Java Servlet by the JSP container.
➢ This happens only once when the page is first requested.

2. Compilation Phase
➢ The translated servlet file is compiled into bytecode.
➢ This bytecode is then loaded into memory for execution.

3. Initialization (jspInit() method)


➢ The container calls the jspInit() method once to initialize the JSP.
➢ It is used to set up resources needed for processing requests.

4. Request Processing (_jspService() method)


➢ The _jspService() method is called for each client request.
➢ It handles the request and generates a dynamic response.

5. Destruction (jspDestroy() method)


➢ The jspDestroy() method is called when the JSP is about to be removed.
➢ It is used to release resources and perform cleanup tasks.
How to add tomcat Server ?
1. Step 1

2. Step 2

3. Open Apache folder- check & download your tomcat version zip file & extract it
4. Click Next
5. Browse tomcat folder from your folder

6. Finish
How to Create a Dynamic Web Project in Eclipse IDE ?
Step 1: Open your Eclipse IDE then go to the File > New > Other as shown in the below
image.

Step 2: Now in the select wizard search for the Dynamic Web Project as shown in the below
image. And click on the Next button.
Step 3: In the next screen you have to provide your project name as per your choice and
don't touch anything else for now. Click on the Next button.
Step 4: In the next screen just click on the Next button.
Step 5: In the last screen just check out the Generate [Link] deployment descriptor
box because we need it during the development of a Spring MVC project. Now click on
the Finish button and you are done.

Now your Dynamic Web Project is ready and below is the file structure.
Implementation of JSP_Servlet :-
Example :-

Output :-
Servlet & JSP
Steps to Create a First Servlet :-
1. Create a Dynamic Web Project in Eclipse or any IDE.
2. Configure the Apache Tomcat server with your project.
3. Create a new Servlet class inside the src folder.
4. Extend the class from the HttpServlet class.
5. Override the doGet() or doPost() method.
6. Use the [Link]("text/html") method to set the output type.
7. Use PrintWriter out = [Link](); to write output.
8. Print HTML output using [Link]() statements.
9. Configure the servlet in the [Link] file using <servlet> and <servlet-mapping> tags.
10. Create an HTML file to send a request to the servlet using a form or link.

HTTP Request in Servlet :-


➢ HTTP (Hypertext Transfer Protocol) is used for communication between client and
server.
➢ Each request uses a specific HTTP method for different operations.
➢ In servlets, each method is handled by a matching method in HttpServlet class.
➢ The servlet container automatically calls the correct method based on the client
request.

Types of HTTP Request in Servlet :-


1. doGet Method :-
• Description: Handles HTTP GET requests.
• Use Case: Ideal for retrieving information from the server.
Parameters are appended to the URL.
2. doPost Method :-
• Description: Handles HTTP POST requests.
• Use Case: Used for submitting data to be processed to a specified resource.
Commonly used for form submissions.

3. doPut Method :-
• Description: Handles HTTP PUT requests.
• Use Case: Typically used for updating a resource on the server. The entire
representation of the resource is sent in the request.
4. doDelete Method:
• Description: Handles HTTP DELETE requests.
• Use Case: Used to request that a resource be removed. Can delete a specified
resource on the server.

Difference between doGet() and doPost() in Servlet :-


Basis doGet() doPost()

Purpose Used to handle HTTP GET requests. Used to handle HTTP POST
requests.

Data Data is sent through the URL as Data is sent in the request body.
Transmission query parameters.

Visibility Data is visible in the browser’s Data is not visible in the URL.
address bar.

Data Size Limit Limited amount of data can be sent Large amounts of data can be
(URL length limit). sent.

Caching GET requests can be cached by the POST requests are not cached.
browser.

Bookmarking Can be bookmarked because Cannot be bookmarked.


parameters are in the URL.

Use Case Used for retrieving data from the Used for sending or submitting
server. data to the server.

Idempotency Generally idempotent (no change in Non-idempotent (may change


server state). server state).
Example :-
[Link]

[Link] Configuration (if annotation not used) :-

HTML File ([Link]) :-


Output :-
HTML Page -

Web Page –

Console Page -
Steps to Create a JSP Page in a Servlet Project :-
1. Create a Dynamic Web Project in Eclipse or any Java IDE.
2. Configure the Apache Tomcat server with your project.
3. Inside the WebContent folder, create a new JSP file (for example, [Link]).
4. Write basic HTML structure in the JSP file.
5. Add JSP scripting elements if needed (<% %>, <%= %>, or <%! %>).
6. Create a Servlet class inside the src folder.
7. Extend the servlet class from HttpServlet.
8. In the servlet, process user input or perform backend logic.
9. Use [Link]() to send data from servlet to JSP.
10. Forward the request from servlet to JSP using
RequestDispatcher rd = [Link]("[Link]");
11. Call [Link](request, response); to display the JSP page.
12. The JSP page receives data from the servlet and displays it in the browser.

Example: -
HTML File ([Link]) :-
JSP File ([Link]) :-

Output :-
HTML Page –

JSP Page –
Task – Registration Form using JDBC :-
JSP File ([Link]) :-

JSP File ([Link]) :-


Output :-
[Link] Page –

[Link] Page –

Database – student
Servlet & JSP
How to Perform JSP CRUD Application Using PostgreSQL ?
1. Create a PostgreSQL database and a table to store user data.
2. Design a JSP form to collect user input (name, email, etc.).
3. Use JDBC to connect JSP pages with the PostgreSQL database.
4. Write SQL queries to insert, display, update, and delete data.
5. Use PreparedStatement for executing queries securely.
6. Retrieve data using ResultSet and display it in a JSP table.
7. Redirect pages after each operation using [Link]().
8. Test all CRUD operations to ensure smooth database interaction.

How JSP Interacts with Databases Dynamically ?


1. Database Connectivity:
JSP uses JDBC (Java Database Connectivity) to establish a connection between the
web application and the database.
2. Driver Loading:
The database driver (e.g., [Link]) is loaded using [Link]() to
enable communication with the specific database.
3. Establishing Connection:
A connection is created using [Link](), which connects JSP to
the database using the URL, username, and password.
4. Executing SQL Queries:
SQL queries like INSERT, SELECT, UPDATE, or DELETE are executed using Statement or
PreparedStatement objects.
5. Dynamic Data Handling:
The JSP page retrieves user inputs with [Link]() and uses them in SQL
queries to store or fetch data dynamically.
6. Displaying Results:
Data fetched from the database using a ResultSet is displayed on the web page in
real-time using JSP expressions (<%= %>).
7. Closing Connections:
After execution, all database objects (ResultSet, Statement, Connection) are closed to
release resources and maintain performance.
Modules of the Application :-
1. Registration Form ([Link])
• This page contains a simple HTML form that allows the user to input their details
such as:

• Full Name

• Email

• Password

• Contact Number
• The form uses the POST method and submits the entered data to [Link] for
processing.

2. Data Insertion ([Link])


• This file retrieves the form data using the [Link]() method.
• It establishes a connection to the PostgreSQL database using the JDBC driver.
• A PreparedStatement is used to execute an INSERT query, which adds the user's data
into the student table.
• Once the record is successfully inserted, the user is redirected to the Welcome Page
([Link]) using [Link]().
Key Concepts Used:
• [Link]("[Link]") – Loads PostgreSQL driver.
• [Link]() – Connects JSP to the PostgreSQL database.
• PreparedStatement – Used to safely insert data and prevent SQL Injection.

3. Display Records ([Link])


• This page retrieves all the stored records from the database using a SELECT * FROM
student query.
• A ResultSet object is used to display data dynamically inside an HTML table.
• Each record is shown with a “Delete” link that passes the record ID to [Link] for
deletion.
Purpose:
To view all registered users in a structured tabular format directly from the database.
4. Delete Operation ([Link])
• This page performs the DELETE operation using the ID value passed from the
welcome page.
• It prepares a SQL statement DELETE FROM student WHERE id=? to remove the
selected record.
• After deleting, the page redirects back to the welcome page to refresh the record list.
Key Concept Used:
PreparedStatement ensures secure deletion of records without SQL injection risks.
Example – Registration Form
[Link] –

[Link] –
[Link] –
[Link] –
Output –
[Link] Page -

[Link] Page -
Database - Student
Servlet & JSP
Modules of the Application :-
1. Display Records ([Link])
➢ This page displays all student records from the database in a tabular format.
➢ It loads the PostgreSQL driver using [Link]("[Link]") and
connects to the database using [Link]().
➢ A Statement object executes a SELECT query to fetch all records from the student
table.
➢ The results are retrieved using a ResultSet and displayed dynamically inside an HTML
<table> using JSP scriptlets.
➢ Each record includes two action links — Delete and Profile Edit for managing data.
Key Concepts Used:
1. [Link]("[Link]") – Loads the PostgreSQL JDBC driver.
2. [Link]() – Establishes the database connection.
3. Statement and ResultSet – Used to fetch and display records.
4. [Link]() – Used later for page navigation.
5. JSP Scriptlets – For dynamically embedding Java code inside HTML.

2. Edit Records (profile_edit.jsp)


➢ This page retrieves a specific student record using the student’s ID passed through
the request parameter.
➢ It connects to the PostgreSQL database using JDBC to execute a SELECT query for that
ID.
➢ The fetched data is displayed inside an HTML form with fields pre-filled using JSP
expressions.
➢ The user can modify any detail and submit the form to save changes.
➢ The form sends the updated data to [Link] using the POST method.
Key Concepts Used:
1. [Link]() – Retrieves the student’s ID from the URL.
2. [Link]() and [Link]() – Establish database
connection.
3. ResultSet – Fetches data for the selected student.
4. JSP Expression Tags <%= %> – Display dynamic values inside form fields.
5. Form Handling – Enables data update through POST submission.
3. Update Records ([Link])
➢ This page receives updated data from the Edit Form using [Link]().
➢ It loads the PostgreSQL driver and connects to the database using JDBC.
➢ A PreparedStatement executes an UPDATE query to modify existing data in the
student table.
➢ The PreparedStatement ensures safe query execution and prevents SQL Injection.
➢ After the update, the user is redirected to [Link] using
[Link]().
Key Concepts Used:
1. PreparedStatement – Safely updates records in the database.
2. setString() and setInt() – Used to set dynamic query parameters.
3. executeUpdate() – Executes the UPDATE query.
4. [Link]() – Redirects to the Welcome Page after updating.
5. JDBC + JSP Integration – Demonstrates server-side data update using JSP and
PostgreSQL.
Example :-
[Link] -

profile_edit.jsp -
[Link] -
Output :-
Welcome Page -

Profile Edit Page -

Profile Save Page -


What Is a Session in JSP?
➢ A session stores user data across multiple HTTP requests.
➢ HTTP is stateless, so it cannot remember users between requests.
➢ Sessions solve this by assigning each user a unique session ID for identification.
Each session is associated with one user and is maintained until:
• The user logs out, or
• The session times out (default: 30 minutes), or
• The browser is closed.

How JSP Manages Session ?


➢ JSP manages sessions using the HttpSession object.
➢ Each user gets a unique session ID, usually stored in a cookie.
➢ The browser sends this ID with each request to identify the user.
➢ Data is stored using methods like setAttribute() and getAttribute().
➢ The session lasts until it is invalidated or times out.

Session Object in JSP :-


➢ The session object in JSP is an implicit object used to maintain user data.
➢ It represents the HttpSession created for each user.
➢ Data can be stored and retrieved using setAttribute() and getAttribute().
➢ Each session has a unique ID and lasts until it expires or is invalidated.
Common Session Methods :-
Method Description

setAttribute(String name, Object value) Stores a value in the session.

getAttribute(String name) Retrieves a stored value.

removeAttribute(String name) Deletes a session attribute.

invalidate() Ends the session completely.

getId() Returns the unique session ID.

getCreationTime() Returns time when session was created.

getLastAccessedTime() Returns last time the session was accessed.

isNew() Returns true if the session is new.


Example :- Login System using JSP Session
[Link] -

[Link] –
[Link] -

[Link] -
Output :-
Login Page -

Dashboard Page –

Logout Page –

You might also like