Introduction
The rise of server-side Java applications is one of the latest and most exciting trends in Java programming. Initially,
Common Gateway Interface (CGI) scripts were the main technology used to generate dynamic content. Although widely used, CGI scripting technology has a
number of shortcomings, including platform dependence and lack of scalability.
To address these limitations, Java Servlet technology was created as a portable
way to provide dynamic, user-oriented content. Server-side java solves the problems that Applets are when the code is being executed on the server-side there are no issues with browser compatibility or long download time.
What is a Servlet?
Servlets are modules of Java code that run in a
server application (hence the name "Servlets", similar to "Applets" on the client-side) to answer client requests. Servlets are not tied to a specific client-server protocol but they are most commonly used with HTTP. Servlet programming is first created by Sun Microsystems in June 1997. The latest version is Servlet 2.5 which is released with JEE 5.0 specification.
In other words, Java Servlet is the
server-side Java programming language, acting as a middle layer between a request
coming from a Web browser or other HTTP client and databases or applications on
the HTTP server. Their job is to:
- Read any data sent by the user.
- Lookup any other information about the
request that is embedded in the HTTP request.
- Generate the results.
- Format the results inside a document.
- Set the appropriate HTTP response
parameters.
- Send the document back to the client.
The javax.servlet and javax.servlet.http packages
provide interfaces and classes for writing Servlets. All Servlets must implement
the Servlet interface, which defines life cycle methods. When implementing a
generic service, you can use or extend the GenericServlet class
provided with the Java Servlet API. The HttpServlet class provides
methods, such as doGet and doPost, for handling HTTP-specific services.
The Advantages of Servlets Over
"Traditional" CGI
- Efficient
- Convenient
- Powerful
- Portable
- Secure
- Inexpensive
Life Cycle of Servlet
The life cycle of a Servlet can be categorized
into four parts:
- Loaded and Instantiated - The
loading and instantiation can occur when the container is started, or
delayed until the container determines the Servlet is needed to service a
request. when the Servlet engine is started, the Servlet container loads the Servlet class using normal Java class loading facilities. The loading of the Servlet depends on the attribute <load-on-startup> of web.xml file. After
loading the Servlet class, the container instantiates it for use for client
request.
- Initialization - After the
Instantiated load, the container must be initialized before it can handle the request to the client. The container initializes the Servlet instance by calling the init method of the Servlet interface with a unique (per servlet declaration) object implementing the ServletConfig interface. The initialization parameters persist until the Servlet is destroyed. The init() method is called only once throughout the life cycle of the Servlet. The error should occur while the Servlet is initialized which is:
Error Conditions on Initialization.
Tool Considerations.
The Servlet will be available for service if it is loaded successfully
otherwise, the Servlet container unloads the Servlet.
- Servicing the request or Request
Handling - When a Servlet is properly initialized, the servlet container
may use to handle a client request which is represented by request object
ServletRequest. The ServletResponse() method is to provide the Servlet fill out the response of all the request. While in case of HTTP request, the objects
provided by the container are of types HttpServletRequest and
HttpServletResponse.The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends a response to the client using the methods of the response object.
Note some issue occurs by which a Servlet container may handle no requests
during its lifetime like:-
Multithreading Issues.
Exceptions During Request Handling.
Thread Safety Issues
- Destroying the Servlet: The Servlet container is not required to keep a Servlet loaded for any particular period
of time. whenever the Servlet container determines that a Servlet should be removed from service then it calls the destroy method of the Servlet interface to allow the Servlet to release all the resources that are held and save any persistent state. The destroy method only call when it must complete execution of any thread that is currently running in the service method of the servlet, or exceed a server-defined time limit. The destroy()
method, like init(), is called only once in the lifecycle of a Servlet.
Life cycle methods
The following are the life cycle methods
of a Servlet instance:
- public void init(ServletConfig
config) throws ServletException
This method is called once for a Servlet instance.
When the first-time Servlet is called, Servlet container creates an instance of
that Servlet and loaded into the memory.
The init method has a ServletConfig parameter. The Servlet can read its initialization arguments through the ServletConfig object. How the initialization arguments are set is Servlet engine dependent but they are
usually defined in a configuration file(web.xml).
An example of an initialization argument is a database identifier.
A Servlet can read this argument from the ServletConfig at initialization
and then use it later to open a connection to the database during the processing
of a request
- private String dbURL;
- public void init(ServletConfig config) throws ServletException {
- super.init(config);
- dbURL = config.getInitParameter("database");
- }
- public void service(HttpServletRequest
request, HttpServletResponse response) throws ServletException, IOException
This method is called to process a request. It can be called zero, one or many times until the Servlet is unloaded. This is the entry point for the every Servlet request and here we have to write our business logic or any other processes. This method takes HttpServletRequest and
HttpServletresponse as the parameters. It is not mandatory to write this
method, normally developers are interested in writing doGet() or
doPost() methods which is by default called from the service()
method. If you override service(), it is your responsibility to call the appropriate methods. If you are not overridden the service()
method, based on the types of request the methods will be called.
- import java.io.*;
- import javax.servlet.*;
- import javax.servlet.http.*;
- public class SerLifeCycle extends HttpServlet
- {
- int count=0;
- protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
- {
- response.setContentType("text/html");
- PrintWriter pw=response.getWriter();
- count++;
- pw.println("<html><body>");
- pw.println("Since loading, this servlet has been accessed " + count + " times.");
- pw.println("</body></html>");
- }
- }
The variable count is
shared by all the threads each corresponding to a single request. So this provides a way for the threads to communicate with each other.
-
public void destroy()
This method is called once just before the Servlet is unloaded and taken out of service. It is used for releasing any resources used by the Servlet instance. Most of the times it could be database connections, Fill IO
operations, etc.
destroy() is called by the container when it
is removing the instance from the
servlet container. Servlet
instance is deleted or garbage collected by the container only when the web
server issues shut down or the instance is not used for a long time.
- public void destroy()
- {
- }
Usage