Chapter 6 Servlet
Chapter 6 Servlet
1
• Servlet is a java program that runs inside JVM on the web server. It is used for developing
dynamic web applications.
Before we proceed further lets understand what is dynamic web application? A web
application can be described as collection of web pages (e.g. a website) and when we call it
dynamic, it simply means that the web pages are not same for all the users, web pages would
be generated on server side based on the request made by client(user’s browser).
• The main difference between static and dynamic web page is that static page as name
suggests remains same for all users however a dynamic web page changes based on the
request from client (user’s browser). For example, consider a web application that shows you
two input fields & an add button and when you enter two numbers and click add, it shows
you another web page that has the result of addition of two numbers, this web application is
dynamic in nature as the second web page that shows you the result changes based on the
user input, it is not static for all users.
• However you can very well say that what a servlet does can be done by CGI (Common
Gateway Interface), well its true but here is the thing – CGI has several limitations such as
performance, scalability, reusability etc. that a servlet doesn’t have. I am not going to
discuss CGI in detail but I am going to tell you, how a servlet is better than CGI.
Limitations of CGI
Server has to create a new CGI process for every client request. For example, If
100 users are accessing the web application, then the server has to create 100 CGI
processes to handle the request made by them. Since a server has limited
resources, creating new process every time for a new request is not a viable
option, this imposed the limitation on server, due to that the server cannot handle
more than a specified number of users at the same time.
Ms.Adhatrao A S
20-12-2021 3
How Servlet is better than CGI
CGI programs are handled by a new process every time a new request has been
made. Unlike CGI, the servlet programs are handled by separate threads that can
run concurrently more efficiently.
CGI program can be written in any programming language that makes it mostly
platform dependent as not all programming languages are platform independent.
Servlet only uses Java as programming language that makes it platform
independent and portable. Another benefit of using java is that the servlet can take
advantage of the object oriented programming features of java.
Ms.AdhatraoA S
12/20/2021 4
How Servlet Works
As I mentioned above that concurrent requests to the server are handled by
threads, here is the graphical representation of the same –
12/20/2021 5
Features of Servlet
Now that we have understood what is a servlet and for what purpose it is being used. Let’s
proceed further and discuss its main features.
1. Portable:
As I mentioned above that Servlet uses Java as a programming language, Since java is platform
independent, the same holds true for servlets. For example, you can create a servlet on Windows
operating system that users GlassFish as web server and later run it on any other operating system
like Unix, Linux with Apache tomcat web server, this feature makes servlet portable and this is
the main advantage servlet has over CGI.
2. Efficient and scalable:
Once a servlet is deployed and loaded on a web server, it can instantly start fulfilling request of
clients. The web server invokes servlet using a lightweight thread so multiple client requests can
be fulling by servlet at the same time using the multithreading feature of Java. Compared to CGI
where the server has to initiate a new process for every client request, the servlet is truly efficient
and scalable.
3. Robust:
By inheriting the top features of Java (such as Garbage collection, Exception handling, Java
Security Manager etc.) the servlet is less prone to memory management issues and memory leaks.
This makes development of web application in servlets secure and less error prone.
12/20/2021 7
Servlet
Servlet is used to create web applications. Servlet uses Java language to create web
applications.
Web applications are helper applications that resides at web server and build
dynamic web pages. A dynamic page could be anything like a page that randomly
chooses picture to display or even a page that displays the current time.
Types of Servlet
Generic servlets
HTTP servlets
The life cycle of a servlet is controlled by the container in which the servlet has
been deployed. When a request is mapped to a servlet, the container performs the
following steps.
If an instance of the servlet does not exist, the Web container
Loads the servlet class.
Creates an instance of the servlet class.
Initializes the servlet instance by calling the init method. Initialization is covered in
Initializing a Servlet.
Before I start explaining the life cycle of Servlet, lets discuss few terminologies
that you will encounter while reading this guide. It is important to learn what each
term means, this will help you understand things faster.
Web Server: It is also known as HTTP Server, it can handle HTTP Requests send
by client and responds the request with an HTTP Response.
Web Container: Also known as Servlet Container and Servlet Engine. It is a part
of Web Server that interacts with Servlets. This is the main component of Web
Server that manages the life cycle of Servlets.
12/20/2021 12
Servlet life cycle methods
The init() method
The init method is designed to be called only once. It is called when the servlet is
first created. So, it is used for one-time initializations, just as with the init
method of applets.
The servlet is normally created when a user first invokes a URL corresponding to
the servlet, but you can also specify that the servlet be loaded when the server is
first started.
When a user invokes a servlet, a single instance of each servlet gets created, with
each user request resulting in a new thread that is handed off to doGet or doPost
as appropriate. The init() method simply creates or loads some data that will be
used throughout the life of the servlet.
The init method definition looks like this:
Every request has a header that tells the status of the client. There are
many request methods. Get and Post requests are mostly used.
As I mentioned above, if you are creating a Generic Servlet then you must extend
javax.servlet.GenericServlet class. GenericServlet class has an abstract service()
method. Which means the subclass of GenericServlet should always override the
service() method.
Signature of service() method:
public abstract void service(ServletRequest request, ServletResponse response)
throws ServletException, java.io.IOException
The service() method accepts two arguments ServletRequest object and
ServletResponse object. The request object tells the servlet about the request made
by client while the response object is used to return a response back to the client.
12/20/2021 19
12/20/2021 20
HTTP Servlet
If you creating Http Servlet you must extend javax.servlet.http.HttpServlet class, which is
an abstract class. Unlike Generic Servlet, the HTTP Servlet doesn’t override the service()
method. Instead it overrides one or more of the following methods. It must override at
least one method from the list below:
1. doGet() – This method is called by servlet service method to handle the HTTP GET
request from client. The Get method is used for getting information from the server
2. doPost() – Used for posting information to the Server
3. doPut() – This method is similar to doPost method but unlike doPost method where we
send information to the server, this method sends file to the server, this is similar to the
FTP operation from client to server
4. doDelete() – allows a client to delete a document, webpage or information from the
server
5. init() and destroy() – Used for managing resources that are held for the life of the servlet
6. getServletInfo() – Returns information about the servlet, such as author, version, and
copyright.
12/20/2021 21
In Http Servlet there is no need to override the service() method as this
method dispatches the Http Requests to the correct method handler, for example if
it receives HTTP GET Request it dispatches the request to the doGet() method.
12/20/2021 22
Interfaces in javax.servlet package
1. Servlet
2. ServletRequest
3. ServletResponse
4. ServletConfig
5. ServletContext
6. SingleThreadModel
7. RequestDispatcher
8. ServletRequestListener
9. ServletRequestAttributeListener
10. ServletContextListener
11. ServletContextAttributeListener
12. Filter
13. FilterConfig
14. FilterChain
12/20/2021 23
Classes in javax.servlet package
1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletException
5. ServletRequestWrapper
6. ServletRequestEvent
7. ServletResponseWrapper
8. ServletContextEvent
9. ServletRequestAttributeEvent
10. ServletContextAttributeEvent
11. UnavailableException
12/20/2021 24
Interfaces in javax.servlet.http
package
1. HttpSession
2. HttpServletRequest
3. HttpServletResponse
4. HttpSessionAttributeListener
5. HttpSessionListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext
12/20/2021 25
Classes in javax.servlet.http package
1. HttpServlet
2. Cookie
3. HttpSessionEvent
4. HttpSessionBindingEvent
5. HttpServletRequestWrapper
6. HttpServletResponseWrapper
7. HttpUtils
12/20/2021 26
While discussing Servlet API, I have discussed little bit about Generic Servlet. In
this article, I will discuss Generic Servlet in detail.
A generic servlet is a protocol independent Servlet that should always override the
service() method to handle the client request. The service() method accepts two
arguments ServletRequest object and ServletResponse object. The request object
tells the servlet about the request made by client while the response object is used
to return a response back to the client.
12/20/2021 27
How Generic Servlet works?
12/20/2021 28
Hierarchy of Generic Servlet
java.lang.Object
|_extended byjavax.servlet.GenericServlet
GenericServlet is an abstract class and it has only one abstract method, which is
service(). That’s why when we create Generic Servlet by extending GenericServlet
class, we must override service() method.
Pros of using Generic Servlet:
1. Generic Servlet is easier to write
2. Has simple lifecycle methods
3. To write Generic Servlet you just need to extend javax.servlet.GenericServlet and
override the service() method (check the example below).
12/20/2021 29
Cons of using Generic Servlet:
Working with Generic Servlet is not that easy because we don’t have convenience
methods such as doGet(), doPost(), doHead() etc in Generic Servlet that we can
use in Http Servlet.
In Http Servlet we need to override particular convenience method for particular
request, for example if you need to get information then override doGet(), if you
want to send information to server override doPost(). However in Generic Servlet
we only override service() method for each type of request which is cumbersome.
12/20/2021 30
Methods of GenericServlet class:
Here is the list of all the methods of GenericServlet class.
1. public void init(): it is a convenient method. This method can be overridden so that there’s no
need to call super.init(config).
2. public void init(ServletConfig config): Called by the servlet container to indicate that the servlet
is being placed into service, this method is used for initializing the servlet.
3. public String getInitParameter(String name): Returns a String containing the value of the given
initialization parameter, or null if the parameter does not exist.
4. public Enumeration getInitParameterNames(): Returns the names of all the parameters defined in
the web.xml file or null if web.xml does’t have any parameter.
12/20/2021 31
6. public void destroy(): It is called by servlet container once at the end of servlet life cycle to
indicate that servlet is being destroyed.
7. public ServletConfig getServletConfig(): Return the ServletConfig object that initialized this
servlet
10. public String getServletName(): Returns the name of the servlet instance.
11. public void log(String msg): Writes the given message in the servlet log file.
12. public void log(String msg,Throwable t): Writes the explanatory message in the servlet log file
including a String that describes the error or exception.
12/20/2021 32
HttpServlet class
In Servlet API, I have discussed little bit about Http Servlet. In this article, I will
discuss Http Servlet in detail.
Unlike Generic Servlet, the HTTP Servlet doesn’t override the service() method.
Instead it overrides the doGet() method or doPost() method or both. The doGet()
method is used for getting the information from server while the doPost() method
is used for sending information to the server.
In Http Servlet there is no need to override the service() method because this
method dispatches the Http Requests to the correct method handler, for example if
it receives HTTP GET Request it dispatches the request to the doGet() method.
12/20/2021 33
How Http Servlet works?
As you can see in the diagram below that client (user’s browser) make requests.
These requests can be of any type, for example – Get Request, Post Request, Head
Request etc. Server dispatches these requests to the servlet’s service() method, this
method dispatches these requests to the correct handler for example if it receives
Get requests it dispatches it to the doGet() method.
12/20/2021 34
Hierarchy of Http Servlet
java.lang.Object
|_extended by javax.servlet.GenericServlet
|_extended by javax.servlet.http.HttpServlet
I have already discussed in the Generic Servlet article that you should always use
HttpServlet instead of the GenericServlet. HttpServlet is easier to work with, and
has more methods to work with than GenericServlet.
12/20/2021 35
Methods of HttpServlet class
12/20/2021 36
4. protected void doPost(HttpServletRequest req, HttpServletResponse resp): This
method is called by servlet service method to handle the POST request from client. The
HTTP POST method allows the client to send data of unlimited length to the Web server
a single time and is useful when posting information to the server. Unlike, doGet where
we get information from the sever this method is used when we are transferring
information from client to the server.
10. public void service(ServletRequest req, ServletResponse res): Forwards client request
to the protected service method. There’s no need to override this method as well.
12/20/2021 38
12/20/2021 39