You are on page 1of 23

SERVLETS INTRODUCTION

Servlets are the objects (Java Objects) whose responsibility is to handle the client
requests. Servlets are also known as container managed objects because all the
servlets life cycles are managed by a container called as Servlet Containers.
Servlets are the specification provided by Oracle(Sun Micro Systems) in the form of
interfaces and all server vendors implements the Servlet interface. Before the servlets
are invented there was another specification called as CGI (Common Gateway
Interface) which were used to create a web application. CGI has several shortcomings
and to overcome that Servlet was designed.
To make servlet picture clear, let’s look at the below figure.

 Web Browser is a client which sends request to servlets. Corresponding Servlet invokes
the business logic.
 Servlets responds back with the response to the client.
 Servlet container contains multiple servlets .It is the responsibility of Servlet Container
to delegate the request to a particular Servlet.

2.2 SERVLET CONTAINER


Servlet container (also known as Servlet engine ) and is a part of any web server or
Application Server and runs within a web or application server and interacts with
Servlets. Some of the free or open source web servers are tomcat, Jetty, Glassfish etc.
There are specifications for a container , that needs to be fulfilled to become a servlet
container like “it must respond to all HTTP requests”.
As we discussed earlier, container manages the life cycle of each and every servlet
starting instantiation to destroy. We will discuss the life cycle of servlet in detail in
upcoming chapters.
All web applications are deployed under web server and a servlet container and all
servlets are a part of specific web application.

2.3 WHERE DOES SERVLET RESIDE ACTUALLY


(COMPLETE PICTURE) -
A web application is an application accessible over web. A web application is composed
of web components like Servlet, JSP, Filter etc. and other components such as HTML.
The web components typically execute in Web Server and respond to HTTP request.
Let’s look at the below figure and its description. Below figure is the complete picture of
all components in relation.

Web Server & Servlet Container

2.4 ILLUSTRATION /FLOW


 There are two clients (Client1 and Client2).
 One Web Server with Servlet Container
 There are two web application with name “Web Application 1” and “Web Application 2”
 Web application 1 consists of two servlets (Servlet 1 and Servlet 2)
 Web application 2 consists of two servlets (Servlet 3 and Servlet 4)

Any client (client 1) opens up a web browser and sends the request to web server by
hitting the URL of web application like “http//localhost:8080/WebApplicaion1/Servlet1”.
This URL says that server location is localhost (which means client and server are
running on same machine) and web server is running in port 8080.
Web server scans the request and verifies that request is for Servlet1 of
WebApplcation1. So servlet container instantiates the servlet1 if not already
instantiated, creates a new thread and delegates the client request to the servlet to
handle this request in that thread.
Now servlet can have any custom logic or it may invoke another java classes to execute
some business logic. Once the processing is done , servlet sends back the HTTP
response to the client.
Similarly another client can invoke another web application or the same web application
which is invoked by client 1.

2.5 ADVANTAGES OF SERVLTS OVER CGI


a. Servlets are platform independent. There are two reason for Servlets portability.

 As we all know Java is platform independent language and Servlets are written in Java
which means servlets can run on any Operation System like Windows, Unix, Mac etc.
 Servlets are just specification and all vendor servers implement the interface so custom
code written following specification can be ported easily from one server to another like
Tomcat, JBoss etc.

b. Servlets provides a much better performance as compared to traditional Common


Gateway Interface scripts in terms of both memory and processing time.

As Servlets are web based which means any number of concurrent requests can come
for a particular servlet. Servlet container handles this situation very well which results
much better performance.

 With traditional CGI script , for each new HTTP request a separate process is created.
Creating a process is very expensive operation. In case of servlets, all requests are
handled in a separate thread (not separate process).

 Only one instance of a particular servlet is created and all the requests to that servlet
are executed in a separate thread. This saves a lot of memory at run time as only one
instance is created. This is very important concept so be clear that always one and only
one instance of a particular servlets is created. We will discuss this more in Servlet Life
Cycle.

c. Servlets have an access to all other java classes and functionality like RMI, sockets.

