JAVA - UNIT IV
Introduction to Java Server Pages
JSP is used as a problem-solving technology for creating dynamic, platform-independent web applications.
A popular server-side technology that makes it possible to create dynamic, platform-independent web
applications is Java Server Pages (JSP). Because it enables developers to embed Java code directly
within HTML pages, it makes creating Java-based online apps easier.
What is JSP in Java?
JSP (Java Server Pages) is a technology developed by Sun Microsystems (now Oracle) that allows
developers to create dynamic web content using Java. It is an extension of Servlets, offering a more flexible
and readable way to embed Java logic within HTML.
Unlike Servlets, which require Java code for everything, JSP allows developers to use special JSP tags to
integrate Java logic within an HTML page. This makes JSP a preferred choice for web applications requiring
dynamic content generation.
Key Features of JSP
1. Separation of Business Logic and Presentation: Unlike Servlets, JSP enables better separation
between UI (HTML) and backend logic (Java code).
2. Reusability: JSP supports reusable components like JavaBeans, custom tags, and Expression
Language (EL).
3. Simplified Code Management: HTML and Java code can coexist in a single file, making development
more intuitive.
4. Platform Independence: Runs on any platform that supports a Java Virtual Machine (JVM), ensuring
broad compatibility.
5. Built-in Session Management: JSP provides built-in session tracking, making state management
easier.
How Does JSP Work?
JSP follows a request-response cycle similar to Servlets but with an additional step for compilation. Here’s
how JSP works:
1
Jaswant Kunwar
1. Client Request: The user requests a JSP page via a web browser.
2. JSP Compilation: The JSP file is compiled into a Servlet by the JSP engine.
3. Servlet Execution: The generated Servlet processes user input, interacts with databases, and
generates the necessary HTML response.
4. Dynamic Content Generation: The compiled Servlet executes the logic and sends an HTML response
to the client.
5. Response Delivery: The final output is displayed in the user’s browser.
Since JSP pages are converted into Servlets, they offer the same performance and scalability benefits as
Java Servlets.
JSP vs. Servlets: Understanding the Differences
2
Jaswant Kunwar
Feature JSP Servlets
Syntax HTML with embedded Java Pure Java code
Readability Easier for designers More complex for non-developers
Maintenance Easier due to separation of concerns Harder to maintain
Performance Slightly slower due to compilation overhead Faster execution
Core Components of JSP
1. JSP Directives
JSP directives provide instructions to the JSP container about how to process the page. Common directives
include:
• page directive: Defines page attributes like language, error handling, and buffer size.
• include directive: Includes content from another file.
• taglib directive: Declares custom tag libraries.
Example:
1<%@ page language="Java" contentType="text/html; charset=UTF-8" %>
2. JSP Scriptlets
Scriptlets allow embedding Java code within HTML.
Example:
1<%
2String message = "Hello, JSP!";
3%>
4<p><%= message %></p>
Here, <%= message %> dynamically outputs the Java variable value.
3. JSP Expressions
Expressions are used to output values directly within an HTML response.
Example:
1<p>Current time: <%= new [Link]() %></p>
This dynamically displays the current server time.
3
Jaswant Kunwar
This dynamically displays the current server time.
4. JSP Declarations
Declarations define class-level variables and methods.
Example:
1 <%! int count = 0; %>
By doing this, an integer variable that holds its value throughout requests is declared.
Advantages of JSP in Java
1. Simplified Web Development: By embedding Java code into HTML, JSP makes web development
faster and more intuitive.
2. Enhanced Maintainability: With JSP, business logic can be separated from presentation using
JavaBeans and MVC architecture.
3. Session Management: JSP provides built-in session tracking to maintain user states.
4. Integration with Java Technologies: Works seamlessly with Java Servlets, JDBC, and JavaBeans.
5. Scalability: JSP is highly scalable and can handle large enterprise applications efficiently.
Common Use Cases for JSP
JSP is used by many industries to build interactive web applications. Here are some common use cases:
1. E-commerce Websites
JSP is used in e-commerce platforms for:
• Displaying dynamic product listings.
• Handling user authentication and session management.
• Processing shopping cart functionality.
2. Content Management Systems (CMS)
JSP is used in CMS solutions to:
• Storing and updating digital content.
• Provide user authentication for restricted content.
3. Online Forms & Surveys
JSP is effective in creating online forms that:
• Collect and process user input.
• Store data in a backend database(db).
4. Enterprise Applications
JSP is used in enterprise software solutions, such as HR and finance applications, due to its scalability and
security features.
4
Jaswant Kunwar
Challenges and Considerations
While JSP offers several benefits, developers must be aware of the following challenges:
1. Performance Overhead: The compilation of JSP pages may introduce a slight delay in execution.
2. Security Risks: If not implemented properly, JSP applications can be vulnerable to SQL injection,
cross-site scripting (XSS), and session hijacking.
3. Complexity in Large-Scale Projects: For extensive applications, adopting Java frameworks
like Spring MVC is often a better choice.
To mitigate these challenges, developers should follow best coding practices, implement security
mechanisms, and optimize application performance.
How is JSP More Advantageous than Servlets?
JSP simplifies web development by combining the strengths of Java with the flexibility of HTML. Some
advantages of JSP over Servlets are listed below:
• JSP code is easier to manage than Servlets as it separates UI and business logic.
• JSP minimizes the amount of code required for web applications.
• Generate content dynamically in response to user interactions.
• It provides access to the complete range of Java APIs for robust application development.
• JSP is suitable for applications with growing user bases.
JSP Architecture
JSP follows a three-layer architecture:
• Client Layer: The browser sends a request to the server.
• Web Server Layer: The server processes the request using a JSP engine.
• Database/Backend Layer: Interacts with the database and returns the response to the client.
5
Jaswant Kunwar
The web server needs a JSP engine, i.e, a container to process JSP pages. The JSP container is responsible
for intercepting requests for JSP pages. This tutorial makes use of Apache which has built-in JSP container
to support JSP pages development.
A JSP container works with the Web server to provide the runtime environment and other services a JSP
needs. It knows how to understand the special elements that are part of JSPs.
Following diagram shows the position of JSP container and JSP files in a Web application.
JSP Processing
The following steps explain how the web server creates the Webpage using JSP −
• As with a normal page, your browser sends an HTTP request to the web server.
• The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP engine.
This is done by using the URL or JSP page which ends with .jsp instead of .html.
• The JSP engine loads the JSP page from disk and converts it into a servlet content. This conversion is
very simple in which all template text is converted to println( ) statements and all JSP elements are
converted to Java code. This code implements the corresponding dynamic behavior of the page.
• The JSP engine compiles the servlet into an executable class and forwards the original request to a
servlet engine.
• A part of the web server called the servlet engine loads the Servlet class and executes it. During
execution, the servlet produces an output in HTML format. The output is furthur passed on to the
web server by the servlet engine inside an HTTP response.
• The web server forwards the HTTP response to your browser in terms of static HTML content.
• Finally, the web browser handles the dynamically-generated HTML page inside the HTTP response
exactly as if it were a static page.
All the above mentioned steps can be seen in the following diagram −
6
Jaswant Kunwar
Typically, the JSP engine checks to see whether a servlet for a JSP file already exists and whether the
modification date on the JSP is older than the servlet. If the JSP is older than its generated servlet, the JSP
container assumes that the JSP hasn't changed and that the generated servlet still matches the JSP's
contents. This makes the process more efficient than with the other scripting languages (such as PHP) and
therefore faster.
So in a way, a JSP page is really just another way to write a servlet without having to be a Java programming
wiz. Except for the translation phase, a JSP page is handled exactly like a regular servlet.
Life Cycle of JSP
The life cycle of a JavaServer Page (JSP) consists of various phases that start from its creation, followed by
its translation into a servlet, and finally managed by the servlet lifecycle. The JSP engine handles this
process automatically.
7
Jaswant Kunwar
Servlet
Steps of JSP Life Cycle
1. Translation of JSP page to Servlet
2. Compilation of JSP page(Compilation of JSP into [Link])
3. Classloading ([Link] to [Link])
4. Instantiation(Object of the generated Servlet is created)
5. Initialization(jspInit() method is invoked by the container)
6. Request processing(_jspService()is invoked by the container)
7. JSP Cleanup (jspDestroy() method is invoked by the container)
. Translation of JSP to Servlet
• The JSP file is parsed and converted into a Java servlet source file ([Link]).
• This step checks for syntax correctness.
// The JSP is converted to a servlet class.
public class TestServlet extends HttpServlet {
// The generated servlet code
}
2. Compilation of JSP page
• The generated [Link] file is compiled into a class file ([Link]).
• This step converts the servlet code into bytecode.
8
Jaswant Kunwar
// JSP is automatically converted into a servlet, such as
public class TestServlet extends HttpServlet {
// Generated servlet code here
}
3. Classloading
• The container dynamically loads the compiled class.
4. Instantiation
• The container creates an instance of the generated servlet class.
• This instance handles multiple requests unless explicitly configured otherwise.
// The container creates an instance automatically.
TestServlet servlet = new TestServlet();
5. Initialization (jspInit())
• This method is called only once when the JSP is first loaded.
• It is used for initializing resources like database connections or configurations.
public void jspInit() {
// Initialization code, like setting up resources.
[Link]("JSP Initialized.");
}
6. Request Processing (_jspService())
• This method is called for every request.
• It cannot be overridden because it is auto-generated and declared as final.
• It receives HttpServletRequest and HttpServletResponse objects to handle the request.
public void _jspService(HttpServletRequest request, HttpServletResponse response) {
// Code that handles the request, like generating HTML output.
[Link]().write("<html><body>Hello, World! </body></html>");
}
7. JSP Cleanup (jspDestroy())
9
Jaswant Kunwar
• This method is called once before removing the JSP from service.
• It is used for releasing resources, such as closing database connections or cleaning up open files.
public void jspDestroy() {
// Clean up resources like closing database connections.
[Link]("JSP Destroyed.");
}
This Lifecycle ensures that JSP pages are efficiently compiled, managed and cleaned up by the server
container
JDBC
Inspired by the original ODBC (Open Database Connectivity), the JDBC stands for Java Database
Connectivity. JDBC is a Java database API that was created as an industry standard for making connections
between Java applications and other databases. The Java JDBC connection in Java API defines all classes
that handle various aspects of the database, such as connection details, result sets, and database
metadata. Originally, JDBC was intended to be a client-side API that could connect to a data source. In
version 2.0, it was added with an optional package that supports server-side connections. Since then, every
new release of JDBC has included updates to both the client-side and server-side packages. The most
recent version, which was released in September 2017, was part of Java SE 9.
More so, it supports various types of relational databases which use SQL (Structured Query Language) such
as DB2, ORACLE, and Sybase. Each of these possesses a unique JDBC driver name, that encodes access
request statements, issues commands, and handles result sets obtained from the database.
Understanding JDBC in Java
Before we delve into the detailed processes of creating a JDBC connection with databases like SQL, we have
to understand all the concepts, tools, classes, and interfaces involved such as JDBC components, JDBC
drivers, as well as the relations between relational databases like SQL and JDBC.
10
Jaswant Kunwar
Creating JDBC Application
There are following six steps involved in building a JDBC application −
• Import the packages − Requires that you include the packages containing the JDBC classes needed
for database programming. Most often, using import [Link].* will suffice.
• Open a connection − Requires using the [Link]() method to create a
Connection object, which represents a physical connection with the database.
• Execute a query − Requires using an object of type Statement for building and submitting an SQL
statement to the database.
• Extract data from result set − Requires that you use the appropriate [Link]() method to
retrieve the data from the result set.
• Clean up the environment − Requires explicitly closing all database resources versus relying on the
JVM's garbage collection.
JDBC Architecture
Explanation:
• Application: It can be a Java application or servlet that communicates with a data source.
• The JDBC API: It allows Java programs to execute SQL queries and get results from the database.
Some key components of JDBC API include
o Interfaces like Driver, ResultSet, RowSet, PreparedStatement, and Connection that helps
managing different database tasks.
o Classes like DriverManager, Types, Blob, and Clob that helps managing database
connections.
• DriverManager: It plays an important role in the JDBC architecture. It uses some database-specific
drivers to effectively connect enterprise applications to databases.
• JDBC drivers: These drivers handle interactions between the application and the database.
11
Jaswant Kunwar
The JDBC architecture consists of two-tier and three-tier processing models to access a database. They are
as described below:
1. Two-Tier Architecture
A Java Application communicates directly with the database using a JDBC driver. It sends queries to the
database and then the result is sent back to the application. For example, in a client/server setup, the
user's system acts as a client that communicates with a remote database server.
Structure:
Client Application (Java) -> JDBC Driver -> Database
2. Three-Tier Architecture
In this, user queries are sent to a middle-tier services, which interacts with the database. The database
results are processed by the middle tier and then sent back to the user.
Structure:
Client Application -> Application Server -> JDBC Driver -> Database
JDBC Components
There are generally 4 main components of JDBC through which it can interact with a database. They are as
mentioned below:
1. JDBC API
It provides various methods and interfaces for easy communication with the database. It includes two key
packages
• [Link]: This package, is the part of Java Standard Edition (Java SE) , which contains the core
interfaces and classes for accessing and processing data in relational databases. It also provides
essential functionalities like establishing connections, executing queries, and handling result sets
• [Link]: This package is the part of Java Enterprise Edition (Java EE) , which extends the
capabilities of [Link] by offering additional features like connection pooling, statement pooling,
and data source management.
It also provides a standard to connect a database to a client application.
2. JDBC Driver Manager
Driver manager is responsible for loading the correct database-specific driver to establish a connection with
the database. It manages the available drivers and ensures the right one is used to process user requests
and interact with the database.
3. JDBC Test Suite
It is used to test the operation (such as insertion, deletion, updating) being performed by JDBC Drivers.
4. JDBC Drivers
12
Jaswant Kunwar
JDBC drivers are client-side adapters (installed on the client machine, not on the server) that convert
requests from Java programs to a protocol that the DBMS can understand. There are 4 types of JDBC
drivers:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver (partially java driver)
3. Type-3 driver or Network Protocol driver (fully java driver)
4. Type-4 driver or Thin driver (fully java driver) - It is a widely used driver. The older drivers like (JDBC-
ODBC) bridge driver have been deprecated and no longer supported in modern versions of Java.
JDBC Classes and Interfaces
Class/Interfaces Description
DriverManager Manages JDBC drivers and establishes database connections.
Connection Represents a session with a specific database.
Statement Used to execute static SQL queries.
Precompiled SQL statement, used for dynamic queries with
PreparedStatement
parameters.
CallableStatement Used to execute stored procedures in the database.
Represents the result set of a query, allowing navigation
ResultSet
through the rows.
SQLException Handles SQL-related exceptions during database operations.
Steps to Connect to MySQL Database Using JDBC
Step 1: Load the JDBC Driver
[Link]("[Link]");
Step 2: Establish a Connection
Connection connection = [Link]("jdbc:mysql://localhost:3306/your_database",
"your_username","your_password");
13
Jaswant Kunwar
Step 3: Create a Statement
Statement statement = [Link]();
Step 4: Execute a Query
String query = "INSERT INTO students (id, name) VALUES (101, 'John Doe')";
int rowsAffected = [Link](query);
[Link]("Rows affected: " + rowsAffected);
Step 5: Close the Connection
[Link]();
[Link]();
Create a Simple JDBC Application
The below Java program demonstrates how to establish a MYSQL database connection using JDBC and
execute a query.
// Java program to implement a simple JDBC application
import [Link].*;
public class Geeks {
public static void main(String[] args)
{
// Database URL, username, and password
// Replace with your database name
String url= "jdbc:mysql://localhost:3306/your_database";
// Replace with your MySQL username
String username = "your_username";
// Replace with your MySQL password
String password = "your_password";
// Updated query syntax for modern databases
14
Jaswant Kunwar
String query
= "INSERT INTO students (id, name) VALUES (109, 'bhatt')";
// Establish JDBC Connection
try {
// Load Type-4 Driver
// MySQL Type-4 driver class
[Link]("[Link]");
// Establish connection
Connection c = [Link](
url, username, password);
// Create a statement
Statement st = [Link]();
// Execute the query
int count = [Link](query);
[Link]( "Number of rows affected by this query: " + count);
// Close the connection
[Link]();
[Link]();
[Link]("Connection closed.");
}
catch (ClassNotFoundException e) {
[Link]("JDBC Driver not found: “ + [Link]());
}
catch (SQLException e) {
[Link]("SQL Error: “ + [Link]());
15
Jaswant Kunwar
}
}
}
Output:
Servlet
A Servlet is a program that runs on a web server and can process your request and send the right content
back. These programs have a life cycle from creation to destruction.
Introduction to Servlet
When we search Google for any webpage, we request that a server render that particular web page.
Handling such requests and rendering web pages dynamically can be done using Java Servlets.
Java Servlets (also known as Jakarta Servlets) are server-side programs that run on a web server. They act as
a middle layer between client requests and the web server's database/applications.
They are used to host web applications on servers and mostly support all client-server protocols. The
architecture of the servlet is as follows:
16
Jaswant Kunwar
Client/Browser: The client through the browser sends HTTP requests to the webserver.
Web Server: Includes several components to control access to files hosted on the server. A basic HTTP
server will comprehend URLs and follow HTTP protocol to deliver the contents of hosted websites.
Web Container: This web server component interacts with Java servlets. It manages the servlets' life cycle,
including loading and unloading, managing request and response objects, and URL mapping on the server-
side. Ex: Tomcat.
Servlet Life Cycle
Servlet Life Cycle can be described as a series of steps that a servlet goes through during its life span from
loading to destruction.
The Servlet Life Cycle is as follows:
• Servlet class is loaded first when the Web container receives a new request.
• Then, the web container creates a servlet instance. This instance is created only once in the entire
Servlet Life Cycle.
• The servlet is initialized using the init() method.
• the servlet calls service() method to process the client's request.
• The server is destroyed using the destroy() method.
• Java Virtual Machine's(JVM) garbage collector clears the destroyed servlet's memory.
Let us see the signature for each of the methods mentioned above:
17
Jaswant Kunwar
init()
Whenever a user invokes the URL associated with the particular servlet, the init() method is called. It is
called only once, not each time a request is made. An instance of a servlet is created through
the init() method. Each user request creates a new thread catering to GET and POST requests.
Ex.-
public void init(ServletConfig config) throws ServletException{
//initialization code
}
service()
The web container calls the service() method each time there is a new request to the servlet. This is done
by spawning a new thread. This method checks the HTTP request type, i.e, whether it is a GET, POST,
DELETE, etc, and calls the doGet, doPost, doDelete, etc methods as per the request.
Ex.-
public void service(ServletRequest request, ServletResponse response) throws ServletException,
IOException{
//doGet, doPost, doDelete etc as per request
}
destroy()
This method is called just once at the end of the Life Cycle of Servlet. It helps perform all the clean-up
activities, including closing database connections and halting background threads. Then, the servlet is
removed from the container.
Ex.-
public void destroy (){
//clean-up code
}
Architecture Diagram of the Servlet Life Cycle in Java
The following represents the Servlet Life Cycle. When a request is sent for a particular web page, the
corresponding servlet must be initialized. The servlet container/web container will load the servlet and
create an instance of it through init().
18
Jaswant Kunwar
Subsequent requests to the same web page will invoke the service() method. This method will typecast the
ServletRequest and ServletResponse objects to HttpServletRequest and HttpServletResponse objects,
respectively. Servlets can handle multiple requests concurrently since each request results in a new thread.
The destroy() method is only called once all threads within the servlet's service methods have exited or
after a timeout period.
Program Illustrating Java Servlet Implementation
A program illustrating Java Servlet implementation We can implement a Servlet in the following ways:
1. By implementing Servlet interface
2. By extending GenericServlet class
3. By extending HttpServlet class
The easiest and most common way is to extend the HTTPServlet class. Let's see a servlet's Hello
World program using this method.
19
Jaswant Kunwar
import [Link].*;
import [Link].*;
import [Link].*;
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
//Set content type
[Link]("text/html");
//Get the stream to write data
PrintWriter out = [Link]();
//Write HTML in stream
[Link]("<html><body>");
[Link]("<h1>Hello World</h1>");
[Link]("</body></html>");
//Close the stream
[Link]();
}
}
The HttpServlet class is extensively used to create servlets since it provides methods to handle HTTP
requests like doGet(),doPost, doDelete(), etc. The above code is used to display HTML content on the web
page displaying "Hello World".
Features of Java Servlet Life Cycle
1. Portable
Java's portability comes from the fact that It is portable. This means that the Java code is compiled into
bytecode, which is platform-independent. Hence, it is Write Once Run Anywhere (WORA).
2. Efficient
20
Jaswant Kunwar
Efficient because it creates a new thread for each request and not each process.
3. Scalable
Due to multithreading, Servlets can handle multiple requests and are scalable to be quite responsive.
Servlets are also amenable to various load distribution architectures. With the right load distribution, we
can easily scale web applications.
4. Robust
JVM handles all the Servlet programs, including garbage collection and memory leaks prevention.
Benefits of Servlets
Easy to implement
It is wasy to implement Servlet using Java APIs. It is also easy to implement sessions and cookies since
dedicated interfaces are provided for each use case.
Easy Database Connection
Using' CGI', we could not connect to the database directly. However, using Servlets, we can connect to the
database directly and track sessions.
Protocol Independent
Servlets are flexible to follow any web protocol, including FTP, and HTTP.
Better Exception Handling
Earlier, CGI(Common Gateway Interface) scripts, which were used before Servlets and written in C++, did
not have good exception handling. For instance, the application might crash if there was a divide by 0 error.
Servlets, written in Java, have much better ways to handle such exceptions and ensure the application
doesn't crash. They also have provisions for redirection and forwarding.
Security
The server-side components inherit the security of the webserver. And the Servlet programs benefit from
Java's Security Manager.
Conclusion
• Java Servlets are server-side programs that handle and respond to client requests to a web
application through the browser.
• Life Cycle of Servlet consists mainly of three methods - init(), service(), and destroy().
• HTTP requests from clients/browsers can be read. This includes cookies, parameters, and session
handling.
21
Jaswant Kunwar
• HTTP response from the server is sent can be sent to the client in various forms, including text,
documents, HTML, binary, etc.
• Servlets can handle multiple requests concurrently through multithreading. Each new request
spawns a new thread, which consumes less space than creating a new process.
• JVM's garbage collector handles stale data and prevents memory leaks.
22
Jaswant Kunwar