Welcome to the Java Servlet Tutorial, which is part of the Java Certification course offered by Simplilearn. We will learn about Java Servlet and various other elements of Java Servlet in this tutorial.
On completion of this Java Servlet tutorial, we will be able to:
Let us look at the topics covered below under this section.
We have learned that web server generates two types of responses:
However, a web server can generate static responses in the form of HTML. To generate a dynamic response, a programming language that performs dynamic operations is needed.
Servlet is a Java program that can perform dynamic operations and send it to the web server. The web server then sends this response to the web client.
Let’s look at these two types below:
Every time we type HTTPS://www.google.com/ in your browser, you are directed to the Google homepage. This is called a static page as the web server displays the same HTML page every time the client requests.
When users log in to their Facebook account, different pages will be generated for different users. These are not Static Pages that are saved on the server-side and later displayed. Instead, they are dynamically generated based on the user ID. So you would see the pages relevant to your login. This requires multiple responses from the server, called Dynamic Response and hence we need Servlets, which is programming capability on the server side to generate such dynamic content.
Let us understand Client-Server Architecture below.
Web server is a program that sends HTTP response, and Servlet is a Java Program that deals with classes and objects. How is the response generated in the HTTP format?
It is done by the web server at work that purely works on HTTP protocol. This is done using a web container present on the web server.
Let’s understand the web container below.
A web container is built on top of the Java EE platform, and it implements the Servlet API and the services required to process HTTP (and other Transmission Control/Internet Protocol [TCP/IP]) requests.
The lifecycle of a Servlet is controlled by the web container in which the Servlet has been deployed.
Given below are some of the topics discussed in this section.
Learn more about Java Certification course details. Click to know more!
Servlet API contains a number of classes and interfaces that describe the contracts between a servlet class and the runtime environment provided for an instance by a conforming servlet container. Servlet API provides the following two packages that contain its classes and interfaces:
javax.servlet.*; |
Classes and interfaces define the contracts between a Servlet class and the runtime environment provided for an instance of such a class by a conforming Servlet container. |
javax.servlet.HTTP.*; |
Classes and interfaces define the contracts between a Servlet class running under the HTTP protocol and the runtime environment provided for an instance of such a class by a conforming Servlet container. |
This largely is the ecosystem in terms of the set of functions, API’s, Interfaces and classes available as part of Java Servlet API.
The table below lists out some of the interface functions.
javax.servlet.FilterConfig |
Passes information to a filter during initialization |
javax.servlet.RequestDispatcher |
Sends request and response object to any resource (such as a Servlet, HTML file, or JSP file) on the server |
javax.servlet.Servlet |
Defines methods that all Servlets must implement |
javax.servlet.ServletConfig |
A Servlet configuration object used by a Servlet container to pass information to a Servlet during initialization |
javax.servlet.ServletContext |
Defines a set of methods that a Servlet uses to communicate with its Servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file |
javax.servlet.ServletContextAttributeListener |
Implementation of this interface receives notifications of changes to the attribute list on the Servlet context of a web application |
javax.servlet.ServletContextListener |
Implementation of this interface receives notifications about changes to the Servlet context of the web application they are a part of |
javax.servlet.ServletRequest |
Defines an object to provide client request information to a Servlet |
javax.servlet.ServletRequestAttributeListener |
A ServletRequestAttributeListener can be implemented by the developer interested in being notified of request attribute changes |
javax.servlet.ServletRequestListener |
A ServletRequestListener can be implemented by the developer interested in being notified of requests coming in and out of scope in a web component |
javax.servlet.ServletResponse |
Defines an object to assist a Servlet in sending a response to the client |
Given below is the hierarchy that needs to be followed to create a Servlet.
javax.servlet.Servlet (I) |
All Servlets must implement the Servlet interface that defines lifecycle methods |
javax.servlet.GenericServlet(C) |
Servlet can also be created by extending GenericServlet abstract class. GenericServlet abstract class implements all methods of Servlet interface except service method. |
javax.servlet.HTTP.HTTPServlet(C) |
Another way of creating a Servlet is to extend HTTPServlet abstract class. HTTPServlet abstract class extends GenericServlet abstract class |
User Defined Servlet |
I —Interface, C—Class. |
Servlet interface has 5 methods:
Let us look into the 5 methods.
The init method is called by Servlet container to indicate to a Servlet that it is being placed into service. It is declared as:
void init (ServletConfig config)
The service method is called by the Servlet container to allow the Servlet to respond to a request. So it takes a response and request object. It is declared as:
public void service(ServletRequest req, ServletResponse res) throws ServletException, java.io.IOException
The destroy() indicates that the Servlet is being taken out of service and needs to be destroyed. It is declared as:
public void destroy()
The getServletInfo method returns information about the Servlet. It is declared as:
public java.lang.String getServletInfo()
Returns a ServletConfig object that contains initialization and start-up parameters for the Servlet. It is declared as:
public ServletConfig getServletConfig()
Some of the Abstract Class methods mentioned below are:
void init(ServletConfig config) |
Called by the Servlet container to indicate to a Servlet that the Servlet is being placed into service |
void log(java.lang.String msg) |
Writes the specified message to a Servlet log file, prepended by the Servlet's name |
void log(java.lang.String message, java.lang.Throwable t) |
Writes an explanatory message and a stack trace for a given Throwable exception to the Servlet log file, prepended by the Servlet's name |
abstract void service(ServletRequest req, ServletResponse res) |
Allows the Servlet to respond to a request. |
public abstract class GenericServlet |
Extends java.lang.Object implements Servlet, ServletConfig, and java.io.Serializable |
java.lang.String getInitParameter(java.lang.String name) |
Returns a String containing the value of the named initialization parameter, or returns null if the parameter does not exist |
java.util.Enumeration getInitParameterNames() |
Returns the names of the Servlet's initialization parameters as an Enumeration of String objects, or returns an empty Enumeration if the Servlet has no initialization parameters |
ServletContext getServletContext() |
Returns a reference to the ServletContext in which the Servlet is running |
java.lang.String getServletName() |
Returns the name of this Servlet instance |
void init() |
A convenient method which can be overridden so that there's no need to call super.init(config) |
It provides an abstract class to be subclassed to create an HTTP Servlet suitable for a website.
Following is the list of methods mentioned in the table:
public abstract class HTTPServlet |
Extends GenericServlet Implements java.io.Serializable |
doGet |
Used if the Servlet supports HTTP GET requests |
doPost |
Used for execution of HTTP POST requests |
doPut |
Used for HTTP PUT requests |
doDelete |
Used for HTTP DELETE requests |
init and destroy |
Used to manage resources that are held for the life of the Servlet |
getServletInfo |
Used by the Servlet to provide information about itself |
The lifecycle of a Servlet is controlled by the container in which the Servlet has been deployed. When a request is mapped to the Servlet, the container performs the following steps if an instance of the Servlet does not exist.
Let’s look at the topics mentioned below under this section.
Create a dynamic web project in eclipse.
We will add a web XML by selecting but the web XML checkbox and Click finish
Given below are the steps involved to add the server to project.
The steps to run Apache Tomcat server are:
The image below gives the code structure for creating HTML file.
The image below gives the code structure for creating java class Servlet.
Steps required to create the web.XML file are mentioned below:
Inside the web container of the web server, inside the deployment destructor file, we will prove the configuration name and the package name for the servlet. The web container will create only one servlet object in the deployment descriptor.
Steps to configure Servlet mapping:
After Configuring, when we hit a URL of localhost port no: 8080(default port for TOMCAT), and the name of the file we are looking for, it will do a lookup in the web container, and it will check the deployment descriptor whether there is a mapping to the correct servlet. It will then process it, generate an HTML file and sends it back to client-server.
When the URL pattern becomes HTTP://localhost:8080/project name/check, the Web container looks in web.XML to find the location of the servlet class using servlet name and servlet mapping.
When the user selects the home page by the way of URL HTTP://localhost:8080/project name/urlpatterns, the web container responds with the HTML code for the home page.
In this section, we will be covering:
The points below helps us understand ServletRequest.
Some of the methods available are given below:
getAttribute(): |
returns the value of the the name |
getAttributeNames(): |
returns enumeration containing the names of the attributes. |
getCharacterEncoding(): |
returns the name of the character encoding used in the body of the request |
getContentLength(): |
returns the length of the request body (in bytes) |
getContentType(): |
returns MIME type of the body of the request |
getInputStream(): |
retrieves the body of the request as binary data |
getLocale(): |
returns the preferred locale, that the client will accept |
getLocales(): |
returns an enumeration of local objects |
getLocalName(): |
returns the host name of the IP interface on which the request was received. |
getLocalPort(): |
gives you the port number |
getParameter(): returns |
a perimeter value based on the key |
getParameterMap(): |
returns java.util.Map |
getParameterNames(): |
returns an Enumeration |
getParameterValues() |
returns an array of string objects containing all of the values that given request parameter has |
getProtocol() |
gives us the protocol |
getReader() |
retrieves the body of the request as character data using BufferedReader |
setAttribute() |
stores an attribute in the request |
Let us discuss ServletConfig and ServletContext below in details.
Let us understand ServletConfig below:
Let us understand ServletContext below:
Let us look at some of the methods mentioned below in the table.
java.lang.String getInitParameter(java.lang.String name) |
Returns a String containing the value of the named initialization parameter, or returns null if the parameter does not exist |
java.util.Enumeration getInitParameterNames() |
Returns the names of the servlet's initialization parameters as an Enumeration of String objects, or returns an empty Enumeration if the servlet has no initialization parameters |
ServletContext getServletContext() |
Returns a reference to the ServletContext in which the caller is executing. |
java.lang.String getServletName() |
Returns the name of this servlet instance |
public interface ServletContext |
Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file |
java.lang.Object getAttribute(java.lang.String name) |
Returns the servlet container attribute with the given name, or returns null if there is no attribute by that name |
java.util.Enumeration getAttributeNames() |
Returns an Enumeration containing the attribute names available within this servlet context |
ServletContext getContext(java.lang.String uripath) |
Returns a ServletContext object that corresponds to a specified URL on the server |
java.lang.String getInitParameter(java.lang.String name) |
Returns a String containing the value of the named context-wide initialization parameter, or returns null if the parameter does not exist |
java.util.Enumeration getInitParameterNames() |
Returns the names of the context initialization parameters as an Enumeration of String objects, or returns an empty Enumeration if the context has no initialization parameters |
Let us look into the topics that will be covered under this section.
Servlet Attributes
Attribute-Specific Methods
Attributes allow data to be stored and used in inter Servlet communication. The methods associated with attribute manipulation are:
Attribute |
Scope of Data |
ServletRequest |
Duration of the request |
HTTPSession |
While the client is active |
ServletContext |
The life of Web Application |
The table below has some of the functions mentioned.
public void setAttribute() |
This method is used to set the given object in the application scope |
getAttribute() |
used to return the value of the attribute for the specified name |
getInitParameterNames() |
which is used to return the names of the context’s initialization parameter as an Enumeration. |
removeAttributes(): |
used to remove that attribute with a given name from the Servlet context. |
Let us understand the topics covered under this section.
Keen on learning more about Java Certification training? Get detailed info here!
The Servlet Collaboration involves sharing of information among multiple servlets.
Collaborating Servlets is passing common information that is to be shared directly by one Servlet to another Servlet of HTML or JSP through various invocations of methods.
There are various ways of Servlet Collaboration
Let us understand Forwarding and Redirecting below:
forward() method Syntax
RequestDispatcher= request. getRequestDispatcher(“url_pattern_for_servlet or HTML_file_name”);
rd.forward(request, response)
include() method Syntax
RequestDispatcher rd= request.getRequestDispatcher(“url_pattern_for_servlet or HTML_file_name”);
rd.include(request, response);
We enter UserName and Password and Click Log In.
Next, the validate Servlet checks if the information provided invalid.
If it is valid; we move to the Welcome Servlet.
If the validation fails; the response is included in the HTML file and sends back with a specific error message.
A quick summary of the various functions we have covered so far.
Let us quickly go through the topics we have covered so far in this tutorial.
This covers the Java Servlet tutorial.
Name | Date | Place | |
---|---|---|---|
Java Certification Training | 7 May -18 Jun 2021, Weekdays batch | Your City | View Details |
A Simplilearn representative will get back to you in one business day.