d. As Servlet’s life cycle is managed by Servlet container, they are more robust as
developers need not to worry about most complex areas like garbage collections ,
memory management, memory leaks and security.

2.6 WHAT CAN A SERVLET DO?


 Servlets can be used to execute complex business logic, to interact with third party or
any legacy systems or can make a database calls.
 Servlet can even create a web page by writing complete output to the response.
 Servlet can grab the user inputs and can process the request or user inputs.

2.7 NUMBER OF SERVLET INSTANCES -


Typically one and only one Servlet instance is created by a servlet container and for
each HTTP request, container spawns a separate thread which handles the request.
This means multiple requests can be processed simultaneously in a separate thread
and hence provides memory and performance gain.

2.8 CAN YOU THINK OF ANY PROBLEM WITH THIS


MODEL?
If there is only one instance created and all requests are served in a separate thread
which means all threads will share the member variables (instance variable). If servlets
just performs read only operations on instance variable than we are good but if servlet
writes or updates the value of an instance variable then we may end up with
unpredictable behaviour.
To address this problem, there are options like

a. Access the instance variable in synchronized blocks.


b. Servlet specification provides a concept / feature of Single Thread Model. Single Thread
Model is a marker interface and Implementing single thread model makes sure that only
one thread executes at a time. This is a serious disadvantage as web multiple requests
need to wait till one request completes.

Single Thread Model is deprecated now as its functionality can be achieved using
synchronized blocks.

OVERVIEW OF SERVLETS API


In earlier chapters we discussed that Servlets are the objects (Java Objects ).Does this
mean that any java class can act as Servlets? Answer is No.
For any class to become a Servlet it has to follow the specifications defined for servlets
which means class has to implement certain interfaces directly OR indirectly.

3.2 SERVLET PACKAGES


Sun defines two java packages that contain all the interfaces and classes required by
Servlet API. These packages are -

a. javax.servlet – This package contains generic classes and interfaces (protocol less).
b. javax.servlet.http- As package name suggest , this package contains all classes and interfaces
related to HTTP protocol.

The main interface in the Servlet API is the Servlet interface. All servlets implement this
interface, either directly or indirectly.
By indirectly we mean, instead of implementing Servlet interface, custom servlets can
extend one of the two available abstract classes which are Generic Servlet or Http
Servlet.
The inheritance hierarchy looks as follows.

Servlet is displayed in a different colour because it is an interface while Generic Servlet


and Http Servlet are abstract classes.
Generic Servlet implements Servlet interface whereas Http Servlet extends Generic
Servlet.

3.3 SERVLET API


3.3.1 javax.servlet.Servlet
This is the base interface of Java Servlet API and it defines all the lifecycle methods of
the servlet.
Since this is an interface, any class implementing Servlet interface has to implement all
its methods. Below is the list of methods declared in Servlet interface.

1. public abstract void init(ServletConfig) throws ServletException – this is the lifecycle


method of servlet and gets invoked only once in the entire lifecycle of a particular servlet. This
method is used to initialize the servlet and useful to have onetime processing code or one time
initialization code like Database initialization etc.

2. public abstract void service(ServletRequest , ServletResponse ) throws


ServletException, IOException – This is the main method that performs business logic and
responsible for processing client request. When a new request for a servlet comes, servlet
container spawns a new thread. Then the thread executes the service() method and executes
the business logic or the intended task of the servlet.

3. public abstract void destroy() – The destroy() method is called only once at the end of the life
cycle of a servlet and thus gives an opportunity to the servlet to perform some cleanup activities
like database connection close , closing of any files opened etc. We can relate it to finalize
method that gets executed before GC of an object.

4. public abstract ServletConfig getServletConfig() – This method returns a servlet config


object, which contains any initialization parameters and startup configuration for this servlet.

5. public abstract String getServletInfo() – This method returns string containing information
about the servlet, such as its author etc.

3.3.2 javax.servlet.ServletConfig
This is an interface and used to get the servlet initialization and configuration
parameters to the servlet. While defining servlet in web.xml, we can provide init
parameters and with the help of this interface we can get those init parameters.
“Servlet Config object is specific to Servlet which means each servlet will have its own
servlet config object”
To get the Servlet Config object in a servlet, we just need to call getServletConfig()
method.
The important methods of ServletConfig interface are:

