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

UNIT 3

SERVLETS
Introduction
• Servlets are the Java programs that run on the Java-enabled web
server or application server.
properties of Servlets
• Servlets work on the server side.
• Servlets are capable of handling complex requests obtained from the
web server.
Servlet Architecture
Life Cycle of a Servlet

• Servlet class is loaded.


• Servlet instance is created.
• init method is invoked.
• service method is invoked.
• destroy method is invoked.
Execution of Servlets

• The clients send the request to the webserver.


• The web server receives the request.
• The web server passes the request to the corresponding servlet.
• The servlet processes the request and generates the response in the
form of output.
• The servlet sends the response back to the webserver.
• The web server sends the response back to the client and the client
browser displays it on the screen.
CGI

• CGI is actually an external application that is written by using any of


the programming languages like C or C++ and this is responsible for
processing client requests and generating dynamic content.
• It first locates the requested web page i.e the required CGI application
using URL.
• It then creates a new process to service the client’s request.
• Invokes the CGI application within the process and passes the request
information to the application.
• Collects the response from the CGI application.
• Destroys the process, prepares the HTTP response, and sends it to the
client.
Difference between Servlet and CGI

Servlet CGI (Common Gateway Interface)

Servlets are portable and efficient. CGI is not portable.

In Servlets, sharing data is possible. In CGI, sharing data is not possible.

Servlets can directly communicate with the CGI cannot directly communicate with the
webserver. webserver.

Servlets are less expensive than CGI. CGI is more expensive than Servlets.

Servlets can handle the cookies. CGI cannot handle the cookies.
Servlets API’s:

• Servlets are built from two packages:


• javax.servlet(Basic)
• javax.servlet.http(Advance)
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.
• can use the wide range of APIs created on Java platforms such as JDBC to access the database.
• Many Web servers that are suitable for personal use or low-traffic websites are offered for free
or at extremely cheap costs eg. Java servlet. However, the majority of commercial-grade Web
servers are rather expensive, with the notable exception of Apache, which is free.
Servlet Container

• Servlet container, also known as Servlet engine, is an integrated set


of objects that provide a run time environment for Java Servlet
components. In simple words, it is a system that manages Java Servlet
components on top of the Web server to handle the Web client
requests.
Services provided by the Servlet
container:
• Network Services: Loads a Servlet class. The loading may be from a local file
system, a remote file system or other network services. The Servlet container
provides the network services over which the request and response are sent.
• Decode and Encode MIME-based messages: Provides the service of decoding
and encoding MIME-based messages.
• Manage Servlet container: Manages the lifecycle of a Servlet.
• Resource management Manages the static and dynamic resources, such as
HTML files, Servlets, and JSP pages.
• Security Service: Handles authorization and authentication of resource access.
• Session Management: Maintains a session by appending a session ID to the
URL path.
The service() Method
• The service() method is the main method to perform the actual task.
The servlet container (i.e. web server) calls the service() method to
handle requests coming from the client( browsers) and to write the
formatted response back to the client.
• Each time the server receives a request for a servlet, the server issues
a new thread and calls service. The service() method checks the HTTP
request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost,
doPut, doDelete, etc. methods as appropriate.
doGet and doPost in Servlets
• doGet and doPost are methods of the
javax.servlet.http.HttpServlet class that are used to handle
HTTP GET and POST requests, respectively.
• The doGet method is called by the server (via the service
method) when the client requests a GET request. It is used to
retrieve information from the server.
• The doPost method is called by the server (via the service
method) when the client requests a POST request. It is used
to send information to the server.
doGet
• The doGet() method in servlets is used to process the HTTP GET
requests.
• HTTP GET method should be used to get the data from the server to
the browser.
• Although in some requests, the GET method is used to send data from
the browser to the server also.
• The data that is being submitted to the server will be visible in the URL
• So, if you are sending any sensitive information like passwords, you
should not use the GET method as the data entered can be clearly
visible in the browser URL.
doPost
• used to process the HTTP POST requests.
• It is used to submit the data from the browser to the server
for processing.
• The data submitted with POST method type is sent in the
message body so it is secure and cannot be seen in the URL.
• And there is no limit on the data that can be sent through
the POST method.
• Ideally, we need to use the POST method, to send the form
data to the webserver.
Attribute in Servlet
• An attribute in servlet is an object that can be set, get or removed from one of the
following scopes:
• request scope
• session scope
• application scope
• The servlet programmer can pass informations from one servlet to another using
attributes. It is just like passing object from one class to another so that we can reuse
the same object again and again.
• public void setAttribute(String name,Object object):sets the given object in the
application scope.
• public Object getAttribute(String name):Returns the attribute for the specified name.
RequestDispatcher in Servlet
• The RequestDispatcher interface provides the facility of forwarding the request
to another resource it may be html, servlet or jsp. This interface can also be used
to include the content of another resource also. It is one of the way of servlet
collaboration.
• public void forward(ServletRequest request,ServletResponse response)throws
ServletException,java.io.IOException:Forwards a request from a servlet to
another resource (servlet, JSP file, or HTML file) on the server.
• The include() method is used to include the content of another servlet, JSP page,
HTML file in the servlet response. After calling this method, the response of
another resource is included in the called resource.
• public void include(ServletRequest request, ServletResponse response) throws
ServletException, java.io.IOException
Servlet – Session Tracking
• HTTP is a “stateless” protocol, which means that each time a client requests
a Web page, the client establishes a new connection with the Web server,
and the server does not retain track of prior requests.
• The conversion of a user over a period of time is referred to as a session. In
general, it refers to a certain period of time.
• The recording of the object in session is known as tracking.
• Session tracking is the process of remembering and documenting customer
conversions over time. Session management is another name for it.
• The term “stateful web application” refers to a web application that is
capable of remembering and recording client conversions over time.
Why is Session Tracking Required?
• Because the HTTP protocol is stateless, we require Session Tracking to
make the client-server relationship stateful.
• Session tracking is important for tracking conversions in online
shopping, mailing applications, and E-Commerce applications.
Session Tracking employs Four Different
techniques
• Cookies
• Hidden Form Field
• URL Rewriting
• HttpSession
Servlet – Cookies
• Cookies are the textual information that is stored in key-value pair format to
the client’s browser during multiple requests.
• It is one of the state management techniques in session tracking.
• Basically, the server treats every client request as a new one so to avoid this
situation cookies are used.
• When the client generates a request, the server gives the response with
cookies having an id which are then stored in the client’s browser.
• Thus if the client generates a second request, a cookie with the matched id is
also sent to the server.
• The server will fetch the cookie id, if found it will treat it as an old request
otherwise the request is considered new.
Using Cookies in Java
• In order to use cookies in java, use a Cookie class that is present
in javax.servlet.http package.
• To make a cookie, create an object of Cookie class and pass a name
and its value.
• To add cookie in response, use addCookie(Cookie) method of
HttpServletResponse interface.
• To fetch the cookie, getCookies() method of Request Interface is used.
Hidden Form Field
• The information is inserted into the web pages via the hidden form
field, which is then transferred to the server. (invisible)
• These fields are hidden from the user’s view.

