SERVLETS

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

SERVLETS

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.
Properties of Servlets are as follows:
• Servlets work on the server-side.
• Servlets are capable of handling complex requests obtained from the
webserver.

Execution of Servlets basically involves six basic steps:


1. The clients send the request to the webserver.
2. The web server receives the request.
3. The web server passes the request to the corresponding servlet.
4. The servlet processes the request and generates the response in the form of
output.
5. The servlet sends the response back to the webserver.
6. The web server sends the response back to the client and the client browser
displays it on the screen.
The server-side extensions are nothing but the technologies that are used to create
dynamic Web pages.
APIs(Application Programming Interface).
These APIs allow us to build programs that can run with a Web server. In this case,
Java Servlet is also one of the component APIs of Java Platform Enterprise Edition
which sets standards for creating dynamic Web applications in Java.
Advantages of a Java Servlet
Servlet is faster than CGI as it doesn’t involve the creation of a new process for
every new request received.
Servlets, as written in Java, are platform-independent.
Removes the overhead of creating a new process for each request as Servlet
doesn’t run in a separate process. There is only a single instance that handles all
requests concurrently. This also saves the memory and allows a Servlet to easily
manage the client state.
It is a server-side component, so Servlet inherits the security provided by the Web
server.
The API designed for Java Servlet automatically acquires the advantages of the
Java platforms such as platform-independent and portability

Life Cycle of a Servlet (Servlet Life Cycle)


The web container maintains the life cycle of a servlet instance. Let's see the life
cycle of the servlet:

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.
1) Servlet class is loaded
The classloader is responsible to load the servlet class. The servlet class is loaded
when the first request for the servlet is received by the web container.

2) Servlet instance is created


The web container creates the instance of a servlet after loading the servlet class.
The servlet instance is created only once in the servlet life cycle.

3) init 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:

1. 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:
1. public void service(ServletRequest request, ServletResponse response)
2. throws ServletException, IOException

5) destroy method is invoked


The web container calls the destroy method before removing the servlet instance
from the service. It gives the servlet an opportunity to clean up any resource for
example memory, thread etc. The syntax of the destroy method of the Servlet
interface is given below:

1. public void destroy()


HTTP Methods
For HTTP/1.1, the set of common methods are defined below. This set can be
expanded based on the requirements. The name of these methods is case sensitive,
and they must be used in uppercase.

Method and Description


i) GET
This method retrieves information from the given server using a given URI. GET
request can retrieve the data. It can not apply other effects on the data.
GET /hello.htm HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.Medi-Caps.com
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: Keep-Alive

ii) HEAD
This method is the same as the GET method. It is used to transfer the status line and
header section only.
HEAD /hello.htm HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.Medi-Caps.com
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: Keep-Alive

iii) POST
The POST request sends the data to the server. For example, file upload, customer
information, etc. using the HTML forms.
• send a form data to the server, which will be processed by a process.cgi and
finally a response will be returned:
POST /cgi-bin/process.cgi HTTP/1.1
iv) PUT
The PUT method is used to replace all the current representations of the target
resource with the uploaded content.
• requests the server to save the given entity-body in hello.htm at the root of
the server:
• PUT /hello.htm HTTP/1.1

v) DELETE
The DELETE method is used to remove all the current representations of the target
resource, which is given by URI.
• requests the server to delete the given file hello.htm at the root of the server:
DELETE /hello.htm HTTP/1.1
vi) CONNECT
The CONNECT method is used by the client to establish a network connection to a
web server over HTTP.
CONNECT www.Medi-Caps.com HTTP/1.1 User-Agent:Mozilla/4.0 (compatible;
MSIE5.01; Windows NT)
vii) OPTIONS
This method describes the options of communication for the target resource.
MVC
The Model-View-Controller (MVC) is a well-known design pattern in the web
development field. It is way to organize our code. It specifies that a program or
application shall consist of data model, presentation information and control
information.

The MVC pattern architecture consists of three layers:

o Model: It represents the business layer of application. It is an object to carry


the data that can also contain the logic to update controller if data is changed.
o View: It represents the presentation layer of application. It is used to visualize
the data that the model contains.
o Controller: It works on both the model and view. It is used to manage the flow
of application, i.e. data flow in the model object and to update the view
whenever data is changed.

