0% found this document useful (0 votes)
31 views40 pages

Servlet: Design By: Er. Harman S. Gahir (AP) Chandigarh University-Gharuan

Uploaded by

Why soo serious
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views40 pages

Servlet: Design By: Er. Harman S. Gahir (AP) Chandigarh University-Gharuan

Uploaded by

Why soo serious
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

SERVLET

Design By:
Er. Harman S. Gahir(AP)
Chandigarh University-Gharuan

28-01-2019 1
Web Server
• A computer having server software installed within it which serves up web
pages.
• A program that uses client/ server model and World Wide Web’s Hypertext
Transfer Protocol (HTTP).
• Responsible for accepting HTTP requests from clients (web browsers) and
serving HTTP responses which are web pages such as HTML documents.

28-01-2019 2
Web Server
• Popular web servers:
Apache HTTP Server (Apache)
Microsoft Internet Information Server (IIS)
Sun Java System Web Server

28-01-2019 3
Web Application
• A web application is an application accessible from the web.
• A web application is composed of web components like
• Servlet,
• JSP,
• Filter, etc.
• and other elements such as
• HTML,
• CSS,
• and JavaScript.
• The web components typically execute in Web Server and respond to the HTTP
request.

28-01-2019 4
Common Gateway Interface

CGI technology enables the web server to call an external program and pass HTTP request information to
the external program to process the request. For each request, it starts a new process.

1.If number of clients increases, it takes more time for


sending response.

2.For each request, it starts a process and Web server is


limited to start processes.

3.It uses platform dependent language e.g. C, C++,


perl.

28-01-2019 5
Servlet

• The web container creates threads for


handling the multiple requests to the servlet.

• Threads have a lot of benefits over the


Processes such as they share a common
memory area, lightweight, cost of
communication between the threads are low. 

28-01-2019 6
Servlets
• Servlet technology is used to create web application (resides at server side and generates
dynamic web page).
• middle layer between a requests coming from a Web browser or other HTTP client and
databases or applications on the HTTP server
• Servlet is an API that provides many interfaces and classes including documentations.
• Servlet is an interface that must be implemented for creating any servlet.
• Servlet is a class that extend the capabilities of the servers and respond to the incoming
request. It can respond to any type of requests.
• Servlet is a web component that is deployed on the server to create dynamic web page.
• It extends the functionality of a web server by receiving client requests and dynamically
generating a response.
• platform independent.

28-01-2019 7
Servlets

28-01-2019 8
Servlets

28-01-2019 9
Servlets

28-01-2019 10
Servlets

28-01-2019 11
Servlets Process
•Read the explicit data sent by the clients (browsers). This includes an HTML form on a
Web page or it could also come from an applet or a custom HTTP client program.

•Read the implicit HTTP request data sent by the clients (browsers). This includes
cookies, media types and compression schemes the browser understands, and so forth.

•Process the data and generate the results. This process may require talking to a
database, executing an RMI or CORBA call, invoking a Web service, or computing the
response directly.

28-01-2019 12
Servlets Process

•Send the explicit data (i.e., the document) to the clients (browsers). This document can
be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel,
etc.

•Send the implicit HTTP response to the clients (browsers). This includes telling the
browsers or other clients what type of document is being returned (e.g., HTML), setting
cookies and caching parameters, and other such tasks.

28-01-2019 13
Web Component
A web component is a software entity that runs on a web server required for
dynamically handling client requests and generating web presentation
content.

The J2EE specification defines two types of web components


• Servlets
• Java Server Pages(JSPs)

28-01-2019 14
Uses Of Servlets
• Processing and/or storing data submitted by an HTML form
Example: Processing data of a login form.
• Providing dynamic content
Example: Returning results of a database query to the client.
• Managing state information on top of the stateless HTTP
Example: For an online shopping cart system which manages shopping
carts for many concurrent customers and maps every request to the right
customer.

28-01-2019 15
Servlet Architecture
Java Servlet API are in packages
javax.servlet and javax.servlet.http Servlet Interface
Provide interfaces and classes
for writing servlets
All servlets must implement Servlet
GenericServlet Class
interface
Defines life-cycle methods
Extend GenericServlet class HttpServlet Class
To implement generic services
Extend HttpServlet class
To implement HTTP-specific services XYZ Servlet(a user-defined Servlet)
28-01-2019 16
Web Container
Web components and their container run on J2EE server.

• Provides execution environment for servlets of a web application.

• Manages execution of servlet components for J2EE applications

28-01-2019 17
Role Of Web Container
Communication Support
Provides an easy way for servlets to talk to web server.

Lifecycle Management
Controls lifecycle of servlets.

Multithreading Support
Automatically creates a new Java thread for every servlet request it receives.

28-01-2019 18
Role Of Web Container
Declarative Security
Enables to configure security in an XML deployment descriptor thereby
avoiding hard-coding it in servlet or any other class code.

JSP Support
Does JSP processing

28-01-2019 19
Web Container handles Servlet Request

• Container creates 2 objects on receiving a request for a servlet:


HttpServletRequest and HttpServletResponse
• Finds right servlet based on URL in the request.
• Creates a thread for that request.
• Passes request and response objects to the servlet thread.
• Calls servlet’s service() method
• The service() method in turn calls doGet or doPost based on type of request .
• The doGet method generates dynamic page and captures it in response object.

28-01-2019 20
Web Container handles Servlet Request

• Converts response object into an HTTP response on completion of thread.


• Sends this response to the client.
• Finally deletes the request and response objects.

28-01-2019 21
Servlet Interface
It Provides methods that manage the servlet and its communications with
clients.

init(ServletConfig)
Initializes the servlet. Runs once before any requests can be serviced.

service(ServletRequest, ServletResponse)
Processes a single request from the client.

28-01-2019 22
Servlet Interface
destroy()
This method releases all the resources.

getServletConfig()
Returns a servlet config object and this object contains any initialization parameters
and startup configuration information for this servlet.

getServletInfo()
Returns a string containing information about the servlet, such as its author,
version, and copyright.
28-01-2019 23
Servlet Life Cycle
The web container maintains the life cycle of a servlet instance.
• Servlet class is loaded.
• Servlet instance is created.
• init method is invoked.
• service method is invoked.
• destroy method is invoked.

28-01-2019 24
Servlet Life Cycle

http://www.javatpoint.com/life-cycle-of-a-
servlet
28-01-2019 25
Life Cycle Methods
Interaction between a web server, a servlet, and a client is controlled using the
life-cycle methods.
A servlet's life cycle methods are
init()
service()
destroy()
• The init() and destroy() methods will be called only once during the life time
of your Servlet.
• The service() and it's broken down methods ( doGet(),doPost() etc ) will be
called as many times as requests are received for them by the web container.
28-01-2019 26
doGet() & doPost() Method
Methods doGet() and doPost() in HttpServlet class receives appropriate client request,
and formats a response using 2 arguments
• An HttpServletRequest object - receive data from the client .
• An HttpServletResponse object – send response to the client.
Syntax:
public void doPost(HttpServletRequest req,
HttpServletResponse res) throws IOException,
ServletExceptions
public void doGet(HttpServletRequest req,
HttpServletResponse res)throws IOException,
ServletException

28-01-2019 27
HttpServletRequest interface

HttpServletRequest Interface
• The HttpServletRequest object provides communication between client &
servlet.
• Provides methods that allow you to retrieve incoming information.
eg: HTTP request headers, form data, or a client's hostname
• Methods to read parameters from a form
getParameter(String pname)
getParameterNames()
getParameterValues(String pname)
28-01-2019 28
HttpServletResponse interface

HttpServletResponse Interface
• The HttpServletResponse object provide any kind of communication from servlet
to client.
• Allows you to specify outgoing information.
• Also enables you to obtain a PrintWriter object for writing output back to the
client.
• Methods:
getWriter()
setContentType()
sendRedirect()
28-01-2019 29
Session Tracking
• Http is a stateless protocol.
• Many applications require a series of requests from a same client to be associated with
one another.
• A mechanism is needed to maintain state across a series of requests from the same user
(or coming from the same browser)over some period of time.
Example: Online shopping cart
• Session tracking is keeping track of what has gone before in a particular
conversation.
• Since HTTP is stateless, it does not do this for you. You have to do it yourself, in
your servlets.

28-01-2019 30
Session Tracking Mechanism

There are different session tracking mechanisms of passing “session id”.

• Cookies
You can use a single cookie containing a session id

• Http Session
Container creates a session id for each user.

28-01-2019 31
Cookies
A cookie is a small bit of textual information sent to the client by a web
server and web server can later read it back from the browser.

The process of using cookies in servlets


• Servlet sends a cookie with its response to the client.
• The client saves the cookie.
• The client returns a cookie back with subsequent requests.

28-01-2019 32
Cookies
Uses of cookies
• Identifying a user during an e-commerce session.
• Avoiding username and password.
• Customizing a website.

Limitations of cookies
• A Cookie size is limited to 4KB.
• Supports 20 cookies per website.
• Supports 300 cookies in total.
28-01-2019 33
Cookies
Creating cookies
Use a constructor --- Cookie (String name, String value)
Adding cookies to a response
response.addCookie (cookie1)
Retrieving cookies from a request
request.getCookies() //returns array of Cookie or null
For example:
Cookie[ ] cookies = request.getCookies();
String name = cookies[i].getName();
String value = cookies[i].getValue();

28-01-2019 34
Cookies For Session Handling

An example of using cookies to perform session handling.


• Every time the servlet SessionCookieServlet services a request, it first checks
for cookies in HttpServletRequest by calling request.getCookies().
• If request contain cookies, the servlet will iterate over the list of cookies
looking for a cookie with the name session_id.
• If request contain no cookies or list of cookies has no cookie named session_id,
create one and add it to response.
• The code fragment for this is:
Cookie c = new Cookie("session_id", "abc123");
response.addCookie(c);
28-01-2019 35
Session Tracking Using HttpSession

It is built on top of cookies and URL rewriting.


Servlet container creates HttpSession object.
Attached to HttpServletRequest object in doXXXX methods
Contains Methods to
• View and manipulate information about a session, such as session
identifier, creation time, and last accessed time.
• Bind objects to sessions, allowing user information to persist across
multiple user connections.

28-01-2019 36
HttpSession
Create a session
HttpSession session = request.getSession();
Returns session associated with this request.
If there was no associated session, new one is created.
We can also get an HttpSession object by using following method :
HttpSession session = request.getSession(true);
getSession(true) works exactly like getSession().
HttpSession session = request.getSession(false);
This method returns session associated with this request.
If there was no associated session, new one is NOT created.
28-01-2019 37
HttpSession Methods
Store and retrieve user-defined data in the session
To store values:
session.setAttribute(name, value);
To retrieve values:
Object obj = session.getAttribute(name);
boolean session.isNew()
Determines if session is new to client .
public void invalidate()
Expires the session and unbinds all objects with it.
28-01-2019 38
Frequently Asked Questions
• How to notify an object in session when session is invalidated or timed-
out?
• How does Cookies work in Servlets?
• How can you get the information about one servlet context in another
servlet? 
• How can we invoke another servlet in a different application?
• Are Servlets Thread Safe?

28-01-2019 39
Bibliography
• javatpoint.com
• tutorialspoint.com
• Thinking in java by Bruce Eckel
• Head first Java on Servlet & JSP by Kathy Sierra

28-01-2019 40

You might also like