• Illustration:

• <input type = ‘hidden' name = ‘user' value = ‘abcdef' >


URL Rewriting
• With each request and return, append some more data via URL as request
parameters.
• URL rewriting is a better technique to keep session management and
browser operations in sync.
• Advantage of URL Rewriting
• It will always work whether cookie is disabled or not (browser independent).
• Extra form submission is not required on each pages.
• Disadvantage of URL Rewriting
• It will work only with links.
• It can send Only textual information.
HttpSession
• A user session is represented by the HttpSession object. A session is
established between an HTTP client and an HTTP server using the
HttpSession interface.
• A user session is a collection of data about a user that extents many
HTTP requests.
• An object of HttpSession can be used to perform two tasks:
• bind objects
• view and manipulate information about a session, such as the session
identifier, creation time, and last accessed time.
Concurrency in Servlets
• A Java servlet container or web server is multithreaded and multiple
requests to the same servlet may be executed at the same time.
Therefore, we need to take concurrency into consideration while writing
servlet.
• one and only one instance of Servlet gets created and for every new
request , Servlet Container issue a new thread to execute doGet() or
doPost() method of a servlet.
• By default servlets are not thread safe and it is a responsibility of a
servlet developer to take care of it.
Threads Overview
• A thread is a lightweight process which has its own call stack and
accesses shared data of other threads in the same process (shares
heap memory). Every thread has its own memory cache.
• When we say that a program is multithreaded, we mean that same
instance of an object issues multiple threads and process this single
instance of code. This means that more than one sequential flow of
control runs through the same memory block. So multiple threads
execute a single instance of a program and therefore shares instance
variables and could possibly be attempting to read and write those
shared variable.
Write Thread Safe Servlets
• Service() , doGet(), doPost() methods should not update or modify instance
variables as instance variables are shared by all threads of same instance.
• If you have a requirement which requires modification of instance variable
then do it in a synchronized block.
• Above two rules are applicable for static variables also because they are
also shared.
• Local variables are always thread safe.
• The request and response objects are thread safe to use because new
instance of these are created for every request into your servlet, and thus
for every thread executing in your servlet.
two approaches to make the thread safe
• Synchronized the block where you are modifying instance or static
variables.
• We recommend to synchronize the block where your code modifies the
instance variables instead of synchronizing complete method for the sake
of performance.
• Note that we need to take a lock on servlet instance as we need to make
the particular servlet instance as thread safe.
• Single Thread Model –Implements SingleThreadModel interface to make
our thread single threaded which means only one thread will execute
service() method at a time. A single-threaded servlet is slower under load
because new requests must wait for a free instance in order to proceed
When servlet is thread safe
• If your servlet does not have any static then no need to worry and
your servlet is thread safe
• If your servlet just reads the instance variable then your servlet is
thread safe.
• If you need to modify the instance or static variables , update it in a
synchronized block while holding a lock on Servlet instance

You might also like