1. public abstract ServletContext getServletContext() – This method returns the ServletContext


object for the servlet.

2. public abstract Enumeration getInitParameterNames() – This method returns the


Enumeration of name of init parameters defined for the servlet.

3. public abstract String getInitParameter(String ) – This method returns the value of given init
parameter. If parameter is not present with the name, it returns null.
“Key thing to note here is – there is no setInitParameter() method available which
means we cannot set or update init parameters from servlet code.”

3.3.3 javax.servlet.GenericServlet
This is an abstract class and implements both javax.servlet.Servlet and
javax.servlet.ServletConfig interface. As its name implies this is a Generic servlet and
not tied to any specific protocol.
Since class implements Servlet interface, it provides default implementation of all the
methods available in Servlet and ServletConfig interface.
We can simply extend this class to have all the default functionality available and just
override the methods of our interest
service() method is still abstract in GenericServlet which means any servlet extending
Generic Servlet has to provide implementation of service() method.
“Can you think why Generic Servlet left service method unimplemented? – As
mentioned earlier, this method is the main method where complete logic of your servlet
goes and how can a generic servlet knows which logic to execute. If this method is not
abstract then developers might leave this method unimplemented.”

3.3.4 javax.servlet.http.HttpServlet class


This class is also an abstract class and extends GenericServlet.
As its name suggests, this class provides base for creating HTTP protocol based web
applications.
With Http Servlet, request can be of several types like GET, POST, PUT,DELETE etc.
so Http Servlet provides an implementation of service() method as well. Default
implementation of service method checks the request type and based on type invokes,
doXXX() method where XXX is type of request
There are methods defined to be overridden by subclasses for different HTTP methods
in HttpServlet class.

1. doGet(), for HTTP GET requests


2. doPost(), for HTTP POST requests
3. doPut(), for HTTP PUT requests
4. doDelete(), for HTTP DELETE requests

Since this class provides an implementation of service method, classes extending Http
Servlet class should not override service() method. Instead such classes should
override doXXX() methods.
Details of Other Interfaces like ServletRequest, ServletResponse,HttpServletRequest,
HttpServletRepsonse will be discussed in a next chapter.
3.6 ADVANTAGES OF EXTENDING HttpServlet OVER
IMPLEMENTING SERVLET INTERFACE
 Advantage of extending HttpServlet class over implementing Servlet interface is quite simple
.Custom servlet just needs to implement the required methods and will have default
implementation out of the box.
 One more advantage is, in case Servlet interface gets changed then all the servlets
implementing this interface have to be changed but since HttpServlet or Generic servlet already
implements this interface so all of those changes will be already available to use out of the box
and there will be no impact on our custom code.

3.7 Summary
In almost all cases, servlet is created by extending HttpServlet class and implementing
doGet() and doPost() method as these two are the most common Request types.

INTRODUCTION TO SERVLET REQUEST AND


SERVLET RESPONSE
In earlier chapters we discussed about the Servlets API and in this chapter we will
discuss important methods and the usage of Request, Response and Session Classes.
In some of the servlet API methods like doGet(), doPost() or service() you must have
seen Request and Response arguments.
There are several methods available in Servlet Request /Response and in Session but
we will discuss the most commonly used and important ones here.
The important and most commonly used functionality of ServletRequest are –

 get the parameter from the user (front end)


 store and get the objects in request scope
 read the headers
 get session object

Similarly for ServletResonse is used to-

 Write the response back to user


 Set or update the header values
 Redirect to another url.

Http Session is used to store the attributes which are required in entire user session.
Let’s discuss these classes in details

4.2 SERVLET REQUEST / RESPONSE PACKAGES


Request and Response related classes are packaged in two packages . These
packages are -
a. javax.servlet – This package contains ServletRequest and ServletResponse interfaces
(protocol less).
b. javax.servlet.http- This package contains HttpServletRequest, HttpServletResponse and
HttpSession classes As package name suggest , this package contains all classes and
interfaces related to HTTP protocol.