In Java Programming, the Model contains the simple Java classes, the View used to
display the data and the Controller contains the servlets. Due to this separation the
user requests are processed as follows:

1. A client (browser) sends a request to the controller on the server side, for a page.
2. The controller then calls the model. It gathers the requested data.
3. Then the controller transfers the data retrieved to the view layer.
4. Now the result is sent back to the browser (client) by the view.

Advantages of MVC Architecture


The advantages of MVC architecture are as follows:

o MVC has the feature of scalability that in turn helps the growth of application.
o The components are easy to maintain because there is less dependency.
o A model can be reused by multiple views that provides reusability of code.
o The developers can work with the three layers (Model, View, and Controller) simultaneously.
o Using MVC, the application becomes more understandable.
o Using MVC, each layer is maintained separately therefore we do not require to deal with
massive code.
o The extending and testing of application is easier.

Init parameter
init parameters refers to the initialization parameters of a servlet or filter.
<init-param> attribute is used to define a init parameter. <init-param>
attribute has two main sub attributes <param-name> and <param-value>. The
<param-name> contains the name of the parameter and <param-value>
contains the value of the parameter. ServletConfig interface is used to access
the init parameters.

ServletContext Interface
An object of ServletContext is created by the web container at time of deploying the
project. This object can be used to get configuration information from web.xml file.
There is only one ServletContext object per web application.
If any information is shared to many servlet, it is better to provide it from the web.xml
file using the <context-param> element.

Advantage of ServletContext
Easy to maintain if any information is shared to all the servlet, it is better to make it
available for all the servlet. We provide this information from the web.xml file, so if
the information is changed, we don't need to modify the servlet. Thus it removes
maintenance problem.

Usage of ServletContext Interface


There can be a lot of usage of ServletContext object. Some of them are as follows:

1. The object of ServletContext provides an interface between the container and servlet.
2. The ServletContext object can be used to get configuration information from the web.xml
file.
3. The ServletContext object can be used to set, get or remove attribute from the web.xml file.
4. The ServletContext object can be used to provide inter-application communication.
Inter Servlet Communication
• A process where two or more servlets communicates with each other to
process the client request.
• A servlet can forward the request to another servlet to process the client
request.
• A servlet can include the output of another servlet to process the client
request.
Technique to do Inter-Servlet Communication
• Inter-servlet communication using Request Dispatcher
• A Request Dispatcher:
– Is an object of the javax.servlet.RequestDispatcher interface that allows
inter-servlet communication.
– Object is used to include the content of another servlet.
– Object is used to forward the request to another servlet.
• This interface is present in the javax.servlet package and contains only
following two methods :
– forward(ServletRequest request, ServletResponse response) Forwards
a request to another resource on the same server. That resource can be
a Servlet, JSP page or a simple HTML page.
– include(ServletRequest request, ServletResponse response) Works like
a server-side include ( SSI ) and includes the response from the given
resource ( Servlet, JSP page, HTML page ) within the caller response.

Servlet Listener
• A Servlet listener is a servlet method or function that awaits the occurrence
of an event.
• Servlet Listeners are classes that monitor a specific type of event and
activate functionality when that event happens.
• Servlet Listener works for listening to events in web containers like a
session is created, an attribute is inserted into a session, or a container is
activated.
• Servlet Listener is used for listening to events in web containers, such as
when you create a session, insert an attribute, passivate and activate in
another container. The servlet container generates events that trigger the
action of event listener classes.
There are total eight type of listeners available in servlet framework.
• ServletContextListener
• ServletContextAttributeListener
• HttpSessionListener
• HttpSessionAttributeListener
• ServletRequestListener
• ServletRequestAttributeListener
• HttpSessionActivationListener
• HttpSessionBindingListener

Servlet Filter
• A filter is an object that is invoked at the preprocessing and postprocessing
of a request on the server, i.e., before and after the execution of a servlet for
filtering the request. Filter API (or interface) includes some methods which
help us in filtering requests.
• To validate the data coming from the client because through the server the
data will be stored in the database. So, only valid data should enter the
database. Can we not do this validation (or add filters) on the client-side? We
can add filters on the client-side. But if javascript is disabled on the client-
side, then the request (or data) will not be checked. Someone might do this
intentionally. So to avoid this, we add Filters on the Server side.

You might also like