UNIT-4
CHAPTER-1
Servlet
A Servlet is a Java program that runs on a web server and handles client
requests and responses. It is mainly used to create dynamic web applications.
Part of Java EE technology
Runs inside a Servlet Container like Apache Tomcat
Used for processing:
o Form data
o Database interaction
o Session handling
o Dynamic web pages
Advantages of servlet
Servlets offer several advantages in comparison with CGI (Common
Gateway Interface).
First, performance is significantly better.
Servlets execute within the address space of a web server.
It is not necessary to create a separate process to handle each client
request.
Second, servlets are platform-independent because they are written in
Java.
Third, the Java security manager on the server enforces a set of
restrictions to protect the resources on a server machine.
Finally, the full functionality of the Java class libraries is available to a
servlet.
It can communicate with applets, databases, or other software via the
sockets and RMI mechanisms.
Drawbacks of CGI programs.
CGI allowed the separate process to read data from the HTTP request and
write data to the HTTP response.
A variety of different languages were used to build CGI programs. These
included C, C++, and Perl.
However, CGI suffered serious performance problems.
It was expensive in terms of processor and memory resources to create a
separate process for each client request.
It was also expensive to open and close database connections for each
client request.
In addition the CGI programs were not platform independent.
Architecture of Servlet
Client → Web Server → Servlet Container → Servlet → Database
Components of Servlet
1. Client – Browser sends request
2. Web Server – Receives request
3. Servlet Container – Manages servlet lifecycle
4. Servlet – Processes request
5. Database – Stores data
1. Client: The Client is usually a web browser that sends requests to the server.
Example: Google Chrome, Mozilla Firefox, Microsoft Edge.
Function of client
Sends HTTP request
Receives HTTP response
Displays web pages to users
2. Web Server: A Web Server receives requests from clients and forwards
them to the servlet container.
Example: Apache HTTP Server. Apache Tomcat.
Functions of Web Server
Handles HTTP requests
Communicates with servlet container
Sends response back to browser
Working
1. Browser sends request
2. Web server receives request
3. Request forwarded to servlet container
3. Servlet Container: The Servlet Container is the most important component.
It manages the execution of servlets also called: Web Container, Servlet Engine
Example: Apache Tomcat, Glassfish
Responsibilities of Servlet Container
Handling Requests: Receives request and passes it to servlet
Loading Servlet: The container loads the servlet class into memory.
Creating Servlet Object: Only one object of servlet is generally created.
Managing Lifecycle: It calls: init() ,service(),destroy() methods
Multithreading: Handles multiple users simultaneously using threads.
Security: Provides security features like authentication.
Session Management: Maintains user sessions using cookies and sessions.
4. Servlet
A Servlet is a Java class used to handle requests and responses.
Usually extends: HttpServlet
Functions:
1. Reads client request
2. Processes business logic
3. Interacts with database
4. Generates response
5. Database: The database stores application data.
Example: MySQL ,Oracle Database
Function:
Store user information
Save records
Retrieve application data
Methods of Servlet Life Cycle:
The Servlet Life Cycle describes how a servlet is created, used, and destroyed
by the servlet container such as Apache Tomcat. There are three methods are
used.
These are init( ), service( ), and destroy( ). They are implemented by every
servlet and are invoked at specific times by the server.
init(): Called only once when the servlet is loaded into memory. Used for
initialization tasks.
Uses:
Creating database connection
Loading configuration data
Initial setup
public void init() throws ServletException
{
// initialization code
}
Service ():Called every time a client sends a request. Processes the request and
generates the response.
Uses:
Processing form data.
Sending response to browser
Business logic execution.
public void service(ServletRequest req, ServletResponse res) throws
ServletException, IOException
{
// request handling code
}
destroy(): Used for destroying the servlet before removing it from memory.
Used to release resources.
public void destroy( )
{
[Link](“servlet destroyed”);
}
Uses:
Close database connection
Free resources
Interfaces in Servlet: In Java Servlets, an interface declares a set of methods
that a class must implement. Servlet technology provides several important
interfaces used for handling requests, responses, configuration, sessions, and
communication between web resources.
These interfaces belong to the package: [Link], [Link].
Main Interfaces in Servlet
1. Servlet
2. ServletRequest
3. ServletResponse
4. HttpServletRequest
5. HttpServletResponse
1. Servlet Interface: The root interface of servlet technology. Defines lifecycle
methods of a servlet. Every servlet indirectly implements this interface.
Methods of Servlet interface:
1. init(ServletConfig config)
2. service(ServletRequest req, ServletResponse res)
3. destroy()
4. getServletConfig()
5. getServletInfo()
A) init(ServletConfig config ): Called by the servlet container only once when
the servlet is created. Used for initialization tasks. Executes before the servlet
handles any request. Database connection setup. Reading configuration
parameters. Loading resources.
EX: public void init(ServletConfig config)
{
[Link]("Servlet initialized");
}
B) service(ServletRequest req, ServletResponse res): Handles client requests
and generates responses. Called every time a client sends a request. It is used
for reading form data Processing business logic and Sending HTML response.
The parameter req and res are used to store client request data and to send
response back to client.
EX: public void service(ServletRequest req, ServletResponse res)throws
ServletException, IOException
{
PrintWriter out = [Link]( );
[Link]("Hello User");
}
C) destroy( ):Called before the servlet is removed from memory. Executes only
once when: Server shuts down and Servlet is undeployed. Used for Closing
database connections ,releasing resources and Saving clean-up data.
EX: public void destroy( )
{
[Link]("Servlet destroyed");
}
2. ServletRequest Interface: The ServletRequest interface enables a servlet to
obtain information about a client request. Several of its methods are shown in
Table.
Method Description
String getParameter(String name) Returns the value of a request
parameter
String[] getParameterValues(String Returns multiple values of a request
name) parameter
Object getAttribute(String name) It returns the value of an attribute that
was previously stored in the request
object using setAttribute().
Void setAttribute(String name, Object Stores an attribute in request object
obj)
Void removeAttribute(String name) Removes an attribute
String getContentType() Returns MIME type of request body
Int getContentLength() Returns request body size
3. servletResponse interface : ServletResponse interface in Java provides
methods to send responses from a servlet to the client.
Method Description
PrintWriter getWriter() Returns character output stream
ServletOutputStream Returns binary output stream
getOutputStream()
String getCharacterEncoding() Returns character encoding used in the
response
Void setCharacterEncoding(String Sets response character encoding
charset)
String getContentType() Returns MIME type of the response
void setContentType(String type) Sets MIME type of response
Void setContentLength(int len) Sets response content length
4. HttpServletRequest interface: It represents the request sent by the client
(browser) to the servlet.
1. getCookies( ):The getCookies() method is used to retrieve all cookies sent
by the client to the server.(Cookies: A cookie is a small piece of data stored in
the user's browser by the server. Cookies are used to:
remember users
maintain login sessions
track user activity )
Syntax: Cookie[] getCookies()
Returns an array of Cookie objects.
Returns null if no cookies are present.
2. getMethod( ): The getMethod() method is used to obtain the HTTP request
method used by the client.
Syntax: String getMe thod( )
Returns a String
Common values:
"GET"
"POST"
"PUT"
"DELETE"
"HEAD"
3. getSession():The getSession() method is used to obtain the current session
associated with the request.(Session: A session is a mechanism used to store
user-specific data on the server across multiple requests.)
Syntax: HttpSession getSession( )
Returns an object of HttpSession.
4. getPathInfo():The getPathInfo() method returns extra path information
associated with the URL after the servlet path.
Syntax: String getPathInfo( )
Returns a String
Returns null if no extra path information exists
HttpServletResponse interface: It represents the HTTP response sent by the
server to the client (browser). HttpServletResponse is used by a servlet to
send data and response information back to the client. Methods of
HttpServletResponse interface are
Method Description
Returns PrintWriter to send character
PrintWriter getWriter()
data to client
ServletOutputStream Returns ServletOutputStream to send
getOutputStream() binary data
Void setContentType(String type) Sets MIME type (e.g., text/html)
Void setCharacterEncoding(String
Sets response encoding
charset)
Write a Java servlet named FormProcessorServlet that can handle HTTP
POST requests containing form data. The servlet should: Read
Parameters: Extract the names and values of parameters submitted from
the form. Process Data: Access the specific parameter values for fields like
"name" and "email" (assuming those are the form field names). Generate
Response: Create an HTML response that displays the submitted data to
back to the user in a user-friendly formate.
[Link]
<!DOCTYPE html>
<html>
<head>
<title>User Form</title>
</head>
<body>
<form method="post" action="FormProcessorServlet" >
Name: <input type="text" name="name"><br><br>
Email: <input type="email" name="email"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet("/FormProcessorServlet")
public class FormProcessorServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// Set response content type
[Link]("text/html");
// Get form parameters
String name = [Link]("name");
String email = [Link]("email");
// Create response output
PrintWriter out = [Link]();
[Link]("<html>");
[Link]("<head><title>Form Data Result</title></head>");
[Link]("<body>");
[Link]("<h2>Submitted Form Data</h2>");
// Display all parameters
[Link]("<p><strong>Name:</strong> " + name + "</p>");
[Link]("<p><strong>Email:</strong> " + email + "</p>");
[Link]("</body>");
[Link]("</html>");
}
}
The purpose and behavior of the doPost( ) method in a servlet class. The
doPost method is overridden to process any HTTP POST requests that are sent
to the servlet. It uses the getParameter( ) method of HttpServletRequest
interface to obtain the form data that was post by the user. A response is then
formulated.
Ex: refer the above example
JDBC (Java Database Connectivity) is a Java API that java program to
connect and interact with databases. It allows Java programs to execute SQL
queries, retrieve data, and update records in a database such as MySQL, Oracle,
PostgreSQL, or SQLite.
Main functions of JDBC:
Connect to a database
Execute SQL statements
Retrieve query results
Insert, update, and delete data
Manage database transactions
Steps involved in JDBC process(Steps to connect the database)
1. Import JDBC Packages: Import the required JDBC classes from the [Link]
package.
import [Link].*;
2. Load and Register the Driver: Load the database driver so Java can
communicate with the database.
[Link]("[Link]");
3. Establish the connection: Create a connection between the Java application
and the database.
Connection
con=[Link]("jdbc:derby://localhost:1527/student","vani
","1011");
4. Create statement: Create a Statement or PreparedStatement object to send
SQL queries.
Statement stmt = [Link]();
5. Execute SQL Query: Run SQL commands such as SELECT, INSERT,
UPDATE, or DELETE.
ResultSet rs = [Link]("SELECT * FROM students");
executeQuery() → Used for executing SELECT statements
executeUpdate() → Used for executing INSERT, UPDATE, DELETE
statements.
6. Process the result: Retrieve and display data from the ResultSet.
while([Link]())
{
[Link]([Link]("id") + " " + [Link]("name"));
}
7. Close the connection:Close all JDBC objects to free resources.
[Link]();
[Link]();
[Link]();
JDBC Driver: A JDBC Driver is a software component that enables a Java
application to communicate with a database.
It converts JDBC method calls into database-specific commands.
JDBC drivers act as a bridge between:
Java Application
Database Management System (DBMS)
Types of JDBC Driver: There are 4 types of JDBC Drivers:
1. Type 1 Driver – JDBC-ODBC Bridge Driver: Converts JDBC calls into
ODBC calls. It Requires ODBC driver installation on the client machine.
Ex: JDBC-ODBC Bridge
Advantages
Easy to use for small applications
No need of database-specific driver
Disadvantages
Slow performance
Requires ODBC installation
Not suitable for web applications
2. Type 2 Driver – Native API Driver: Converts JDBC calls into native
database API calls. Uses database-specific native libraries.
Ex: Oracle OCI Driver
Advantages
Faster than Type 1
Better performance
Disadvantages
Requires native library installation
Platform dependent
3. Type 3 Driver – Network Protocol Driver: Sends JDBC calls to a
middleware server. Middleware converts requests into database-specific
protocol.
Ex: DataDirect SequeLink
Advantages
Platform independent
No native libraries needed
Disadvantages
Requires middleware server
Network dependency
4. Type 4 Driver – Thin Driver: Directly converts JDBC calls into database-
specific protocol. Communicates directly with the database.
Ex: MySQL Connector/J
Advantages
Fastest performance
Platform independent
No middleware or native libraries required
Most commonly used
Disadvantages
Database-specific driver required
JDBC Statements: Statements are interface used to execute SQL queries
against a database. There are mainly three types of statements in JDBC:
1. Statement: This interface is used to execute simple SQL queries without
parameters. It can be used for executing queries such as SELECT, INSERT,
UPDATE, DELETE, and DDL (Data Definition Language) statements.
Ex:
Statement stmt = [Link]( );
ResultSet rs = [Link]("SELECT * FROM mytable”);
2. PreparedStatement: This interface extends Statement and provides
additional methods for executing parameterized SQL queries.
PreparedStatement is precompiled, which can improve performance when
executing the same SQL statement multiple times with different parameters.
preparedStatement pstmt = [Link]("INSERT INTO my_table
(columnl, column2) VALUES (?, ?)”);
[Link](1, "valuel");
[Link](2, "value2");
int rowsAffected = [Link]( );
3. Callable Statement: This interface is used to execute stored procedures or
functions in the database. Callable Statement allows you to call database stored
procedures or functions with IN, OUT, and INOUT parameters.
CallableStatement cstmt = [Link]("{call mystoredprocedure(?, ?)}");
[Link](1, parameter1);
cstmt. registerOutParameter(2, [Link]);
[Link]( );
int retunValue = [Link](2);
Resultset: A ResultSet is an interface in Java’s JDBC API that represents the
data returned from a SQL query. It acts like a cursor that points to rows in a
database result table.
There are different types of ResultSet:
Forward-only
Scrollable
Updatable
1. Forward-Only ResultSet
This is the default type.
Cursor moves only forward
Cannot go backward or jump to a specific row
Faster and uses less memory
Best for:
Large data reading
Reports
Simple iteration
2. Scrollable ResultSet
A Scrollable ResultSet in JDBC is a type of ResultSet that allows you to move
the cursor forward and backward, as well as to move to a specific row or to a
relative position from the current row. By default, ResultSets in JDBC are
forward-only, meaning you can only traverse them in one direction -forward
from the first row to the last. However, if you need more flexibility in
navigating the result set, you can create a scrollable result set. TWO ResultSet
types:
TYPE_SCROLL_INSENSITIVE ResultSet :
It can be navigated (scrolled) both forward and backwards.
Can also jump to a position relative to the current position, or jump to an
absolute position.
The ResultSet is insensitive to changes in the underlying data source .
If a record in the ResultSet is changed in the database by another thread
or process, it will not be reflected in already opened ResulsSet's of this
type.
TYPE_SCROLL_SENSITIVE ResultSet :
It can be navigated (scrolled) both forward and backwards can also jump
to a position relative to the current position, or jump to an absolute
position
The ResultSet is sensitive to changes in the underlying data Source
If a record in the ResultSet is changed in the database by another thread
or process, it will be reflected in already opened ResulsSet's of this type.
3. Updatable ResultSet: An updatable ResultSet is a feature provided by
JDBC(Java Database Connectivity) that allows you to update the rows retrieved
from a database table through a ResultSet object.
ResultSet concurrency determines whether the ResultSet can be updated, or
only read. Not all databases and JDBC drivers support that the ResultSet is
updated.
ResultSet can have one of two concurrency levels CONCUR_READ_ONLY -
means the ResultSet can only be read.
CONCUR_UPDATABLE be both read and updated.
Methods of resultset:
Method description
boolean first() throws SQLException Moves the cursor to the first row.
boolean last() throws SQLException Moves the cursor to the last row.
boolean next() throws SQL Exception Moves the cursor to the next row. This
method returns false if there are no
more rows in the result set.
boolean previous( ) throws Moves the cursor to the previous row.
SQLException This method returns false if there is no
previous row in the result set.
boolean absolute(int row) thows Moves the cursor to the specified row.
SQLException
Boolean relative(int row) thows Moves the cursor the given number of
SQLException rows forward or backward from where
it is currently pointing.
int getRow( ) thows SQLException Returns the row number that the cursor
is pointing.
JSP: JavaServer Pages (JSP) is a Java technology used to create dynamic
web pages.
It allows you to write HTML along with Java code inside the same file.
Key stages involved in the lifecycle of a Java Server Page (JSP).
The lifecycle of a Java Server Page (JSP) describes the sequence of steps a
JSP goes through from being requested by a client until it is destroyed by the
server. Understanding these stages helps in developing efficient web
applications.
Key Stages in the JSP Lifecycle
1. Translation Phase: When a JSP page is requested for the first time, the web
container translates the JSP file into a Java Servlet source file.
JSP code (HTML, JSP tags, Java code) is converted into servlet code.
This step occurs only the first time the JSP is requested or when the JSP
file is modified.
Example:
[Link] → index_jsp.java
2. Compilation Phase: The generated servlet source file is compiled into a Java
bytecode class.
The servlet .java file is compiled by the Java compiler.
A .class file is produced.
example:
index_jsp.java → index_jsp.class
3. Class Loading Phase: The web container loads the compiled servlet class
into memory. The class becomes available for execution.
4. Initialization Phase
The container calls the jspInit() method once. Allocate resources. Initialize
database connections. Perform startup tasks.
public void jspInit()
{
// Initialization code
}
5. Request Processing Phase For every client request, the container invokes
the _jspService() method.
public void _jspService(HttpServletRequest request, HttpServletResponse
response)
{
// Request processing code
}
Process user requests.
Generate dynamic content.
Send the response back to the client.
6. Destruction Phase
Before removing the JSP from memory, the container calls the jspDestroy()
method. Release resources. Close database connections. Perform cleanup
operations.
public void jspDestroy()
{
// Cleanup code
}
Key steps involved in how a web server processes a JSP request and
generates a web page.
When a user requests a JSP page through a browser, the web server (or servlet
container) follows several steps to process the request and generate the final
webpage.
1. Client Sends Request
A user enters a JSP URL or clicks a link.
The browser sends an HTTP request to the web server.
2. JSP Page Check
The server checks whether the JSP has already been translated and
compiled.
If it is the first request or the JSP has been modified, the server performs
translation and compilation.
3. JSP Translation
The JSP file is converted into an equivalent Java Servlet source file.
4. Servlet Compilation
The generated servlet source code is compiled into a Java class file.
5. Class Loading and Initialization
The servlet class is loaded into memory.
An instance of the servlet is created.
The jspInit() method is called once to initialize resources.
6. Request Processing
For every request, the container invokes the _jspService() method.
Business logic is executed.
Data may be fetched from databases or other resources.
Dynamic content is generated.
7. HTML Response Generation
The servlet combines static HTML and dynamic data.
The output is converted into an HTML page.
8. Response Sent to Browser
The generated HTML is sent back to the client's browser as an HTTP
response.
9. Browser Displays the Web Page
The browser receives the HTML.
It renders the page and displays it to the user.
JSP Tag:
1. Page Directive: Used to define page-level settings for a JSP page.
Syntax: <%@ page attribute="value" %>
Ex: <%@ page language="java" contentType="text/html" %>
Common attributes are:
Attribute Purpose
Language Specifies scripting language
contentType MIME type of response
Import Imports Java packages
Session Enables/disables session
errorPage Defines error page
2. Include directive: Used to include another file during JSP translation time.
Syntax: <%@ include file="[Link]" %>
Features:
Static inclusion
Included file content becomes part of JSP page
Useful for headers, footers, menus
3. Taglib Directive: Used to declare a custom tag library or JSTL library.
Syntax: <%@ taglib uri="URI" prefix="prefix" %>
Ex: <%@ taglib uri="[Link] prefix="c" %>
4. jsp:useBean: Used to create or locate a JavaBean object.
Syntax: <jsp:useBean id="beanName" class="[Link]"
scope="scope"/>
Ex: <jsp:useBean id="std" class="[Link]" scope="session"/>
5. jsp:setProperty: Used to set values to bean properties.
Syntax:
<jsp:setProperty name="beanName" property="propertyName" value="value"/>
Ex: <jsp:setProperty name="user" property="name" value="John"/>
*******************************************