4.3 ServletRequest METHODS


As mentioned ServletRequest is the interface and below are its most commonly used
methods with usage and description.

 String getParameter(String parameterName)- this method is used to get the value of


request parameter by name. Request parameters are the parameters sent by the user
either as a query parameter or in the html form. Remember its return type is String.

http://localhost:8080?param=hello then we can get the parameter in the servlet like


request.getParameter(“param”) and this call will return “hello”

 · String[] getParameterValues(String parameterName)- this method is similar to


getParameter() with the difference is that it returns an array of String containing all of
the values the given request parameter.

You might be wondering how we can have a multiple parameters with same name- so
think of the scenarios where the check box has been used (user can select multiple
options) OR a multi select dropdown.

 Object getAttribute(String attributeName) – this method is used to get the attribute


stored in a request scope by attribute name. Remember the return type is Object.
 void setAttribute(String attributeName, Object value)- this method is used to store
an attribute in request scope. This method takes two arguments- one is attribute name
and another is value.
 As getAttribute() returns Object which means setAttribute() takes Object as well.
 ServletContext getServletContext() – this method can be used to get the servlet
context. The ServletContext contains information about the web application and is
available in all servlets.

Note: Do not get confused between parameter and attribute.

 Parameters are the ones submitted by user in the form of query param or form elements
where as attributes are the one which can be stored in request to take it later.
 Parameters cannot be set programmatically where as we can set the attributes.
 Parameters are of type String where as attributes are Objects.

4.4 ServletResponse METHODS


Below are the important and most commonly used methods
 PrintWriter getWriter() returns a PrintWriter object that can send the character text to
the client.
 void setContentType(String type) sets the content type of the response being sent to
the client before sending the respond.

ServletRequest and ServletResponse are the argument of service() method of


GenericServlet

4.5 HttpServletRequest
HttpServletRequest is the Http protocol based request and extends ServletRequest
Interface

As HttpServletRequest extends Servlet Request all of its methods (discussed above)


will be available. In addition to that the commonly used additional methods are-

 Cookies getCookies()- this methods returns an array containing all of the Cookie
objects the client sent with this request.
 String getQueryString() this methods returns the query string that is contained in the
request URL.
 String getMethod()- this methods returns the name of the HTTP method with which
this request was made, for example, GET, POST, or PUT. Do you remember we
discussed different Request types in earlier chapter? Based on this method
 HttpSession getSession() this methods returns the current HttpSession associated
with this request

There is an overloaded method also available which takes a Boolean argument. if value
of that argument is passed as true then it will return a current session and if there is no
current session returns a new session. In case value is being passed as false then it
returns null if session does not exist.

 String getHeader(String headerName) – this method is used to get the any of header
value based on given header name.

4.6 HttpServletResponse
HttpServletResponse is the Http protocol based request and extends ServletResponse
Interface

As HttpServletResponse extends Servlet Response all of its methods (discussed


above) will be available. In addition to that the commonly used additional methods are-

 void addCookie(Cookie cookie)- this methods adds the cookie object to the
response.
 void sendRedirect(String url) this method redirects the browser to a specified URL
from your servlet. We will discuss more about this method in later chapters.

4.7 HttpSession
The HttpSession object is representation of a user session. User Session starts when a
user opens a browser and sends the first request to server. Session object is available
in all the request (in entire user session) so attributes stored in Http session in will be
available in any servlet or in a jsp. When session is created, server generates a unique
ID and attach that ID with the session. Server sends back this Id to the client and there
on , browser sends back this ID with every request of that user to server with which
server identifies the user.
How to get a Session Object –
As mentioned above session object can be retrieved using HttpServletRequest (not
ServletRequest) object like –

a. HttpSession session = request.getSession()


b. HttpSession session = request.getSession(Boolean)

Destroy or Invalidate Session –


This is used to kill user session and specifically used when user logs off. To invalidate
the session use -
session.invalidate();
Other important methods

 Object getAttribute(String attributeName) – this method is used to get the attribute


