0% found this document useful (0 votes)
41 views11 pages

Servlet

The document discusses Java servlets. Servlets are Java programs that run on a web server and handle requests from clients. They process requests, generate responses, and send responses back to the web server. Servlets work on the server-side and can handle complex requests. The servlet lifecycle involves loading, initializing, handling requests, and destroying servlets. The servlet container manages the lifecycle and provides services like network access and session management.

Uploaded by

r40000227
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)
41 views11 pages

Servlet

The document discusses Java servlets. Servlets are Java programs that run on a web server and handle requests from clients. They process requests, generate responses, and send responses back to the web server. Servlets work on the server-side and can handle complex requests. The servlet lifecycle involves loading, initializing, handling requests, and destroying servlets. The servlet container manages the lifecycle and provides services like network access and session management.

Uploaded by

r40000227
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
You are on page 1/ 11

ITPC-305 WEB DESIGN TECHNOLOGIES

Java Servlets
Today we all are aware of the need of creating dynamic web pages i.e the ones which
have the capability to change the site contents according to the time or are able to
generate the contents according to the request received by the client. If you like coding
in Java, then you will be happy to know that using Java there also exists a way to
generate dynamic web pages and that way is Java Servlet. But before we move forward
with our topic let’s first understand the need for server-side extensions.

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.

Properties of Servlets are as follows:

• Servlets work on the server-side.


• Servlets are capable of handling complex requests obtained from the webserver.
Servlet Architecture is can be depicted from the image itself as provided below as
follows:

Execution of Servlets basically involves six basic steps:


1. The clients send the request to the webserver.
2. The web server receives the request.
3. The web server passes the request to the corresponding servlet.
ITPC-305 WEB DESIGN TECHNOLOGIES

4. The servlet processes the request and generates the response in the form of
output.
5. The servlet sends the response back to the webserver.
6. The web server sends the response back to the client and the client browser
displays it on the screen.

Now let us do discuss eccentric point that why do we need For Server-Side extensions?

The server-side extensions are nothing but the technologies that are used to create
dynamic Web pages. Actually, to provide the facility of dynamic Web pages, Web
pages need a container or Web server. To meet this requirement, independent Web
server providers offer some proprietary solutions in the form of APIs(Application
Programming Interface). These APIs allow us to build programs that can run with a
Web server. In this case, Java Servlet is also one of the component APIs of Java
Platform Enterprise Edition which sets standards for creating dynamic Web
applications in Java.
Before learning about something, it’s important to know the need for that something,
it’s not like that this is the only technology available for creating dynamic Web pages.
The Servlet technology is similar to other Web server extensions such as Common
Gateway Interface (CGI) scripts and Hypertext Preprocessor (PHP). However, Java
Servlets are more acceptable since they solve the limitations of CGI such as low
performance and low degree scalability.

Advantages of a Java Servlet


• Servlet is faster than CGI as it doesn’t involve the creation of a new process for
every new request received.
• Servlets, as written in Java, are platform-independent.
• Removes the overhead of creating a new process for each request as Servlet
doesn’t run in a separate process. There is only a single instance that handles all
requests concurrently. This also saves the memory and allows a Servlet to easily
manage the client state.
ITPC-305 WEB DESIGN TECHNOLOGIES

• It is a server-side component, so Servlet inherits the security provided by the


Web server.
• The API designed for Java Servlet automatically acquires the advantages of the
Java platforms such as platform-independent and portability. In addition, it
obviously can use the wide range of APIs created on Java platforms such
as JDBC to access the database.
• Many Web servers that are suitable for personal use or low-traffic websites are
offered for free or at extremely cheap costs eg. Java servlet. However, the
majority of commercial-grade Web servers are rather expensive, with the notable
exception of Apache, which is free.

The Servlet Container


Servlet container, also known as Servlet engine is an integrated set of objects that
provide a run time environment for Java Servlet components.
In simple words, it is a system that manages Java Servlet components on top of the Web
server to handle the Web client requests.

Services provided by the Servlet container :


