Open-Source Internship opportunity by OpenGenus for programmers. Apply now.
Reading time: 45 minutes
Java Servlets are programs that run on a Web or Application server and act as a middle layer between a requests coming from a Web browser or other HTTP client and databases or applications on the HTTP server.
You can also define servlets as
- Servlet is a technology which is used to create a web application.
- Servlet is a web component that is deployed on the server to create a dynamic web page.
- A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model.
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 such as:
-
Performance is significantly better.
-
Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request.
-
Servlets are platform-independent because they are written in Java.
-
Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. So servlets are trusted.
-
The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms.
Servlet Architecture
The figure below shows the position of servlet in a Web Application
Servlet API Hierarchy
Servlet is Java EE server driven technology to create web applications in java. The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing our own servlets.
javax.servlet.Servlet is the base interface of Servlet API and also defines servlet lifecycle methods.The HttpServlet class provides methods, such as doGet() and doPost(), for handling HTTP-specific services.
Mostly web applications are accessed using HTTP protocol and thats why we mostly extend HttpServlet class.
1. Servlet
Interface
All the servlet classes are required to implement this interface. The methods declared in this interface are:
a. public abstract void init(ServletConfig paramServletConfig) throws ServletException -
We can extend this method in our servlet classes to initialize resources such as DB Connection, Socket connection etc.
b. public abstract void service(ServletRequest req, ServletResponse res) throws ServletException, IOException -
This method is responsible for processing the client request. We will look into this method later.
c. public abstract void destroy() -
This method can be called only once in servlet life cycle and used to close any open resources. This is like finalize method of a java class.
d. public abstract String getServletInfo() -
This method returns string containing information about the servlet, such as its author, version, and copyright.
2. ServletConfig
Interface
This is used to pass configuration information to Servlet. Every servlet has it’s own ServletConfig object and servlet container is responsible for instantiating this object.
The important methods of ServletConfig interface are:
a. public abstract ServletContext getServletContext() -
This method returns the ServletContext object for the servlet. We will look into ServletContext interface in next section.
- b. public abstract Enumeration<String> getInitParameterNames() - This method returns the Enumeration<String> of name of init parameters defined for the servlet. If there are no init parameters defined, this method returns empty enumeration.
c. public abstract String getInitParameter(String paramString) - This method can be used to get the specific init parameter value by name. If parameter is not present with the name, it returns null.
3. ServletContext
interface
This interface provides access to web application variables to the servlet. The ServletContext is unique object and available to all the servlets in the web application.
Some of the important methods of ServletContext are:
a. public abstract ServletContext getContext(String uripath) -
This method returns ServletContext object for a particular uripath or null if not available or not visible to the servlet.
b. public abstract URL getResource(String path) throws MalformedURLException -
This method return URL object allowing access to any content resource requested. We can access items whether they reside on the local file system, a remote file system, a database, or a remote network site without knowing the specific details of how to obtain the resources.
c. public abstract void log(String msg) - This method is used to write given message string to the servlet log file.
d. public abstract Object getAttribute(String name) - Return the object attribute for the given name.
e. public abstract void setAttribute(String paramString, Object paramObject) - This method is used to set the attribute with application scope. The attribute will be accessible to all the other servlets having access to this ServletContext.
f. public abstract void removeAttribute(String paramString) - This method is used to remove an attribute.
g. String getInitParameter(String name) - This method returns the String value for the init parameter defined with name in web.xml, returns null if parameter name doesn’t exist.
h. boolean setInitParameter(String paramString1, String paramString2) - We can use this method to set init parameters to the application.
4. ServletRequest
interface
ServletRequest interface is used to provide client request information to the servlet. Servlet container creates ServletRequest object from client request and pass it to the servlet service() method for processing.
The child interface of ServletRequest is HttpServletRequest that contains some other methods for session management, cookies and authorization of request
Some of the important methods of ServletRequest interface are:
a. Object getAttribute(String name) - This method returns the value of named attribute as Object and null if it’s not present.
b. String getParameter(String name) - This method returns the request parameter as String.
c. String getServerName() - Returns the hostname of the server.
d. int getServerPort() - Returns the port number of the server on which it’s listening.
5. ServletResponse interface
ServletResponse interface is used by servlet in sending response to the client. Servlet container creates the ServletResponse object and pass it to servlet service() method and later use the response object to generate the HTML response for client
Some of the important methods in HttpServletResponse are:
a. void addCookie(Cookie cookie) - Used to add cookie to the response.
b. void addHeader(String name, String value) - Used to add a response header with the given name and value.
c. String encodeURL(java.lang.String url) - Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged.
d. void sendRedirect(String location) - Used to send a temporary redirect response to the client using the specified redirect location URL.
e. void setStatus(int sc) - Used to set the status code for the response.
6. HTTPServlet class
a. doGet() - For HTTP GET requests b. doPost() - For HTTP POST requests c. doPut() - For HTTP PUT requests d. doDelete() - For HTTP DELETE requests7. GenericServlet class
GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It provides the implementation of all the methods of these interfaces except the service method. GenericServlet class can handle any type of request so it is protocol-independent.Servlet Life Cycle
A servlet life cycle can be defined as the entire process from its creation till the destruction.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.
The main phases in a servlet life-cycle are-
- Loading a Servlet.
- Initializing the Servlet.
- Request handling.
- Destroying the Servlet.
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
a. Loads the servlet class.
b. Creates an instance of the servlet class.
c. Initializes the servlet instance by calling the init method. - Invokes the service method, passing request and response objects to process a client's request.
- If the container needs to remove the servlet, it finalizes the servlet by calling the servlet’s destroy method i.e., the servlet is terminated by calling the destroy() method.
- Lastly, servlet is garbage collected by the garbage collector of the JVM.
Lets have a closer look at the methods involved in the life cycle process.
Life-cycle Methods
1. init() Method
Just as with the init method of applets, the init method is called only for one-time initialization. It is not called for any user requests afterwards.
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
}
2. sevice() Method
The web container calls the service method each time when request for the servlet is received.This is method where all the main code is written for performing the actual task. The web container (or servlet container) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client.
It makes use of two objects namely,
- This method uses ServletRequest object to collect the data requested by the client.
- 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
}
The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
The most frequently used are doPost() and doGet().
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
3. destroy() Method
The destroy() method marks the servlet object for garbage collection.It is called only once during the life-cycle of the servlet.This method is a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.
Once this method is activated, the Servlet container releases the Servlet instance.
// destroy() method
public class MyServlet implements Servlet{
public void destroy(){
// finalization code
}
}