stored in a session scope by attribute name. Remember the return type is Object.
 void setAttribute(String attributeName, Object value)- this method is used to store
an attribute in session scope. This method takes two arguments- one is attribute name
and another is value.
 void removeAttribute(String attributeName)- this method is used to remove
the attribute from session.

Note –
You might be thinking that storing attribute in session is more convenient as compared
to request. But be sure while you store attribute in session because session variables
are available everywhere which means it may gets updated or removed from other part
of code which can create undesired behaviour. With request, all stored variables
automatically gets vanished after request is completed.
If you are sure that session variable is no longer will be used , remove it.
Browser session and server sessions are different. Browser session is client session
which starts when you opens browser and destroy on closing of browser where as
server session are maintained at server end.

SERVLET REQUEST / RESPONSE EXAMPLES


a. How to get the query parameter “param” in servlet?

String value = request.getParameter(“param”);

b. How to store a attribute in request?

request.setAttribute(“attributeName”,”atributeValue”);

c. How to get the stored request variable in example #b ?

Object value =request.getAttribute(“attributeName”);


String attribValue=value.toString();
Remember getAttribute() always returns Object.

d. How to send HTML back to the browser?

PrintWriter writer = response.getWriter();


writer.write("<html><body>Hello World</body></html>");

e. How to redirect user to “google.com”?

response.sendRedirect("http://www.google.com");

f. How to store a attribute in session?


HttpSession session = request.getSession();
session.setAttribute(“attributeName”,”atributeValue”);

g. How to get the stored request variable in example #f ?

HttpSession session = request.getSession();


Object value =session.getAttribute(“attributeName”);
String attribValue=value.toString();

h. Write a HelloWorldServlet with both approaches (extends Generic Servlet and Http
Servlet) which prints Hello World Message on browser.

a. With Generic Servlet

?
1
2 import java.io.IOException;
3 import java.io.PrintWriter;
4 import javax.servlet.GenericServlet;
5 import javax.servlet.ServletException;
6 import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
7 public class HelloWorldServlet extends GenericServlet
8 {
9 @Override
10 public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
11 {
12 response.setContentType("text/html");
13 PrintWriter writer = response.getWriter();
14 String helloWorldMessage="<html><body><H1>Hello World Servlet</H1></body></html>
15 writer.println(helloWorldMessage);
}
16 }
17
18
Explanation

 this servlet is written with GenericServlet approach, this servlet extends GenericServlet
and overrides service() method and it takes ServletRequest and ServletResponse.

 to write a response on the browser, we need a PrintWriter object which we can get from
response so once Print Writer object is obtained, simply write the message.

 This example clearly shows that we can write Html code in Print writer object.

b. With HttpServlet
?
1
2 import java.io.IOException;
3 import java.io.PrintWriter;
4 import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
5 import javax.servlet.http.HttpServletRequest;
6 import javax.servlet.http.HttpServletResponse;
7 public class HelloWorldServlet extends HttpServlet {
8 @Override
9 public void doGet(HttpServletRequest request, HttpServletResponse response)throws Servlet
10 {
response.setContentType("text/html");
11 PrintWriter writer = response.getWriter();
12 String helloWorldMessage="<html><body><H1>Hello World Servlet</H1></body></html>
13 writer.println(helloWorldMessage);
14 }
15 }
16
Explanation

 since this servlet is written with HttpServlet approach, this servlet extends HttpServlet
and overrides doGet() method and it takes HttpServletRequest and
HttpServletResponse.
 to write a response on the browser, we need a PrintWriter object which we can get from
response so once Print Writer object is obtained, simply write the message.

5.1 INTRODUCTION TO SERVLETS LIFE CYCLE


In this chapter we will discuss the life cycle of a servlet. Before moving to servlet life
cycle let me recap the very important points we discussed in earlier chapters.

a. “By default one and only one instance of a servlet gets created in a JVM”. I will keep on focusing
on this point in this entire chapter so by the end of this chapter we all must understand this
concept.

b. “Life cycle of a servlet is managed by a Servlet Container and that is why servlets are also
known as container managed objects”

