Server-Side Programming: Core Java Web Technologies
Server-side programming involves scripts and programs running on the web server to generate
dynamic content, manage database interactions, and handle user authentication.
1. Java Servlets
Servlets are the foundation of Java web development. They are Java classes that run on a web
server (like Tomcat) and handle HTTP requests/responses.
Lifecycle: init() service() (handles doGet, doPost, etc.) destroy().
Key Features: Platform-independent, efficient (multi-threaded), and direct access to the
Java API.
Best For: Low-level logic, handling data processing, and acting as a controller.
A Servlet is a server-side Java program that handles client requests and generates dynamic
responses. Its life cycle is managed by the Servlet container using the [Link] API.
Managed by the Servlet container through defined life cycle methods
Helps build efficient and scalable web applications
Note: In Jakarta EE 9 and above, use the [Link].* package instead of the older
[Link].* namespace.
States of the Servlet Life Cycle
The Servlet life cycle consists of four main stages:
Loading a Servlet
Initializing a Servlet
Handling Client Requests
Destroying a Servlet
1. Loading a Servlet
The first stage of the Servlet lifecycle involves loading and initializing the Servlet. The Servlet
container performs the following operations:
Loading: The Servlet container loads the Servlet class into memory.
Instantiation: The container creates an instance of the Servlet using the no-argument
constructor.
When is a Servlet loaded?
During application startup (if configured in deployment descriptor).
On first client request (lazy loading).
2. Initializing a Servlet
After instantiation, the container initializes the Servlet using the init() method.
init(ServletConfig config) method is called once in the Servlet’s lifetime.
It prepares the Servlet to handle requests (e.g., database connection setup).
Called only once, unlike service() which is called per request.
Example:
@Override
public void init() throws ServletException {
// Initialization code (e.g., database connection)
}
3. Handling request
Once initialized, the Servlet is ready to handle client requests.
3.1 Request and Response Objects
ServletRequest and ServletResponse objects are created for each request.
For HTTP, HttpServletRequest and HttpServletResponse objects are used.
3.2 The service() Method
The container calls service(ServletRequest req, ServletResponse res) for each request.
Determines the HTTP request type (GET, POST, PUT, DELETE).
Delegates the request to appropriate methods: doGet(), doPost(), etc.
Example:
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
// Handle request and generate response
4. Destroying a Servlet
When the Servlet container decides to remove the Servlet, it follows these steps which are
listed below
Allow Active Threads to Complete: The container ensures that all threads executing the
service() method complete their tasks.
Invoke the destroy() Method: The container calls the destroy() method to allow the
Servlet to release resources (e.g., closing database connections, freeing memory).
Release Servlet Instance: After the destroy() method is executed, the Servlet container
releases all references to the Servlet instance, making it eligible for garbage collection
Servlet Life Cycle Methods
There are three life cycle methods of a Servlet:
init()
service()
destroy()
Life Cycle of Servlet
1. init() Method
Invoked once when the Servlet is instantiated.
Used to initialize resources (e.g., database connections).
Prefer the non-parameterized init() method for fewer redundant calls.
Example:
@Override
public void init() throws ServletException {
// Initialization code
Exception handling is possible in init().
Constructor is not recommended for initialization because it cannot throw
ServletException.
2. service() Method
Handles client requests and responses.
Determines HTTP request type (GET, POST, PUT, DELETE) and delegates
to doGet(), doPost(), etc.
Example:
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
// Request handling code
Connects client and server.
Accepts ServletRequest and ServletResponse objects.
3. destroy() Method
Called once at the end of the Servlet’s life cycle.
Cleans up resources (e.g., closes DB connections, releases memory).
Example:
@Override
public void destroy() {
// Cleanup code
Java Servlet Example
Below is a sample program to illustrate Servlet in Java.
import [Link].*;
import [Link].*;
import [Link].*;
public class AdvanceJavaConcepts extends HttpServlet {
private final String output; // Immutable (thread-safe)
@Override
public void init() throws ServletException {
output = "Advance Java Concepts";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
[Link]("text/html");
try (PrintWriter out = [Link]()) {
[Link](output); // Thread-safe
@Override
public void destroy() {
[Link]("Servlet destroyed");
Explanation:
init() Method: Initializes the output variable when the Servlet is first loaded.
doGet() Method: Responds to client GET requests and prints the output as HTML.
Thread Safety: output is immutable, ensuring safe access by multiple threads.
destroy() Method: Invoked before Servlet removal to release resources or perform
cleanup.
Deployment Descriptor ([Link])
The [Link] file is the heart of a traditional Java web application. It is an XML file located in the
WEB-INF directory.
Purpose: It tells the Servlet Container (Web Server) how to run the application.
Key Configurations:
o Mapping URLs to specific Servlets.
o Configuring Session timeouts.
o Setting up welcome files (e.g., [Link]).
o Security constraints and error pages.
Explain JSP life cycle phases.
Life Cycle Of JSP
A JSP life cycle can be defined as the entire process from its creation till the destruction.
It is similar to a servlet life cycle with an additional step which is required to compile a JSP into
servlet.
A JSP page is converted into Servlet in order to service requests.
The translation of a JSP page to a Servlet is called Lifecycle of JSP.
JSP Life Cycle
JSP Lifecycle steps
Translation of JSP to Servlet code.
Compilation of Servlet to bytecode.
Loading Servlet class.
Creating servlet instance.
Initialization by calling jspInit() method
Request Processing by calling _jspService() method
Destroying by calling jspDestroy() method
Web Container translates JSP code into a servlet source(.java) file.
Then compiles that into a java servlet class (bytecode).
In the third step, the servlet class bytecode is loaded using classloader in web container.
The Container then creates an instance of that servlet class.
The initialized servlet can now service request.
For each request the Web Container call the _jspService() method.
When the Container removes the servlet instance from service, it calls the jspDestroy() method
to perform any required clean up.
MVC Architecture
The Model-View-Controller is a design pattern used to separate the business logic, the data,
and the user interface.
Model: Represents the data and business logic (Java Beans, Databases).
View: The presentation layer the user interacts with (JSP, JSF, HTML).
Controller: The brain that processes requests, interacts with the Model, and chooses
which View to display (Servlets).
JDBC (Java Database Connectivity)
JDBC is an API that helps applications to communicate with databases. It allows Java programs
to connect to a database, run queries, retrieve and manipulate data. Because of JDBC, Java
applications can easily work with different relational databases like MySQL, Oracle, PostgreSQL
and more.
JDBC Architectue
Components of JDBC
1. Application: It can be a Java application or servlet that communicates with a data source.
2. JDBC API: It allows Java programs to execute SQL queries and get results from the database.
Some key components of JDBC API include
Interfaces like Driver, ResultSet, RowSet, PreparedStatement and Connection that helps
managing different database tasks.
Classes like DriverManager, Types, Blob and Clob that helps managing database
connections.
3. DriverManager: It plays an important role in the JDBC architecture. It uses some database-
specific drivers to effectively connect enterprise applications to databases.
4. JDBC drivers: These drivers handle interactions between the application and the database.
JDBC Processing Models
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 Drivers
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
Manages JDBC drivers and establishes database
DriverManager
connections.
Connection Represents a session with a specific database.
Statement Used to execute static SQL queries.
Precompiled SQL statement, used for dynamic
PreparedStatement
queries with parameters.
Used to execute stored procedures in the
CallableStatement
database.
Represents the result set of a query, allowing
ResultSet
navigation through the rows.
Handles SQL-related exceptions during database
SQLException
operations.