Enterprise Programming
(303105309)
CHAPTER-2
Servlets
Introduction to Servlets
● Servlets provide a component-based, platform-independent method for building Webbased
applications, without the performance limitations of CGI programs. Servlets have access to the
entire family of Java APIs, including the JDBC API to access enterprise databases. This
tutorial will teach you how to use Java Servlets to develop your web based applications in
simple and easy steps.
● Using Servlets, you can collect input from users through web page forms, present records
from a database or another source, and create web pages dynamically.
● Java Servlets often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.
Java Servlets Architecture
● Java servlets container play a very important role. It is responsible for handling important
tasks like load balancing, session management and resource allocation, it makes sure
that all the requests are process efficiently under high traffic. The container distribute
requests across multiple instances, which helps improve the system performance.
● Servlet Architecture can be depicted from the image itself as provided below as follows:
Java Servlets Architecture
Execution of Java Servlet
Execution of Servlets basically involves Six basic steps:
● The Clients send the request to the Web Server.
● The Web Server receives the request.
● The Web Server passes the request to the corresponding servlet.
● The Servlet processes the request and generates the response in the form of output.
● The Servlet sends the response back to the webserver.
● The Web Server sends the response back to the client and the client browser displays it
on the screen.
Life Cycle of a Servlet
Life Cycle of a Servlet
Servlet life cycle can be defined as the stages through which the servlet passes from its creation to its
destruction.
The servlet life cycle consists of these stages:
● Servlet is created
● Servlet is initialized
● Servlet is ready to service
● Servlet is servicing
● Servlet is not ready to service
● Servlet is destroyed
Life Cycle of 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.
The Servlet container can load the Servlet at one of the following times:
● During the initialization of the web application (if the Servlet is configured with a zero or positive
integer value in the deployment descriptor).
● When the Servlet is first requested by a client (if lazy loading is enabled).
Life Cycle of a Servlet
2. Initializing a Servlet
● After the Servlet is instantiated, the Servlet container initializes it by calling the
init(ServletConfig config) method. This method is called only once during the Servlet's life
cycle.
Life Cycle of a Servlet
3. Handling request
Once the Servlet is initialized, it is ready to handle client requests. The Servlet container performs the
following steps for each request:
● Create Request and Response Objects
○ The container creates ServletRequest and ServletResponse objects.
○ For HTTP requests, it creates HttpServletRequest and HttpServletResponse objects.
● Invoke the service() Method
○ The container calls the service(ServletRequest req, ServletResponse res) method.
○ The service() method determines the type of HTTP request (GET, POST, PUT, DELETE,
etc.) and delegates the request to the appropriate method (doGet(), doPost(), etc).
Life Cycle of a Servlet
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
Servlets - Environment Setup
Setting up Java Development Kit
You can download SDK from Oracle's Java site − Java SE Downloads.
Once you download your Java implementation, follow the given instructions to install and configure
the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that
contains java and javac, typically java_install_dir/bin and java_install_dir respectively.
If you are running Windows and installed the SDK in C:\jdk1.8.0_65, you would put the following line
in your C:\autoexec.bat file.
Servlets - Environment Setup
Setting up Web Server − Tomcat
Apache Tomcat is a free, open-source web server that supports Java Servlets and JSP. It can run
as a standalone server or integrate with Apache HTTP Server.
To set it up:
● Download Tomcat from https://tomcat.apache.org
● Extract it and set the CATALINA_HOME environment variable
● Start Tomcat using startup.bat (Windows) or startup.sh (Linux/Unix)
Once started, access it at http://localhost:8080/
Creating Servlet Example in Eclipse
Step 1: Create a Dynamic Web Project
Step 2: servlet-api.jar file
As we are working with servlets, we need to have the servlet-api.jar file in our project. This jar is a
library that contains all the interfaces and classes of the Servlet API, so we can use its functionality to
develop our web application.
● In this example, we are using the Apache Tomcat server to run the project.
● Tomcat container is an open-source Java servlet container that implements several core Java
enterprise functionalities like the Java Servlet, JSP, etc., so it provides this servlet-api.jar file by
default.
● You can check the jar file in the below path if you are using the Tomcat server only.
Creating Servlet Example in Eclipse
s we can see, under Apache Tomcat, there is a
servlet-api.jar file by default.
For Different servers: In case, if you are using a
different server and the servlet-api.jar file is not there,
you can download it from Maven Repository. Add the
downloaded jar file as an external jar to your project
like below:
Creating Servlet Example in Eclipse
Go to the project name and right-click on it. Go to
Build Path -> Configure Build Path
Creating Servlet Example in Eclipse
● In this window, it will show all the libraries that
are associated with the project, and also you can
add any required jar files to your project.
● Go to the Libraries tab and click on Add
External JARs.
● Select the servlet-api.jar file from the location
you downloaded and add.
Servlet API
Servlets are the Java programs that run on the Java-enabled web server or application
server. They are used to handle the request obtained from the webserver, process the
request, produce the response, then send a response back to the webserver. In Java, to
create web applications we use Servlets. To create Java Servlets, we need to use Servlet
API which contains all the necessary interfaces and classes. Servlet API has 2 packages
namely,
● javax.servlet
● javax.servlet.http
javax.servlet
● This package provides the number of interfaces and classes to support Generic servlet which is
protocol independent.
● These interfaces and classes describe and define the contracts between a servlet class and the
runtime environment provided by a servlet container.
Servlet API
Servlets are the Java programs that run on the Java-enabled web server or application
server. They are used to handle the request obtained from the webserver, process the
request, produce the response, then send a response back to the webserver. In Java, to
create web applications we use Servlets. To create Java Servlets, we need to use Servlet
API which contains all the necessary interfaces and classes. Servlet API has 2 packages
namely,
● javax.servlet
● javax.servlet.http
javax.servlet
● This package provides the number of interfaces and classes to support Generic servlet which is
protocol independent.
● These interfaces and classes describe and define the contracts between a servlet class and the
runtime environment provided by a servlet container.
Servlet API
GenericServlet To define a generic and protocol-independent servlet.
ServletContextAttributeEv To generate notifications about changes to the attributes of the servlet context of a
ent web application.
ServletContextEvent To generate notifications about changes to the servlet context of a web application.
ServletInputStream This class provides an input stream to read binary data from a client request.
ServletOutputStream This class provides an output stream for sending binary data to the client.
ServletRequestAttributeE To generate notifications about changes to the attributes of the servlet request in an
vent application.
ServletRequestEvent To indicate lifecycle events for a ServletRequest.
ServletRequestWrapper This class provides the implementation of the ServletRequest interface that can be
subclassed by developers to adapt the request to a Servlet.
ServletResponseWrapper This class provides the implementation of the ServletResponse interface that can
be subclassed by developers to adapt the response from a Servlet.
Servlet API
Filter To perform filtering tasks on either the request to a resource, or on the response from
a resource, or both.
FilterChain To provide a view into the invocation chain of a filtered request for a resource to the
developer by the servlet container.
FilterConfig To pass information to a filter during initialization used by a servlet container.
RequestDispatcher It defines an object to dispatch the request and response to any other resource,
means it receives requests from the client and sends them to a servlet/HTML file/JSP
file on the server.
Servlet This is the main interface that defines the methods in which all the servlets must
implement. To implement this interface, write a generic servlet that extends
javax.servlet.GenericServlet or an HTTP servlet that extends
javax.servlet.http.HttpServlet.
ServletConfig It defines an object created by a servlet container at the time of servlet instantiation
and to pass information to the servlet during initialization.
Servlet API
ServletContext It defines a set of methods that a servlet uses to communicate with its
servlet container. The information related to the web application available
in web.xml file is stored in ServletContext object created by container.
ServletContextAttributeListener The classes that implement this interface receive notifications of changes
to the attribute list on the servlet context of a web application.
ServletContextListener The classes that implement this interface receive notifications about
changes to the servlet context of the web application they are part of.
ServletRequest It defines an object that is created by servlet container to pass client
request information to a servlet.
ServletRequestAttributeListener To generate the notifications of request attribute changes while the
request is within the scope of the web application in which the listener is
registered.
ServletRequestListener To generate the notifications of requests coming in and out of scope in a
web component.
Servlet API
Exception Name Description
ServletException A general exception thrown by a servlet when it encounters difficulty.
UnavailableException Thrown by a servlet or filter to indicate that it is permanently or
temporarily unavailable.
Servlet Collaboration In Java Using RequestDispatcher and HttpServletResponse
What is Servlet Collaboration?
The exchange of information among servlets of a particular Java web application is known as Servlet
Collaboration. This enables passing/sharing information from one servlet to the other through
method invocations.
What are the principle ways provided by Java to achieve Servlet Collaboration?
The servlet api provides two interfaces namely:
1. javax.servlet.RequestDispatcher
2. javax.servlet.http.HttpServletResponse
Servlet Collaboration In Java Using RequestDispatcher and HttpServletResponse
The RequestDispatcher interface provides the option of dispatching the client's request to another
web resource, which could be an HTML page, another servlet, JSP etc. It provides the following two
methods:
● public void forward(ServletRequest request, ServletResponse response)throws
ServletException, java.io.IOException:
The forward() method is used to transfer the client request to another resource (HTML file,
servlet, jsp etc). When this method is called, the control is transferred to the next resource
called. On the other hand, the include() method is used to include the content of the calling file
into the called file. After calling this method, the control remains with the calling resource, but
the processed output is included into the called resource.
Servlet Collaboration In Java Using RequestDispatcher and HttpServletResponse
Servlet Collaboration In Java Using RequestDispatcher and HttpServletResponse
Servlet - Session Tracking
Servlets are the Java programs that run on the Java-enabled web server or application server. They
are used to handle the request obtained from the webserver, process the request, produce the
response, then send a response back to the webserver
HTTP is a "stateless" protocol, which means that each time a client requests a Web page, the client
establishes a new connection with the Web server, and the server does not retain track of prior
requests.
● The conversation of a user over a period of time is referred to as a session. In general, it refers
to a certain period of time.
● The recording of the object in session is known as tracking
● Session tracking is the process of remembering and documenting customer conversations
over time. Session management is another name for it.
● The term "stateful web application" refers to a web application that is capable of remembering
and recording client conversations over time.
Servlet - Session Tracking
Why is Session Tracking Required?
● Because the HTTP protocol is stateless, we require Session Tracking to make the client-server
relationship stateful.
● Session tracking is important for tracking conversions in online shopping, mailing applications,
and E-Commerce applications.
● The HTTP protocol is stateless, which implies that each request is treated as a new one. As you
can see in the image below.
Servlet - Session Tracking
Deleting Session Data
We have numerous alternatives once you've finished processing a user's session data.
1. Remove a specific attribute You can delete the value associated with a specific key by calling
the public void removeAttribute(String name) function.
2. Delete your whole session. To delete an entire session, use the public void invalidate() function.
3. Setting Session Timeout You may set the timeout for a session separately by calling the public
void setMaxInactiveInterval(int interval) function.
4. Log the user out On servers that support servlets 2.4, you may use the logout method to log the
client out of the Web server and invalidate all of the users' sessions.
5. web.xml Configuration If you're using Tomcat, you may set the session timeout in the web.xml
file, in addition to the ways listed above.
Servlet - Session Tracking
<session-config>
<session-timeout>20</session-timeout>
</session-config>
The timeout is specified in minutes and overrides Tomcat's default timeout of 30 minutes.
In a servlet, the getMaxInactiveInterval() function delivers the session's timeout period in seconds.
GetMaxInactiveInterval() returns 900 if your session is set to 20 minutes in web.xml.
Servlet - Session Tracking
Session Tracking employs Four Different techniques
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
A. Cookies
Cookies are little pieces of data delivered by the web server in the response header and kept by the
browser. Each web client can be assigned a unique session ID by a web server. Cookies are used to
keep the session going. Cookies can be turned off by the client.
B. Hidden Form Field
The information is inserted into the web pages via the hidden form field, which is then transferred to
the server. These fields are hidden from the user's view.
<input type = hidden' name = 'session' value = '12345' >
Servlet - Session Tracking
C. URL Rewriting
With each request and return, append some more data via URL as request parameters. URL rewriting
is a better technique to keep session management and browser operations in sync.
D. HttpSession
A user session is represented by the HttpSession object. A session is established between an HTTP
client and an HTTP server using the HttpSession interface. A user session is a collection of data
about a user that spans many HTTP requests.
Illustration:
HttpSession session = request.getSession( );
Session.setAttribute("username", "password");
Servlet - Session Tracking
public Object This method returns the object in this session bound with the supplied name, or
getAttribute(String name) null if no object is bound with the name.
public Enumeration This function returns an Enumeration of String objects with the names of all the
getAttributeNames() items associated with this session.
public long getCreationTime() This method returns the milliseconds since midnight January 1, 1970 GMT,
when this session was created.
public String getId() This function returns a string that contains the session's unique identification.
public long This function returns the session's most recent accessible time in milliseconds
getLastAccessedTime() since midnight on January 1, 1970 GMT.
Servlet - Session Tracking
public int getMaxInactiveInterval() The maximum time interval (seconds) for which the servlet container will
keep the session open between client requests is returned by this function.
public void invalidate() This function unbinds any objects connected to this session and invalidates
it.
public boolean isNew() If the client is unaware of the session or decides not to join it, this function
returns true.
public void removeAttribute(String The object bound with the supplied name is removed from this session
name) using this method.
public void setAttribute(String This function uses the supplied name to tie an object to this session.
name, Object value)
public void This function defines the interval between client requests before the servlet
setMaxInactiveInterval(int container invalidates this session in seconds.
interval)
www.paruluniversity.ac.in