These are very important concepts and most of us get confused with these concepts
specifically on number of instances because Servlet is a web based model and servlet
can be accessed my multiple concurrent users so how the request gets handled.
By this chapter we all know that for any class to become a servlet, it has to either
extends GenericServlet class or HttpServlet Class

5.2 SERVLETS LIFE CYCLE


When a first request comes for a particular servlet, container does the following
a. Loads the class of servlet
b. Create an instance of servlet
c. Initialize the servlet by calling init() method
d. Once servlet is initialized,it is ready to serve the requests.
e. For each request, container spawns a new thread and that thread executes service() method od
a servlet.
f. When container decides to destroy the servlet, it invokes destroy() method of the servlet.

Below figure is the picture of a servlet which faces all methods discussed above,
Step 1, 2 and 3 are executed only once, when the servlet is initially loaded.
Step 4 is executed multiple times - once for every HTTP request to the servlet.
Step 5 is executed when the servlet container unloads the servlet.

5.3 EACH SERVLET LIFE CYCLE PHASE IN DETAIL


1. Load Servlet Class
For any java class to come in to execution mode, it has to be loaded and servlets are
not exception. Servlet class has to be loaded before a servlet can be invoked by the
servlet container so the servlet container must first load its class definition. Process of
loading servlet class is same as any other java class loading process.
Now it should be clear that this phase happens only once for a particular servlet and
reason is simple “One and only one instance of a servlet is created”.

2. Create Servlet Instance


Once the servlet class is loaded, the servlet container creates an instance of the servlet.
As we all know instance of each class has to be created before it actually works
(ignoring static concept right now).
Container executes this phase only once for a particular servlet because “One and only
one instance of a servlet is created”

3. Initialize servlet (Container Call the Servlets init() Method)


This phase is typically used to do initialization processing of a servlet. The init method is
called only once when the servlet is first created, and not called again for each user
request. When a servlet instance is created, its init() method is invoked. In this
method we can get the initialization or init parameters configured for the servlet in
web.xml file like below.
<servlet>
<servlet-name>MyFirstServlet</servlet-name>
<servlet-class>MyFirstServlet</servlet-class>
<init-param>
<param-name>param-name</param-name>
<param-value>param-value</param-value>
</init-param>
</servlet>
Typical use of init method is to do one time initializations like database initialization or
load some one time data. Gist is – this method should be used for one time activity.
init() method definition looks like below
public void init() throws ServletException
{
}

4. Call the Servlets service() Method


This is the main method that performs business logic and responsible for processing
client request. When a new request for a servlet comes, servlet container spawns a new
thread.
Then the thread executes the service() method and executes the business logic or the
intended task of the servlet.
Service() method definition looks like below
public void service(ServletRequest request, ServletResponse response)
throwsServletException, IOException
{
}
As you can see, service() method takes two arguments of type request and response.
With the help of request argument, we can get the session, can get the user inputs.
Similarly response helps to write back the response to the client,
Request can of several types like (GET, POST, PUT, DELETE, etc.) and The service()
method checks the HTTP request type and calls doGet, doPost, doPut, doDelete, etc.
methods as appropriate.
So in nutshell-
“for each request, service method gets executed which in-turn calls doGet(),
doPost(),doPut(), doDelete() etc depending on the type of request “
The doGet() and doPost() are most frequently used methods with in each service
request. Here is the signature of these two methods.
We will discuss about doGet() and doPost() in detail in upcoming chapters but let’s have
an overview about these methods
doGet()- Default request type for every request is “GET” which means if we do not
specify any method, it will be considered as GET request. As it names implies ideally it
should be used to GET something from server (though we can use GET to send data as
well).
public void doGet(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
}
doPost()- This method is generally used to submit the data to server.To make any
request of type POST, we need to specify attribute method as “POST”
public void doPost(HttpServletRequestrequest,HttpServletResponse response)
throwsServletException, IOException {
}
Thus, this step in the life cycle can be executed multiple times.

5. Call the Servlets destroy() Method


