Servlet (Autosaved)
Servlet (Autosaved)
• Java Servlets are the Java programs that run on the Java-enabled web
server or application server.
• They are used to handle the request obtained from the web server,
process the request, produce the response, and then send a response
back to the web server.
• Servlet technology is robust and scalable because of java language.
Before Servlet, CGI (Common Gateway Interface) scripting language
was common as a server-side programming language
• Servlet can be described in many ways, depending on the context.
• In this case, Java Servlet is also one of the component APIs of Java
Platform Enterprise Edition (nowadays known as – ‘Jakarta
EE’) which sets standards for creating dynamic Web applications in
Java.
Disadvantages of CGI:
There are many problems in CGI technology:
1.If the number of clients increases, it takes more time to send the
response.
2.For each request, it starts a process, and the web server is limited to
start processes.
3.It uses platform dependent language e.g. C, C++, perl.
Servlets APIs
Servlets are built from two
packages:
• javax.servlet(Basic)
• javax.servlet.http(Advance)
• Servlets are the Java programs that run on the Java-enabled web
server or application server.
• They are used to handle the request obtained from the webserver,
process the request, produce the response, then send a response
back to the webserver.
• In Java, to create web applications we use Servlets. To create Java
Servlets, we need to use Servlet API which contains all the necessary
interfaces and classes.
• Servlet API has 2 packages namely,
• javax.servlet
• javax.servlet.http
javax.servlet
• This package provides the number of interfaces and classes to
• These interfaces and classes describe and define the contracts
between a servlet class and the runtime environment provided
by a servlet container.
Class Name Description
This class provides an input stream to read binary data from a client
ServletInputStream
request.
ServletOutputStream This class provides an output stream for sending binary data to the client.
To perform filtering tasks on either the request to a resource, or on the response from a
Filter
resource, or both.
To provide a view into the invocation chain of a filtered request for a resource to the developer
FilterChain
by the servlet container.
RequestDispatche It defines an object to dispatch the request and response to any other resource, means it
r receives requests from the client and sends them to a servlet/HTML file/JSP file on the server.
This is the main interface that defines the methods in which all the servlets must implement. To
Servlet implement this interface, write a generic servlet that extends javax.servlet.GenericServlet or an
HTTP servlet that extends javax.servlet.http.HttpServlet.
It defines an object created by a servlet container at the time of servlet instantiation and to
ServletConfig
pass information to the servlet during initialization.
It defines a set of methods that a servlet uses to communicate with its servlet container. The
ServletContext information related to the web application available in web.xml file is stored in ServletContext
object created by container.
ServletContextAttr The classes that implement this interface receive notifications of changes to the attribute list on
ibuteListener the servlet context of a web application.
The classes that implement this interface receive notifications about changes to the
ServletContextListener
servlet context of the web application they are part of.
ServletRequestAttributeLis To generate the notifications of request attribute changes while the request is within
tener the scope of the web application in which the listener is registered.
Exceptions in javax.servlet
package:
Exception Name Description
Creates a cookie object. It is a small amount of information sent by a servlet to a Web browser, saved by the
Cookie
browser, and later sent back to the server used for session management.
HttpServlet Provides an abstract class that defines methods to create an HTTP suitable servlet for a web application.
HttpServletRequestWra This class provides implementation of the HttpServletRequest interface that can be subclassed to adapt the
pper request to a Servlet.
HttpServletResponseWr This class provides implementation of the HttpServletResponse interface that can be subclassed to adapt the
apper response from a Servlet.
This events are either sent to an object that implements HttpSessionBindingListener when it is bound or
HttpSessionBindingEven
unbound from a session, or to a HttpSessionAttributeListener that has been configured in the deployment
t
descriptor when any attribute is bound, unbound or replaced in a session.
HttpSessionEvent To represent event notifications for changes to sessions within a web application.
• Interfaces available in javax.servlet.http package:
• Interface Name Description
• 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.
• Stages of the Servlet Life Cycle:
• The Servlet life cycle mainly goes through four stages,
1. Loading a Servlet.
2. Initializing the Servlet.
3. Request handling.
4. Destroying the Servlet.
• Let’s look at each of these stages in details:
1.Loading a Servlet: The first stage of the Servlet lifecycle involves loading and
initializing the Servlet by the Servlet container. The Web container or Servlet
Container can load the Servlet at either of the following two stages :
1. Initializing the context, on configuring the Servlet with a zero or positive
integer value.
2. If the Servlet is not preceding stage, it may delay the loading process until the
Web container determines that this Servlet is needed to service a request.
• The Servlet container • Loading : Loads the Servlet class.
performs two operations in • Instantiation : Creates an instance of the
Servlet. To create a new instance of the
this stage : Servlet, the container uses the no-argument
constructor.
1.Initializing a Servlet: After the Servlet is
instantiated successfully, the Servlet
container initializes the instantiated Servlet
object. The container initializes the Servlet
object by invoking
the Servlet.init(ServletConfig) method
which accepts ServletConfig object reference
as parameter.The Servlet container invokes
the Servlet.init(ServletConfig) method
only once, immediately after
the Servlet.init(ServletConfig) object is
instantiated successfully. This method is used
to initialize the resources, such as JDBC
datasource.
2.Now, if the Servlet fails to initialize, then it
informs the Servlet container by throwing
the ServletException or UnavailableExcep
tion.
3 Handling request: After initialization, the Servlet instance is ready to serve the
client requests. The Servlet container performs the following operations when the
Servlet instance is located to service a request :
1. It creates the ServletRequest and ServletResponse objects. In this case, if
this is a HTTP request, then the Web container
creates HttpServletRequest and HttpServletResponse objects which are
subtypes of the ServletRequest and ServletResponse objects respectively.
2. After creating the request and response objects it invokes the
Servlet.service(ServletRequest, ServletResponse) method by passing the
request and response objects.
The service() method while processing the request may throw
the ServletException or UnavailableException or IOException.
4 Destroying a Servlet: When a Servlet container decides to destroy the Servlet,
it performs the following operations,
3. It allows all the threads currently running in the service method of the Servlet
instance to complete their jobs and get released.
4. After currently running threads have completed their jobs, the Servlet
container calls the destroy() method on the Servlet instance.
After the destroy() method is executed, the Servlet container releases all the
references of this Servlet instance so that it becomes eligible for garbage
collection.
Servlet Life Cycle Methods
• There are three life cycle methods of a Servlet :
• init()
• service()
• destroy()
1 init() method: 2 service() method:
• The Servlet container calls the The service() method of the Servlet is
invoked to inform the Servlet about the
Servlet.init() method to indicate client requests.
that this Servlet instance is • This method uses ServletRequest object
instantiated successfully and is to collect the data requested by the
about to put into service. client.
• //init() method • This method uses ServletResponse
object to generate the output content.
• // service() method
public class MyServlet implements
Servlet{ public class MyServlet implements
public void init(ServletConfig Servlet{
config) throws ServletException { public void service(ServletRequest res,
ServletResponse res)
//initialization code
throws ServletException, IOException {
} // request handling code
//rest of code }
} // rest of code
}
// Extend HttpServlet class
3 destroy() method: public class AdvanceJavaConcepts extends
The destroy() method runs only HttpServlet
{
once during a Servlet's lifetime private String output;
and signals the Servlet // Initializing servlet
instance's end public void init() throws ServletException
{
output = "Advance Java Concepts";
• //destroy() method }
// Requesting and printing the output
public void destroy() public void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException
• As soon as the destroy() {
method is activated, the resp.setContentType("text/html");
Servlet container releases the PrintWriter out = resp.getWriter();
out.println(output);
Servlet instance. }
• Here, we are going to use apache tomcat server in this example. The steps
are as follows:
1. Create a directory structure
2. Create a Servlet
3. Compile the Servlet
4. Create a deployment descriptor
5. Start the server and deploy the project
6. Access the servlet
• 1)Create a directory structures
• The directory structure defines that where to put the different
types of files so that web container may get the information
and respond to the client.
• The Sun Microsystem defines a unique standard to be
followed by all the server vendors. Let's see the directory
structure that must be followed to create the servlet.
• As you can see
that the servlet
class file must be
in the classes
folder.
• There are three ways to create the • For compiling the Servlet, jar file is
servlet. required to be loaded. Different Servers
1. By implementing the Servlet interface provide different jar files:
2. By inheriting the GenericServlet class Jar file Server
3. By inheriting the HttpServlet class 1) servlet-api.jar Apache Tomcat
2) weblogic.jar Weblogic
• The HttpServlet class is widely used to 3) javaee.jar Glassfish
create the servlet because it provides
methods to handle http requests such 4) javaee.jar JBoss
as doGet(), doPost, doHead() etc.
HttpServletRequest(I):
• HttpServletRequest interface extends the ServletRequest interface to
provide the Http-specific request information for Servlets.
• The servlet container creates an HttpServletRequest object and passes it
as an argument to the servlet’s service methods – doPost(), doGet(), etc.,
• The object provides data like parameter name and values, attributes, and
an input stream. And it has various methods to work with the client data.
getParameter() method:
• The method returns the value of a field/parameter from the request which
is specified by the given name, as a String. If the specified parameter
name does not exist, it returns null.
• This method should be used on the parameter that has only one value. If
multiple values are there, then it returns only the first value.
• Syntax:
• java.lang.String getParameter(java.lang.String name)
getParameterValues() method:
• The method returns an array of String objects containing all of the values
of the given field/parameter from the request. If the specified parameter
name does not exist, it returns null.
• Syntax:
• java.lang.String[] getParameterValues(java.lang.String name)
Steps to create the application: