Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 10

JAVA SERVLET

Introduction Applications of Servlet-

1. Read the explicit data sent by the clients (browsers). This includes an
The Java Servlet, now also known as the Jakarta Servlet, is a Java Server HTML form on a Web page or it could also come from an applet or a
Software component, designed and deployed to enhance the Server custom HTTP client program.
services by upgrading their capabilities to respond to any requests through 2. Read the implicit HTTP request data sent by the clients (browsers).
a Web API. This includes cookies, media types and compression schemes the
Java Servlet or Jakarta Servlet as the technology to design and deploy browser understands, and so forth.
dynamic web pages using the Java Programming Language. It implements 3. Process the data and generate the results. This process may require
a typical servlet in the client-server architecture, and the Servlet lives on talking to a database, executing an RMI or CORBA call, invoking a
the server-side. Web service, or computing the response directly.
4. Send the explicit data (i.e., the document) to the clients (browsers).
Servlets provide a component-based, platform-independent method for This document can be sent in a variety of formats, including text
building Web based applications, without the performance limitations of (HTML or XML), binary (GIF images), Excel, etc.
CGI programs. Servlets have access to the entire family of Java APIs, 5. Send the implicit HTTP response to the clients (browsers). This
including the JDBC API to access enterprise databases. includes telling the browsers or other clients what type of document is
Java Servlets often serve the same purpose as programs implemented using being returned (e.g., HTML), setting cookies and caching parameters,
the Common Gateway Interface (CGI). But Servlets offer several and other such tasks.
advantages in comparison with the CGI.
1. Performance is significantly better. There are several varieties of interfaces and classes available
in the Servlet API. Some of them are as follows:
2. Servlets execute within the address space of a Web server. It is not
HTTP Servlet
necessary to create a separate process to handle each client request.
Generic Servlet
3. Servlets are platform-independent because they are written in Java. Servlet Request
Servlet Response
4. Java security manager on the server enforces a set of restrictions to
protect the resources on a server machine. So servlets are trusted.
5. 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 that you have seen already.
SERVLET TYPES-
• Generic Servlets: These are those servlets that Every servlet should override the following 3 methods namely:
provide functionality for implementing a 1.init(): To initalize/instantiate the servlet container.
servlet. It is a generic class from which all the 2.service(): This method acts like an intermediatory between the HTTP request and the business
customizable servlets are derived. It is logic to serve that particular request.
protocol-independent and provides support for 3.destroy(): This method is used to deallocate the memory allocated to the servlet.
HTTP, FTP, and SMTP protocols. The class
used is ‘javax.servlet.Servlet’ and it only has 2 These methods are used to process the request from the user.
methods – init() to initialize & allocate memory
to the servlet and destroy() to deallocate the JAVA SERVLET FEATURES
servlet.
The Java Servlets carry over the features of Java Programming Language. The key features offered by the Java
• HTTP Servlets: These are protocol dependent Servlets are as follows.
servlets, that provides support for HTTP
request and response. It is typically used to 1. Portable - Servlets feature the same Portable nature as the Java Programming Language. The Servlet program
create web apps. And has two of the most used designed in one Operating System's Platform can be run in a different Operating System Platform with ease.
methods – doGET() and doPOST() each
serving their own purpose. 2. Efficient - The Java Servlet, by its nature, provides an instantaneous response to the client's request. Also, it can
be portable and perform in every environmental condition regardless of the operating system platform.
There are three potential ways in which we can
employ to create a servlet: 3. Scalable- Java Servlets are highly scalable. Servlets use completely lightweight threads for the processes and can
simultaneously handle multiple client requests by generating various threads.
1. Implementing Servlet Interface
4. Robust-The Java Servlets are best known for their robust operating procedures. The servlets extend the features
2. Extending Generic Servlet of Java, which include.

3. Extending HTTP Servlet  Java Security Manager


 Java Garbage Collector
 Exception Handling.
Implementation of these advanced features makes Java Servlets resilient to any security threats to a decent extent.
Also, the garbage collector takes care of memory management and eliminates the issues related to memory management
in real-time, leaving Servlets to be Robust.
1. Client
The client shown in the architecture above is the web browser and it primarily works as
a medium that sends out HTTP requests over to the web server and the web server
generates a response based on some processing in the servlet and the client further
processes the response.
2. Web Server
Primary job of a web server is to process the requests and responses that a user sends
over time and maintain how a web user would be able to access the files that has been
hosted over the server. The server we are talking about here is a software which manages
access to a centralized resource or service in a network. There are precisely two types of
webservers: Following are the steps in which a request flows through a servlet which can be observed in the
•Static web server
architecture diagram:
•Dynamic web server
•The client sends over a request.
3. Web Container
Web container is another typical component in servlet architecture which is responsible •The request is accepted by the web server and forwarded to the web container.
for communicating with the servlets. Two prime tasks of a web container are: •In order to obtain the servlet’s address, the web container traces web.xml file corresponding to
• Managing the servlet lifecycle the request URL pattern.
• URL mapping •By the time above process takes place, the servlet should have been instantiated and initialized.
Web container sits at the server-side managing and handling all the requests that are The init() method is invoked to initialize the servlet.
coming in either from the servlets or from some JSP pages or potentially any other file •By passing ServletRequest and Response object, public service() method is called by the
system. container.
•In the next step, the ServletRequest and ServletResponse objects are type casted
to HttpServletRequest and HttpServletResponse objects by the public service() method.
•Now protected service() method is called by the public service() method.
•The protected service() method dispatches the request to the correct handler method based on
the type of request.
•When servlet container shuts down, it unloads all the servlets and calls destroy() method for
each initialized servlet.
Servlet Life Cycle 1) Servlet class is loaded

The classloader is responsible to load the servlet class. The servlet class is loaded when the first request
The web container maintains the life cycle of a servlet
for the servlet is received by the web container.
instance.
Let's see the life cycle of the servlet: 2) Servlet instance is created
1.Servlet class is loaded.
The web container creates the instance of a servlet after loading the servlet class. The servlet instance is
2.Servlet instance is created.
created only once in the servlet life cycle.
3.init method is invoked.
4.service method is invoked. 3) init method is invoked
5.destroy method is invoked.
The web container calls the init method only once after creating the servlet instance. The init method is
used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of
the init method is given below:

public void init(ServletConfig config) throws ServletException

4) service method is invoked

The web container calls the service method each time when request for the servlet is received. If servlet
is not initialized, it follows the first three steps as described above then calls the service method. If
servlet is initialized, it calls the service method. Notice that servlet is initialized only once. The syntax of
the service method of the Servlet interface is given below:

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException


As displayed in the above diagram, there are three states of a 5) destroy method is invoked
servlet: new, ready and end. The servlet is in new state if servlet
instance is created. After invoking the init() method, Servlet The web container calls the destroy method before removing the servlet instance from the service. It
comes in the ready state. In the ready state, servlet performs all gives the servlet an opportunity to clean up any resource for example memory, thread etc. The syntax of
the tasks. When the web container invokes the destroy() the destroy method of the Servlet interface is given below:
method, it shifts to the end state.
public void destroy()
Java Servlet Request
The Java Servlets operate in the form of Requests and Responses. The first phase is the Java Servlet Response
request from the user's end. The HttpRequest object represents the HTTP request to a
browser that the user sends to the web application. Thus, anything the browser sends is The second important part is the Response phase. The HttpResponse object is used to
accessible through the HttpRequest. represent the HTTP response to your request. A web application sends back a
response page to the user to respond to the HTTP request from the browser sent to
Now, we will learn about the various segments of a request received by the Servlet. your web application.
1. HTTP Request Header Let us now understand the parts of the Response Phase in the Java Servlets as
The request headers are key-value pairs sent as a request by the browser, along with the follows.
HTTP request. The request headers contain information about what browser software is 1. HTTP Response Header
being used, what file types the browser can receive.
Similar to HTTP Request, the HTTP response includes headers. These are responsible
2. HTTP Request Parameters for all the data written in the response.
Along with the request, the browser shares a few parameters related to the information 2. HTTP Response Content Type
required. Request parameters are technically a crucial part of the URL of an HTTP
request. The Content-Type header tells the browser about the type of content you are sending
in return.
3. HTTP Request InputStream
3. HTTP Response Content-Length
HTTP Request InputStream is an ordered stream of input data. The HTTP Request
InputStream extends the java.io.InputStream library. The Content-Length header tells you about the number of bytes your Servlet is
sending in return.
4. HTTP Request Context
4. HTTP Response Write HTML
We dedicate the HTTP Request Context to storing the metadata related to the
application. To send the HTML back to the browser, you need to retrieve the PrintWriter from the
HTTP response object.
5. HTTP Request Session
5. HTTP Response Redirection
The session object holds information about a specific user in between multiple requests.
In case you set a new object during the session object request, the object will get Redirecting will help you turn yourself to a different webpage from the current one.
available for you to access during any subsequent requests within the same session time
scope.
SERVLET ARCHITECTURE

To write a Servlet, the user needs first to implement the Servlet Interface, directly
or indirectly, using the following import command.
import javax.servlet.*;
Once the Servlet interface is imported, and we inherit the HTTP Class, we begin
with the Java Servlet's life cycle.
In the life cycle of a servlet, we have mainly three stages, which are mentioned
below.
•init()
•service()
•destroy()
We call these methods at their respective stages. The methods are resolved by
generating the essential threads for the process to get executed.
1. init() 3. destroy()
The init() is the germinating stage of any Java Servlet. When a URL Like the init() method, the destroy() method is also called only once in the Java Servlet's
specific to a particular servlet is triggered, the init() method is invoked. entire life cycle.
Another scenario when the init() method gets invoked is when the servers
are fired up. With every server starting up, the corresponding servlets When the destroy() method is called, the Servlet performs the cleanup activities like,
also get started, and so does the init() method.
One important specialty of the init() method is the init() method only gets Halting the current or background threads
invoked once in the entire life cycle of the Servlet, and the init() method Making a recovery list of any related data like cookies to Disk.
will not respond to any of the user's commands. After that, the Servlet is badged, ready for the Garbage collector to have it cleared.
The init() method Syntax:
public void init() throws ServletException { The destroy() method Syntax:
//init() method initializing
} public void destroy() {
2. service()
The service() method is the heart of the life cycle of a Java Servlet. Right //destroy() method finalizing
after the Servlet's initialization, it encounters the service requests from
the client end. }
The client may request various services like:
•GET
•PUT
•UPDATE
•DELETE
The service() method takes responsibility to check the type of request
received from the client and respond accordingly by generating a new
thread or a set of threads per the requirement and implementing the
operation through the following methods.
•doGet() for GET
•doPut() for PUT
•doUpdate() for UPDATE
•doDelete() for DELETE
The service() method Syntax:
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
}

You might also like