The destroy() method is called only once at the end of the life cycle of a servlet and thus
gives an opportunity to the servlet to perform some cleanup activities like database
connection close , closing of any files opened etc. We can relate it to finalize method
that gets execute before GC of an object.
This step is only executed once, since a servlet is only unloaded once.
A servlet is unloaded by the container in possibly two scenarios –

a. if the container shuts down,


b. if the container reloads the web application at runtime.

After the destroy() method is called, the servlet object is marked for garbage collection.
The destroy method definition looks like this:
public void destroy() {
}
As mentioned above, servlet is loaded when first request for that servlet comes. There
are scenarios where we need to get it loaded even before that or we can say at the time
of application deployment. To do that, we can set the <load-on-startup> property of
servlet configuration in web.xml
If we do not specify a <load-on-startup> element, the servlet container will typically load
your servlet when the first request arrives for it.By setting a <load-on-startup> element,
we tell the servlet container to load the servlet as soon as the servlet container starts.
<servlet>
<servlet-name>MyFirstServlet</servlet-name>
<servlet-class>MyFirstServlet</servlet-class>
<init-param>
<param-name>param-name</param-name>
<param-value>param-value</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
The number inside the <load-on-startup>1</load-on-startup> indicates the servlet
container, the sequence in which the servlets should be loaded. First the lower
numbers are loaded and in case the value is unspecified or negative, the servlet
container can load the servlet at any time.

5.4 Quiz /Exercise


Let’s have a quick and small questions on what we have discussed in this chapter.
Scenario 1 - Assume there is a web application “Display Message” which has a one
servlet “Display Message Servlet”. Display Message Servlet has a below print
statements in each of life cycle methods
Method name Print statement in corresponding
message

Init() Init method executed

Service Service method executed

Destroy Destroy method executed

Now there are two users who make the request to Display Message Servlet of
DisplayMessage web application. What would be the output?
Answer – As we know only one instance of a servlet is created no matter how many
request are coming so below will be the output. Service method will be executed as
many times requests are coming.
Init method executed
Service method executed
Service method executed
You must be wondering why “Destroy method executed” is not printed. Reason is that
destroy method will be executed only when servlet gets destroyed so you will see this
message when you un-deploy your web application OR when you shut down the server.
Scenario2- I have a requirement where one of my servlet (Load Servlet) loads some
data and rest all other servlets gets that data from Load Servlet. What is the important
thing we need to consider?
Answer- Since all other servlets are dependent on Load Servlet, which means we need
to get the Load Servlet loaded first. To do this we need to add <load-on-
startup>1</load-on-startup>

Overview
In this chapter we will discuss the typical directory structure of a web application and its
deployment.

6.2 Web Application Directory Structure


In any web application we can have following components –

 Static contents like HTML.


 Client side files like CSS and Javascript.
 JSP (Java Server Pages) to generate dynamic content.
 Servlets.
 External library or jar files.
 Any other java utility classes.
 web.xml also known as deployment descriptor
All web servers and container expects the web application to be available in a specific
directory structure. Below is the typical directory structure

Details –
Web Application Root Directory – This is the main or Root folder of web application.
Usually name of this folder becomes your web application context. For example ,if our
web application name is FirstWebApplication , then folder name will be
FirstWebApplication and web application will be accessible
via http://localhost:8080/FirstWebApplication
WEB-INF- This is the special directory under web application root directory. This is
special because this is secured folder and files available within this folder will not be
accessible to client directly. Which means say if this directory has one file “index.html”
then this file cannot be accessed directly
via http://localhost:8080/FirstWebApplication/index.html
WEB-INF/lib- All the required jar files or third party jar files will be placed inside this
directory.
WEB-INF/classes- All the java code including servlets for the web application will go
inside classes folder. We can also put our own classes into a JAR file, and place it here,
rather than putting those classes in the classes directory.
web.xml – web.xml resides under WEB-INF folder and it is also known as deployment
descriptor. All the configuration of web application like servlets configuration , filters
configuration , welcome file list etc are configured in web.xml. We will discuss web.xml
in detail
META-INF/MAINFEST.MF- This is the manifest file
Static Files – All static files like HTML, css ,javascript will be placed directly under web
application root directory. If we want to make these files secure , we need to place these
files under WEB-INF directory.