• Network Services: Loads a Servlet class. The loading may be from a local file
system, a remote file system or other network services. The Servlet container
provides the network services over which the request and response are sent.
• Decode and Encode MIME-based messages: Provides the service of
decoding and encoding MIME-based messages.
• Manage Servlet container: Manages the lifecycle of a Servlet.
• Resource management Manages the static and dynamic resources, such as
HTML files, Servlets, and JSP pages.
• Security Service: Handles authorization and authentication of resource access.
• Session Management: Maintains a session by appending a session ID to the
URL path.
ITPC-305 WEB DESIGN TECHNOLOGIES

Life Cycle of a Servlet


The entire life cycle of a Servlet is managed by the Servlet container which uses
the javax.servlet.Servlet interface to understand the Servlet object and manage it. So,
before creating a Servlet object, let’s first understand the life cycle of the Servlet object
which is actually understanding how the Servlet container manages the Servlet object.

Stages of the Servlet Life Cycle:


The Servlet life cycle mainly goes through four stages,
• Loading a Servlet.
• Initializing the Servlet.
• Request handling.
• Destroying the Servlet.

Let’s look at each of these stages in details:

1. Loading a Servlet: The first stage of the Servlet lifecycle involves loading and
initializing the Servlet by the Servlet container. The Web container or Servlet
Container can load the Servlet at either of the following two stages :
• Initializing the context, on configuring the Servlet with a zero or positive integer
value.
• If the Servlet is not preceding stage, it may delay the loading process until the Web
container determines that this Servlet is needed to service a request.

The Servlet container performs two operations in this stage :

• Loading : Loads the Servlet class.


• Instantiation : Creates an instance of the Servlet. To create a new instance of the
Servlet, the container uses the no-argument constructor.
ITPC-305 WEB DESIGN TECHNOLOGIES

2. Initializing a Servlet: After the Servlet is instantiated successfully, the Servlet


container initializes the instantiated Servlet object. The container initializes the
Servlet object by invoking the Servlet.init(ServletConfig) method which accepts
ServletConfig object reference as parameter.
The Servlet container invokes the Servlet.init(ServletConfig) method only once,
immediately after the Servlet.init(ServletConfig) object is instantiated
successfully. This method is used to initialize the resources, such as JDBC
datasource.
Now, if the Servlet fails to initialize, then it informs the Servlet container by
throwing the ServletException or UnavailableException.

3. Handling request: After initialization, the Servlet instance is ready to serve the
client requests. The Servlet container performs the following operations when the
Servlet instance is located to service a request :
ITPC-305 WEB DESIGN TECHNOLOGIES

• It creates the ServletRequest and ServletResponse objects. In this case, if this


is a HTTP request, then the Web container
creates HttpServletRequest and HttpServletResponse objects which are
subtypes of the ServletRequest and ServletResponse objects respectively.
• After creating the request and response objects it invokes the
Servlet.service(ServletRequest, ServletResponse) method by passing the
request and response objects. The service() method while processing the
request may throw
the ServletException or UnavailableException or IOException.

4. Destroying a Servlet: When a Servlet container decides to destroy the Servlet,


it performs the following operations,
• It allows all the threads currently running in the service method of the Servlet
instance to complete their jobs and get released.
• After currently running threads have completed their jobs, the Servlet
container calls the destroy() method on the Servlet instance.
After the destroy() method is executed, the Servlet container releases all the
references of this Servlet instance so that it becomes eligible for garbage
collection.

Servlet Life Cycle Methods


There are three life cycle methods of a Servlet :

• init()
• service()
• destroy()
ITPC-305 WEB DESIGN TECHNOLOGIES

Let’s look at each of these methods in details:

init() method: The Servlet.init() method is called by the Servlet container to indicate
that this Servlet instance is instantiated successfully and is about to put into service.
//init() method

public class MyServlet implements Servlet{

public void init(ServletConfig config) throws ServletException {

//initialization code

//rest of code

service() method: The service() method of the Servlet is invoked to inform the Servlet
about the client requests.
This method uses ServletRequest object to collect the data requested by the client.
ITPC-305 WEB DESIGN TECHNOLOGIES

This method uses ServletResponse object to generate the output content.


// service() method

public class MyServlet implements Servlet{

public void service(ServletRequest res, ServletResponse res)

throws ServletException, IOException {

// request handling code

// rest of code

destroy() method: The destroy() method runs only once during the lifetime of a
Servlet and signals the end of the Servlet instance.
//destroy() method

public void destroy()

As soon as the destroy() method is activated, the Servlet container releases the Servlet
instance.

Servlet Life Cycle:


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 these stages:
• Servlet is borned
• Servlet is initialized
• Servlet is ready to service
• Servlet is servicing
• Servlet is not ready to service
• Servlet is destroyed
ITPC-305 WEB DESIGN TECHNOLOGIES

Life cycle methods:


Life cycle methods are those methods which are used to control the life cycle of the
servlet. These methods are called in specific order during the servlets’s entire life cycle.
The class Servlet provides the methods to control and supervise the life cycle of
servlet. There are three life cycle methods in the Servlet interface. There are as follows:
init() method :
1. A servlet’s life begins here .
2. This method is called only once to load the servlet. Since it is called only once in
it’s lifetime, therefore “connected architecture” code is written inside it because we
only want once to get connected with the database.

Q. Why can’t we write connected architecture code inside the constructor, since
constructor also run only once in it’s entire life?
Ans. Suppose if the connection doesn’t get established, then we can throw an exception
from init() and the rest of the steps stop executing. But in the constructor we can’t use,
throw in it’s prototype otherwise it is an error.
1. This method receives only one parameter, i.e ServletConfig object.
2. This method has the possibility to throw the ServletException.
3. Once the servlet is initialized, it is ready to handle the client request.
4. The prototype for the init() method:
public void init(ServletConfig con)throws ServletException{ }

where con is ServletConfig object


NOTE:- In programs of servlet, we use non parameterized version of init().

// Java program to show servlet example


// Importing required Java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
ITPC-305 WEB DESIGN TECHNOLOGIES

// Extend HttpServlet class


public class AdvanceJavaConcepts extends HttpServlet
{
private String output;

// Initializing servlet
public void init() throws ServletException
{
output = "Advance Java Concepts";
}

// Requesting and printing the output


public void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException
{
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println(output);
}

public void destroy()


{
System.out.println("Over");
}
}

JSDK
JSDK is the Java Servlet Developers Kit. This is an add on to the regular JDK (Java Developers
Kit). The JSDK has the additional files needed in order to compile Java servlets. The latest
version of the JSDK is version 2.0. Included in the JSDK is a Java Servlet Runner program.
The Servlet Runner is a program that runs on your workstation, and allows you to test servlets
you have written without running a web server. Other files included are the several Java Servlet
ITPC-305 WEB DESIGN TECHNOLOGIES

examples. Included are the .java and .class files for testing purposes and to help you understand
how the Java code is implemented. Another important file that is included is the jsdk.jar file.
This file includes the class information necessary to compile the servlets.

Installing JSDK
Let me preface the JSDK installation procedures by saying that the JSDK is an add on to the
JDK. If you are trying to compile servlets using JSDK, you will be missing software. The JDK
includes the javac.exe program and other java library and class files that are necessary to
compile java code. Before you start to install the JSDK, install the JDK, then begin JSDK
install.

Installing the JSDK is a very simple procedure. When you run the .exe that you download from
the http://java.sun.com web site, it will create some temporary web files on your hard drive. It
will then launch the installation script. You will be asked to specify the directory you wish to
have the files copied to. As in the JDK, the recommended directory includes a 'period' in the
directory name (ex. C:\JSDK.20). Change this to C:\JSDK20 instead to make it easier when
searching for the directory. After the software is installed, you will have a new subdirectory.
In order to use both the JDK and JSDK together, the java compiler (javac.exe) needs to know
where the class files are located. I found the easiest way to make this work, is to first put the
bin directory for the JDK in the path. This will make it easy to find the javac.exe program when
compiling code. Second, add the jsdk.jar file to the classpath. This can be done by adding a
SET statement to the autoexec.bat file on your workstation (for Windows 95). The SET
statement should read SET CLASSPATH = drive:JSDK install path\lib\jsdk.jar (ex. SET
CLASSPATH = C:\jsdk20\lib\jsdk.jar). Once this is done, you will have no problem compiling
your java servlets.

You might also like