Servlet: Design By: Er. Harman S. Gahir (AP) Chandigarh University-Gharuan
Servlet: Design By: Er. Harman S. Gahir (AP) Chandigarh University-Gharuan
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.
28-01-2019 5
Servlet
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.
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.
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
28-01-2019 20
Web Container handles Servlet Request
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
• 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.
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
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