6.3 Web.xml (Deployment Descriptor)


This is the standard file for any web application and container comes to know about all
the detail of web application through this file only.
All configurations of all components of a web application are done in web.xml and it is
placed directly under WEB-INF folder.

6.3.1 Servlet Mapping


All servlets mapping need to be done in web.xml so that servlet container will be aware
of the servlets and also to make it accessible from a browser. We must tell the servlet
container what servlets to deploy, and what URL's to map the servlets to.
Below web.xml configures the Servlet “MyFirstServlet” with two init param.
?

1 <?xml version="1.0" encoding="ISO-8859-1"?>


<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi=http://www.w3.org/2001/XMLSchema-
2
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
3 <servlet>
4 <servlet-name> MyFirstServlet </servlet-name>
5 <servlet-class> MyFirstServlet </servlet-class>

6 <init-param>

7 <param-name>name</param-name>

<param-value>First Servlet</param-value>
8
</init-param>
9
<init-param>
10
<param-name>purpose</param-name>
11
<param-value>learning</param-value>
12 </init-param>

13 </servlet>
14 <servlet-mapping>

15 <servlet-name> MyFirstServlet </servlet-name>

<url-pattern>*.html</url-pattern>
16
</servlet-mapping>
17
</web-app>
18

19

Servlet is configured using the <servlet> element where we assign the servlet a unique
name, and writes the qualified class of the servlet. Then map servlet to a specific URL
or a URL pattern. This is done in the <servlet-mapping> element. In the above example,
all URL's ending in .html are sent to the servlet.
In above sample we have defined one init param as well which can be accessed in a
servlet. As the init params are defined within a servlet tag, they are limited to that servlet
only. One init-param tag is needed for one init parameter.
The * is a wild card, meaning any text.
When a request with URL ending with “html” , container-

a. check the servlet mapping of web.xml and finds the servlet name based on url pattern.
b. Once servlet name is found, gets the servlet class for matching servlet name.
c. Delegate request to the servlet class configured in corresponding servlet-class tag.

6.3.2 Context Parameters


init parameters are limited to the servlet in which they are defined but context
parameters are available to all the servlets of the web application. Below is the sample
configuration of context parameter.
Since these parameters are not limited to any servlet, they are defined outside the
<servlet> tag
?
1 <context-param>

2 <param-name>param</param-name>

3 <param-value>the value</param-value>

4 </context-param>

6.3.3 Early servlet loading & Initialization


As discussed earlier, servlet is loaded when first request for that servlet comes. There
are scenarios where we need to get it loaded even before that or we can say at the time
of application deployment. To do that, we can set the <load-on-startup> property of
servlet configuration in web.xml
If we do not specify a <load-on-startup> element, the servlet container will typically load
your servlet when the first request arrives for it.By setting a <load-on-startup> element,
we tell the servlet container to load the servlet as soon as the servlet container starts.
?
1
<servlet>
2
<servlet-name>MyFirstServlet</servlet-name>
3 <servlet-class>MyFirstServlet</servlet-class>
4 <init-param>

5 <param-name>param-name</param-name>

6 <param-value>param-value</param-value>

</init-param>
7
<load-on-startup>1</load-on-startup>
8
</servlet>
9

The number inside the <load-on-startup>1</load-on-startup> tells the servlet


container in what sequence the servlets should be loaded. The lower numbers are
loaded first. If the value is negative, or unspecified, the servlet container can load the
servlet at any time.

6.4 Web Archive (WAR)


Once the web application is developed, it needs to be deployed on server. Sun
specified a format known as WAR (web achieve) in which the web application has to be
packaged.
Once the packaged war file is deployed to the server, it gets exploded and deploys to
the server.
We can create a war file out of web application by executing below command using
command prompt.(we need to run this command after navigating to the web application
root directory)
jar cvf myapplication.war .
Above command says generate a war with name “myapplication.war” in a current
directory (there is a . in the end of command)

You might also like