Upload
jajupreetam
View
216
Download
0
Embed Size (px)
Citation preview
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 1/73
www.interviewDuniya.com
Fast Track Revision onFast Track Revision on
ServletServlet Introduction & Life CycleIntroduction & Life Cycle
Designed By:Designed By:
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 2/73
www.interviewDuniya.com
Prerequisitesrerequisites
For this section you are expected toFor this section you are expected toknow Java programming including:know Java programming including:
while while andand for for loops (vital)loops (vital)
if if (vital)(vital) Passing parameters to methods (vital)Passing parameters to methods (vital)
Arrays and Strings (important)Arrays and Strings (important)
TheThe Enumeration Enumeration class (important)class (important)
Threads andThreads and synchronized synchronized (useful)(useful)
ExceptionsExceptions try try andand catch catch (useful)(useful)
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 3/73
www.interviewDuniya.com
Serving Static HTMLerving Static HTML Web servers where designed to provideWeb servers where designed to provide
web browsers with HTML.web browsers with HTML. The HTML was read from text files byThe HTML was read from text files by
the server and sent to the client usingthe server and sent to the client using
HTTP. The web server does not modifyHTTP. The web server does not modify
the HTML. This is now termedthe HTML. This is now termed statictatic
HTML servingTML serving
ClientMachine
Server Machine
Web Browser
WebServer
HTML doGet or doPost
HTML
HTMLWeb Pageon disk
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 4/73www.interviewDuniya.com
Static HTML the Problemtatic HTML the Problem•Modern uses of web pages often require pages to bedynamically generated.
•For example a chat system would display any newmessages each time you hit refresh. This requiresthe web page the browser requests to be modified
each time someone adds a new message.•Until recently there was no easy way to do thisbecause
•web browsers were not designed to rewrite webpages
•web browsers are stateless so they process each
request in isolation without reference or memoryof what request came before it.
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 5/73
www.interviewDuniya.com
A Servlet does not run in a separate process.This removes the overhead of creating a newprocess for each request.
A Servlet stays in memory between requests. ACGI program (and probably also an extensiveruntime system or interpreter) needs to beloaded and started for each CGI request.
There is only a single instance which answers all There is only a single instance which answers allrequests concurrently. This saves memory and allows arequests concurrently. This saves memory and allows aServletServlet to easily manage persistent data.to easily manage persistent data.
A A ServletServlet can be run by acan be run by a ServletServlet Engine in a restrictiveEngine in a restrictiveSandboxSandbox (just like an Applet runs in a Web Browser's(just like an Applet runs in a Web Browser'sSandbox) which allows secure use of Sandbox) which allows secure use of untrusteduntrusted andandpotentially harmfulpotentially harmful ServletsServlets..
Browser 1
WebServer
Browser 2
Browser N
Perl 1
Perl 2
Perl N
Browser 1
WebServer
Browser 2
Browser N
Servlet
Whyhy servletservlets over CGIver CGI
script?cript?
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 6/73
www.interviewDuniya.com
What can you build with Servlets?
Search Engines
Personalization Systems
E-Commerce Applications
Shopping Carts
Product Catalogs
Intranet Applications
Groupware Applications: bulletin boards, filesharing, etc.
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 7/73
www.interviewDuniya.com
Servletservlets - a solution forsolution for
dynamically generatingynamically generatingHTMLTML
Servletservlets are programs written in Java which runare programs written in Java which runon the web server and communicate using withon the web server and communicate using withthe web browser using HTTP and HTMLthe web browser using HTTP and HTML
ServletsServlets are compatible withare compatible with allll web browsersweb browsers
becausebecause servletsservlets communicate with the browsercommunicate with the browserusingusing onlynly HTML and HTTPHTML and HTTP
ServletsServlets are simple to write because they areare simple to write because they arewritten in standard Javawritten in standard Java
Most of the communication is done for you byMost of the communication is done for you bythethe ServletServlet class. No need to mess around withclass. No need to mess around withSockets, TCP/IP or Java serialisation.Sockets, TCP/IP or Java serialisation.
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 8/73
www.interviewDuniya.com
What is a What is a ServletServlet
Java technology for Common Gateway Interface Java technology for Common Gateway Interface
(CGI)(CGI) ServletsServlets areare Java programs Java programs that serve as anthat serve as an
intermediating layer between an HTTP requestintermediating layer between an HTTP requestof a client and applications in the Web serverof a client and applications in the Web server
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 9/73
www.interviewDuniya.com
A A ServletServlet is a Java class that extends the web server'sis a Java class that extends the web server'sservice capabilities.service capabilities.
When the client sends a request to the server the. When the client sends a request to the server the.Server can forward the request to aServer can forward the request to a ServletServlet and let itand let it
handle the request.handle the request. ServletsServlets provide open, crossprovide open, cross--server and OS APIs.server and OS APIs.
ServletsServlets have a clean design; This leads to simplicity.have a clean design; This leads to simplicity.
ServletsServlets live inside alive inside a ServletServlet Container.Container.
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 10/73
www.interviewDuniya.com
What Is ahat Is a Servletervlet Containerontainer Sometimes called aSometimes called a ServletServlet Engine.Engine.
TheThe ServletServlet Container providesContainer provides ServletsServlets
with the environment, configurationwith the environment, configurationand runtime needed to support theand runtime needed to support theServletServlet APIs:APIs: Load theLoad the ServletsServlets..
Initialize theInitialize the ServletsServlets..
Execute theExecute the ServletsServlets.. Destroy theDestroy the ServletsServlets..
ServletsServlets do not have a maindo not have a main…… TheThecontainer have itcontainer have it……
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 11/73
www.interviewDuniya.com
A Java A Java ServletServlet
Sending a
request and
receiving a
response
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 12/73
www.interviewDuniya.com
Who Backs Who Backs ServletsServlets??
ServletsServlets are backed by "anybody but Microsoft."are backed by "anybody but Microsoft." There is There is ServletsServlets support for virtually all commonsupport for virtually all common
servers (including Microsoft's).servers (including Microsoft's).
Supporting Supporting ServletsServlets can be done in one of two ways:can be done in one of two ways:
Supporting theSupporting the ServletServlet APIs in the web APIs in the web--server levelserver level
Adding a Adding a
ServletServlet
--Container addContainer add
--on to the webon to the web
--server.server.
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 13/73
www.interviewDuniya.com
Function Cycle of aFunction Cycle of a ServletServlet
1.) A user clicks submit of a1.) A user clicks submit of a
formform using ausing a servletservlet
2.) The data in the form is sent2.) The data in the form is senttoto the serverthe server
3.) The server finds the3.) The server finds the
appropriateappropriate servletservlet
4.) The4.) The servletservlet creates thecreates theHTMLHTML page based on thepage based on the
useruser’ ’ ss supplied informationsupplied information
5.) The created HTML page is then transmitted back to the user5.) The created HTML page is then transmitted back to the user6.) The requested information is displayed in the user6.) The requested information is displayed in the user’ ’ s webs web
browserbrowser
S l if C l
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 14/73
www.interviewDuniya.com
Servlet Life Cycle
Loaded in memory of the web server
Servlet resides in memory until called by the server
Computes requested information
Returns to idle state in memory
Servlet is destroyed
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 15/73
www.interviewDuniya.com
The Basic Structure of an The Basic Structure of an HttpServletHttpServlet
There are several methods that you commonly There are several methods that you commonly
override when you write anoverride when you write an HttpServletHttpServlet. These. Thesemethods aremethods are
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 16/73
www.interviewDuniya.com
void init(ServletConfig sc) throws ServletException;
void service(HttpServletRequest request, HttpServletResponseresponse)
throws ServletException, IOException;
void doGet(HttpServletRequest request, HttpServletResponseresponse)
throws ServletException, IOException;
void doPost(HttpServletRequest request, HttpServletResponseresponse)
throws ServletException, IOException;
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 17/73
www.interviewDuniya.com
The The ServletServlet LifecycleLifecycle
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 18/73
www.interviewDuniya.com
The The ServletServlet lifelife--cycle defines:cycle defines:
How aHow a ServletServlet is initialized.is initialized. How aHow a ServletServlet is serving users and how many times.is serving users and how many times.
How aHow a ServletServlet is destroyed.is destroyed. Concurrency management (multiConcurrency management (multi--threading threading
considerations).considerations).
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 19/73
www.interviewDuniya.com
In brief In brief ……the sequence of events..the sequence of events..
The sequence of events starts with a browser sending a The sequence of events starts with a browser sending a requestrequestto a Web server.to a Web server.
The server hands the request to a The server hands the request to a ServletServlet ContainerContainer.. The container loads the The container loads the servletservlet (if it isn't already loaded),(if it isn't already loaded),
instantiates a request and response objects, and then hands thesinstantiates a request and response objects, and then hands thesee
objects to theobjects to the servletservlet by calling first itsby calling first its init() methodinit() method, then its, then itsservice() methodservice() method, and lastly the, and lastly the destroy() methoddestroy() method..
The service() method will typically call one of the The service() method will typically call one of the doXXX doXXX ()()methods such asmethods such as doGetdoGet().().
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 20/73
www.interviewDuniya.com
ServletServlet InstantiationInstantiation The container instantiates a new The container instantiates a new ServletServlet in twoin two
occasions:occasions: A user request service from a A user request service from a ServletServlet that was notthat was not
instantiated yet.instantiated yet.
The The ServletServlet is in the list of startupis in the list of startup ServletsServlets and theand thecontainer is starting.container is starting.
A A ServletServlet is instantiated in the following manner:is instantiated in the following manner: The container loads the The container loads the ServletServlet’’ss class.class.
Using Using Class.newInstanceClass.newInstance() the container instantiates a() the container instantiates anew instance of thenew instance of the ServletServlet..
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 21/73
www.interviewDuniya.com
Servletervlet Initializationnitialization After the instantiation, the containerAfter the instantiation, the container
initializes theinitializes the ServletServlet.. The container casts the new instance to aThe container casts the new instance to a
ServletServlet object and initializes it by calling anobject and initializes it by calling an
init() method.init() method. If initialization fail theIf initialization fail the ServletServlet creation fail andcreation fail and
the new instance is garbage collected.the new instance is garbage collected.
TheThe ServletServlet initialization is done in ainitialization is done in a
single threaded manner.single threaded manner.
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 22/73
www.interviewDuniya.com
Init()Init()
The init method is called when the The init method is called when the servletservlet is firstis first
created;created; init(ServletConfiginit(ServletConfig )) oror init()init()
it is not called again for each user request.it is not called again for each user request.
So, it is used for oneSo, it is used for one--time initializations, just as withtime initializations, just as with
the init method of applets.the init method of applets.
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 23/73
www.interviewDuniya.com
Init()Init() …… A code for initialization that is called only once (e.g., creati A code for initialization that is called only once (e.g., creating ng
the tables of the database)the tables of the database)
Initialization parameters are server specificInitialization parameters are server specific Many times these parameters are used to specify theMany times these parameters are used to specify the
maximum or minimum number for yourmaximum or minimum number for your ServletServlet..
For example, if you have a banking account, there is typically For example, if you have a banking account, there is typically a minimum amount required to maintain the account. Thea minimum amount required to maintain the account. The
initial parameter could be set to this minimum number andinitial parameter could be set to this minimum number and
then yourthen your ServletServlet could access it to check the object's valuecould access it to check the object's value
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 24/73
www.interviewDuniya.com
Service Phaseervice Phase After theAfter the ServletServlet initialization, the container can ask theinitialization, the container can ask the
ServletServlet to serve incoming requests.to serve incoming requests.
The container will call theThe container will call the ServletServlet’ ’ ss service() method.service() method.
AA ServletServlet may handle many concurrent requests.may handle many concurrent requests.
By different threads, all of them running in the sameBy different threads, all of them running in the sameservice methods.service methods.
The service method should be thread safe.The service method should be thread safe.
MultithreadingMultithreading
By default theBy default the servletservlet need to be multithread safe!need to be multithread safe!
One may instruct the container to make theOne may instruct the container to make the servletservlet
“ “multithread safemultithread safe” ” by insuring that no two thread willby insuring that no two thread will
execute on a singleexecute on a single servletservlet instanceinstance By making theBy making the ServletServlet class implement theclass implement the
SingleThreadModelSingleThreadModel interface (deprecated)interface (deprecated)
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 25/73
www.interviewDuniya.com
singlethreadmodelsinglethreadmodel
javax.servletjavax.servlet
When we implement When we implement singlethreadmodelsinglethreadmodel it meansit means
that only one thread can access the servicethat only one thread can access the servicemethod at a timemethod at a time
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 26/73
www.interviewDuniya.com
Http MethodsHttp Methods
when u click on Submit on your JSP page...you when u click on Submit on your JSP page...you
will be directed to the method either will be directed to the method either doGetdoGet() or() or doPostdoPost() in the() in the servletservlet
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 27/73
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 28/73
www.interviewDuniya.com
The main diff in these methods The main diff in these methods
When you select GET as method in your form the data you When you select GET as method in your form the data you
pass from that JSP, will be appended to the URL with your pass from that JSP, will be appended to the URL with your
servletservlet address.......address.......
where if you select POST then, any kind of data will not be where if you select POST then, any kind of data will not be
appended to the URL........it will be passedappended to the URL........it will be passed directly(butdirectly(but uu
can not see appended data on the URL)can not see appended data on the URL)
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 29/73
www.interviewDuniya.com
Other MethodsOther Methods
HEADHEAD: Client sees only header of response to: Client sees only header of response to
determine size, etcdetermine size, etc…… PUTPUT: Place documents directly on server: Place documents directly on server
DELETEDELETE: Opposite of PUT: Opposite of PUT TRACE TRACE: Debugging aid returns to client: Debugging aid returns to client
contents of its requestcontents of its request
OPTIONSOPTIONS: what options available on server: what options available on server
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 30/73
www.interviewDuniya.com
HttpServletHttpServlet Request HandlingRequest Handling
GET request
service()
HttpServlet subclass
response
doGet()
doPost()
Web
Server
POST request
response
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 31/73
www.interviewDuniya.com
DestroyingDestroying ServletsServlets
Destroying:Destroying:
destroy() is adestroy() is a servletservlet lifelife--cycle method called by cycle method called by servletservlet container to kill the instance of thecontainer to kill the instance of the servletservlet..
destroy()destroy() methodmethod make sure all service threads completemake sure all service threads complete
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 32/73
www.interviewDuniya.com
End of End of servletservlet life cyclelife cycle
Servlet Architecture
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 33/73
www.interviewDuniya.com
A servlet is an object of the javax.servlet class.
It runs inside a Java Virtual Machine on a server host.
A servlet is an object. It is loaded and runs in an object calleda servlet engine, or a servlet container.
Every servlet must implement javax.servlet.Servlet interface
Most servlets implement the interface by extending one of these classes
– javax.servlet.GenericServlet
– javax.servlet.http. HttpServlet
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 34/73
www.interviewDuniya.com
Working with Working with ServletsServlets
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 35/73
www.interviewDuniya.com
ServletServlet PackagePackage
javax.servletjavax.servlet
The The ServletServlet interface defines methods thatinterface defines methods thatmanagemanage servletsservlets and their communication withand their communication with
clientsclients
Client Interaction: when it accepts call, receivesClient Interaction: when it accepts call, receives
two objects that implementstwo objects that implements
ServletRequestServletRequest
ServletResponseServletResponse
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 36/73
www.interviewDuniya.com
Architecture Architecture
YourOwnServlet
HttpServlet
Generic Servlet
Servlet
Generic Servlet & HTTP Servlet
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 37/73
www.interviewDuniya.com
GenericServletGenericServlet
service ( )Server
ClientClient
HTTPServletHTTPServlet
service ( )HTTPServer
BrowserBrowser
request
response
doGet( )
doPost( )
request
response
Difference betweenDifference between GenericServletGenericServlet
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 38/73
www.interviewDuniya.com
Difference betweenDifference between GenericServletGenericServlet
andand HttpServletHttpServlet GenericServletGenericServlet is foris for servletsservlets that might not usethat might not use
HTTP, like for instance FTPHTTP, like for instance FTP servlets.(futureservlets.(futuregrowth specs)growth specs)
GenericServletGenericServlet is protocol independent, whereasis protocol independent, whereas
HttpServletHttpServlet is protocol dependentis protocol dependent
InIn GenericServletsGenericServlets you cannot use Cookies oryou cannot use Cookies or
HttpSessionHttpSession..
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 39/73
www.interviewDuniya.com
Session tracking is not possible, redirection is notSession tracking is not possible, redirection is not
possible.possible.
HttpHttp servletsservlets overridesoverrides doGetdoGet andand doPostdoPost methods.methods.
GenericGeneric servletservlet overidesoverides service method.service method.
genericgeneric
servletservlet
isis
superclasssuperclass
forfor
HttpServletHttpServlet
.
.
httpservlethttpservlet class can also have service()class can also have service() method.it'smethod.it's notnot
necessary that you can only havenecessary that you can only have doGetdoGet() and() and doPostdoPost()()
method defined.method defined.
GenericGeneric servletservlet is used for small data transfer whereasis used for small data transfer whereas
HttpServletHttpServlet is used for huge data transfer.is used for huge data transfer.
Writing aWriting a ServletServlet
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 40/73
www.interviewDuniya.com
Writing a Writing a ServletServlet
Your s Your servletservlets will usually extend the will usually extend the HttpServlet HttpServlet classclass. Which provides default implementations of . Which provides default implementations of
initinit, you only need to override this if you want to, you only need to override this if you want todo some initialisation such as open a databasedo some initialisation such as open a databaseconnection.connection.
destroydestroy, you only need to override this if you, you only need to override this if you want to do some cleaning up such as closing a want to do some cleaning up such as closing adatabase connection.database connection.
serviceservice, should not normally be overridden, should not normally be overriddenbecause it decides which of thebecause it decides which of the doX doX methodsmethodsshould be calledshould be called
i iW i i S lS l
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 41/73
www.interviewDuniya.com
Writing a Writing a ServletServlet....
doGetdoGet. HTTP Get is the default way a web. HTTP Get is the default way a web
browser makes a request and this causes thebrowser makes a request and this causes thedoGetdoGet method of themethod of the servletservlet to be invoked soto be invoked so
you would normally override this methodyou would normally override this method
doPostdoPost. If you don't respond to a. If you don't respond to a PostPost youyou
don't need to override this method.don't need to override this method.
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 42/73
www.interviewDuniya.com
HTTPHTTP Get or PostGet or Post??••The main differences between Get and Post areThe main differences between Get and Post are
* GET: data is sent as a query string client querydata is sent as a query string client query
is completely embedded in the URL sent to theis completely embedded in the URL sent to theserver. The amount of query information isserver. The amount of query information is
usually limited to 1KB. This information isusually limited to 1KB. This information is
stored in the request line. This is the defaultstored in the request line. This is the defaultmethod when you click on amethod when you click on a href href HTML link.HTML link.* POST: data is sent as part of the message body.data is sent as part of the message body.
Data is not visible in the URL and largeData is not visible in the URL and large
amounts of data can be sent to the server.amounts of data can be sent to the server.
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 43/73
www.interviewDuniya.com
ServletServlet doGetdoGet andand doPostdoPost
doGetdoGet andand doPostdoPost have identical signatures andhave identical signatures andreceive two parameters from the service method..receive two parameters from the service method..
public void public void doGet(HttpServletRequest doGet(HttpServletRequest request,request,HttpServletResponse HttpServletResponse response) throws response) throws IOException IOException , ,ServletException ServletException
public void public void doPut(HttpServletRequest doPut(HttpServletRequest request,request,HttpServletResponse HttpServletResponse response) throws response) throws IOException IOException , ,ServletException ServletException
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 44/73
www.interviewDuniya.com
•• HttpServletRequestHttpServletRequest is an Object containing informationis an Object containing informationabout the request from the web browser.about the request from the web browser.
Such as the login name of the user and any values in the headerSuch as the login name of the user and any values in the header field sentfield sentby the web browser.by the web browser. Any parameters sent as part of the request Any parameters sent as part of the request Any initialisation parameters set in the deployment descriptor Any initialisation parameters set in the deployment descriptor It also supplies any session and cookies (more on these later)It also supplies any session and cookies (more on these later)
•• HttpServletResponseHttpServletResponse is an Object which allows you to addis an Object which allows you to addcookies, add header values and redirect to a new URL, writecookies, add header values and redirect to a new URL, writeHTTP to the web browser and send error messages.HTTP to the web browser and send error messages.
ClientClient Server InteractionServer Interaction
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 45/73
www.interviewDuniya.com
ClientClient--Server InteractionServer Interaction
HTTP RequestHTTP Request (Sending request message to(Sending request message to
Server ):Server ):
• HTTP is a requestHTTP is a request--response protocolresponse protocol•• When a client sends a request, it consists of three parts:When a client sends a request, it consists of three parts:
•• request line:request line:
•• HTTP method type (GET or POST)HTTP method type (GET or POST)•• resource name (URL)resource name (URL)
•• protocol/versionprotocol/version e.g. POST /im51p/w7.htmle.g. POST /im51p/w7.html
HTTP/1/1HTTP/1/1
•• header variables: contains browser informationheader variables: contains browser information(optional)(optional)
•• message body: in POST method request information ismessage body: in POST method request information is
stored here (optional)stored here (optional)
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 46/73
www.interviewDuniya.com
HTTP ResponseHTTP Response (Sending response message to client):(Sending response message to client):
•• The response sent by the server also consists of three parts: The response sent by the server also consists of three parts:
•• response line (server protocol and status code)response line (server protocol and status code)
•• header variables (server and response information)header variables (server and response information)
•• message body (response, such as HTML)message body (response, such as HTML)
ServletServlet OutputOutput
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 47/73
www.interviewDuniya.com
public void doGet(HttpServletRequest request,
HttpServletResponse response)throws IOException, ServletException
{response.setContentType("text/html");PrintWriter out = response.getWriter();
out.println("<HTML>");out.println("<HEAD><TITLE>First Servlet
program</TITLE></HEAD>");
out.println("<BODY>");out.println("<H1>Welcome to Servlets</H1>");out.println("</BODY>");out.println("</HTML>");out.close();
}
<HTML><HEAD><TITLE>First Servlet Program</TITLE></HEAD><BODY><H1>Welcome to Servlets</H1></BODY></HTML>
The servlet must get thecommunications channel from the
response Object and set the
encoding before sending anything tothe client
Request containsany parameters,
Cookies andSessions send by
the client
Response allows
you to add cookiesand send data tothe client
FirstFirst ServletServlet ExampleExample
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 48/73
www.interviewDuniya.com
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
public class ServWelcome extends HttpServlet
{ public void doGet( HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{ response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(" <HTML>");
out.println(" <HEAD><TITLE>First Servlet Program</TITLE></HEAD>"); out.println(" <BODY>"); out.println(" <H1>Welcome to Servlets</H1>"); out.println(" </BODY>"); out.println("< /HTML>");
out.close();}
}
Servlets are not part of the
standard SDK, they are part of the J2EE
Servlets normally extendHttpServlet
Details of the HTTP requestfrom the client
The response to be sent to theclient
Set the response type totext/html (this is normal)
This HTMLtext is sent to
the clientDon't forget to
close theconnection
with the client
ServletServlet Life Cycle Managed by the Server and ContainerLife Cycle Managed by the Server and Container
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 49/73
www.interviewDuniya.com
Call to methodsdoGet(), doPost() in theuser defined servlet class
// load the servlet class and setup request, response objects
Servlet servlet = …ServletRequest request = …ServletResponse response = …
// initialise servletServletConfig config = servlet.getServletConfig();servlet.init(config);
// service zero or more requestswhile ( …more requests… )// invoke servlet to process requestservlet.service(request, service);
// cleanup after serviceservlet.destroy();
Unlike CGI a single servlet can service several requests. In CGIa separate process for each request. Servlets therefore reduce
Scalability ofScalability of ServletsServlets
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 50/73
www.interviewDuniya.com
Scalability of Scalability of ServletsServlets
There are several costs associated with loading andThere are several costs associated with loading andexecuting user supplied code in the web server.executing user supplied code in the web server.
Compiling and loadingCompiling and loading
Handling sequential requestsHandling sequential requests
Handling concurrent requestsHandling concurrent requests TheThe servletservlet is only recompiled by the web browser if itis only recompiled by the web browser if it
has changed otherwise the already compiled .class file ishas changed otherwise the already compiled .class file isloaded =>loaded => Faster response timesaster response times because thebecause the servletservletdoes not need to be recompileddoes not need to be recompiled
TheThe servletservlet can be kept in memory for a long time tocan be kept in memory for a long time toservice many sequential requests =>service many sequential requests => Faster responseaster responsetimesimes because thebecause the servletservlet does not need to be reloadeddoes not need to be reloaded
Only one copy of theOnly one copy of the servletservlet is held in memory even if is held in memory even if
there are multiple concurrent requests for it =>there are multiple concurrent requests for it => lessessmemory usageemory usage foror concurrentoncurrent requestsequests and noand no need toeed toload another copyoad another copy of theof the servletservlet and create a newand create a newprocess to run it.process to run it.
CompilingCompiling
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 51/73
www.interviewDuniya.com
CompilingCompiling
In order to compile aIn order to compile a servletservlet, you may need to add to your, you may need to add to your
CLATHPATH definition the following:CLATHPATH definition the following:
setenv setenv CLASSPATHCLASSPATH ${CLASSPATH}:${CLASSPATH}:
//usr/local/java/apache/jakartausr/local/java/apache/jakarta--tomcat/lib/ant.jartomcat/lib/ant.jar::
//usr/local/java/apache/jakartausr/local/java/apache/jakarta--tomcat/lib/jasper.jartomcat/lib/jasper.jar:://usr/local/java/apache/jakartausr/local/java/apache/jakarta--tomcat/lib/jaxp.jartomcat/lib/jaxp.jar::
//usr/local/java/apache/jakartausr/local/java/apache/jakarta--tomcat/lib/parser.jartomcat/lib/parser.jar::
//usr/local/java/apache/jakartausr/local/java/apache/jakarta--tomcat/lib/servlet.jartomcat/lib/servlet.jar::
//usr/local/java/apache/jakartausr/local/java/apache/jakarta--tomcat/ lib/tomcat/ lib/ webserver.jar webserver.jar
Calling theCalling the ServletServlet
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 52/73
www.interviewDuniya.com
Calling theCalling the ServletServlet
Calling theCalling the servletservlet is done from the Webis done from the Web
browser:browser:http://http://host:port/servlet/ServletNamehost:port/servlet/ServletName
For servlets that are positioned under
webapps/ROOT/WEB-INF/classes
Calling theCalling the ServletServlet
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 53/73
www.interviewDuniya.com
Calling theCalling the ServletServlet
Calling theCalling the servletservlet is done from the Webis done from the Web
browser:browser:http://http://host:port/dirName/servlet/ServletNamehost:port/dirName/servlet/ServletName
For servlets that are positioned under
dir_path/WEB-INF/classesand dir_path is mapped to dirName
PackagesPackages
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 54/73
www.interviewDuniya.com
PackagesPackages
Add Add packege packege packageName packageName to the java code toto the java code to
create a packagecreate a package Put the classes files underPut the classes files under
tomcat_home/webapps/ROOT/WEBtomcat_home/webapps/ROOT/WEB--
INF/classes/packageNameINF/classes/packageName
Call theCall the servletservlet with with
http://http://host:port/servlet/packageName.servletNahost:port/servlet/packageName.servletNameme
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 55/73
www.interviewDuniya.com
The The ServletServlet API API
WhatWhat’’s in the APIss in the APIs
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 56/73
www.interviewDuniya.com
What What s in the APIss in the APIs
The The ServletServlet APIs defines: APIs defines:
A A servletservlet lifecyclelifecycle – – how ahow a servletservlet is created, usedis created, usedand destroyed.and destroyed.
A programmer interface A programmer interface – – how ahow a servletservlet looks likelooks like
to the container and how the container looks like toto the container and how the container looks like tothethe servletservlet..
The The ServletServlet APIs is what the programmer APIs is what the programmershould care aboutshould care about
A Destroy ExampleA Destroy Example
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 57/73
www.interviewDuniya.com
A Destroy Example A Destroy Example
public void public void destroy()destroy() {{
/* Check to see whether there are still/* Check to see whether there are still
* service methods running,* service methods running,* and if there are, tell them to stop.* and if there are, tell them to stop.*/*/if (if (numServicesnumServices() > 0) {() > 0) {
setShuttingDown(truesetShuttingDown(true););
}}
/* Wait for the service methods to stop. *//* Wait for the service methods to stop. */ while(numServices while(numServices() > 0) {() > 0) {
try {try {
Thread.sleep(interval Thread.sleep(interval););} catch (} catch (InterruptedExceptionInterruptedException e) {}e) {}
}}}}
ServletServlet DestructionDestruction
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 58/73
www.interviewDuniya.com
A container may destroy the A container may destroy the ServletServlet because:because: It wants to preserve resources (this is not common).It wants to preserve resources (this is not common).
The container is shutting down. The container is shutting down.
In both cases the container will call theIn both cases the container will call the ServletServlet’’ss destroy()destroy()method.method.
Note that this means that a certainNote that this means that a certain ServletServlet will usually stay will usually stay ““alivealive”” for a very long time and is going to serve many users.for a very long time and is going to serve many users.
After the destruction the After the destruction the ServletServlet is garbage collected.is garbage collected.
SupportingSupporting ServletsServlets
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 59/73
www.interviewDuniya.com
SupportingSupporting ServletsServlets
The Web server must support The Web server must support servletsservlets::
Apache Apache Tomcat Tomcat SunSun’’ss JavaServer JavaServer Web Development Kit ( Web Development Kit ( JSWDK JSWDK ) )
Allaire Allaire Jrun Jrun – – anan engeineengeine that can be added to IIS,that can be added to IIS,
PWS, old Apache Web servers etcPWS, old Apache Web servers etc……
SunSun’’s Java Web Servers Java Web Server
……
““ListeningListening”” to a Shutdownto a Shutdown
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 60/73
www.interviewDuniya.com
ListeningListening to a Shutdownto a Shutdown
public void doPost(...) {...
for(i = 0; ((i < numberOfThingsToDo)
&& !isShuttingDown()); i++) {try {
partOfLongRunningOperation(i);} catch (InterruptedException e) {}
}}
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 61/73
www.interviewDuniya.com
Passing Multiple Parameters toPassing Multiple Parameters to ServletsServlets
The name of theparameter
The value of the
parameter
The name of theparameter
The value of the
parameter
To pass more than one parameter separate each one To pass more than one parameter separate each one
with a & with a &
<<a a
href href
="http:// localhost:8080/ /kingj1/servlet/param ="http:// localhost:8080/ /kingj1/servlet/param
? ?
p1 p1= = hellohello& & p2 p2 = = goodbye goodbye ">"> click here for a parameter example! </a>click here for a parameter example! </a>
Getting a list of ParametersGetting a list of Parameters
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 62/73
www.interviewDuniya.com
Gett g a st o Pa a ete sg
You can get a list of all the parameters passed by using You can get a list of all the parameters passed by using
getParameterNames getParameterNames ()() which returns an which returns an Enumeration Object Enumeration Object
Enumeration p=Enumeration p=request.getParameterNames request.getParameterNames (); ();
while ( while (
p.hasMoreElements p.hasMoreElements
())())
{{
String n=( String n=( String)p.nextElement String)p.nextElement (); ();
String v=String v=request.getParameter(n request.getParameter(n ); );
out.println("parameter out.println("parameter name is "+n+" parameter value" +v+"<name is "+n+" parameter value" +v+"<br br >"); >"); }}
Using forms to Pass ParametersUsing forms to Pass Parameters
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 63/73
www.interviewDuniya.com
gg
The second way to pass parameters to an The second way to pass parameters to an servletservlet isis
to useto use HTML formsHTML forms..<FORM METHOD="<FORM METHOD="GETGET""
ACTION="http://localhost:8080/servlet/param" ACTION="http://localhost:8080/servlet/param"
>>Enter your Name: <INPUT TYPE=TEXTEnter your Name: <INPUT TYPE=TEXTNAME="NAME="myNamemyName">">
<INPUT TYPE="SUBMIT" VALUE="Send<INPUT TYPE="SUBMIT" VALUE="SendName">Name">
</FORM></FORM>
Name of parametervalue of parameteris whatever is typed
into the text box
This will cause the doGet method in the servlet tobe invoked
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 64/73
www.interviewDuniya.com
Using Choice boxesUsing Choice boxes The choice box allows one of a set of choices to be The choice box allows one of a set of choices to be
selectedselected
Just like a TEXT input the result of the selection is Just like a TEXT input the result of the selection isstored in a parameter and passed to your applicationstored in a parameter and passed to your application
Using Choice boxesUsing Choice boxes
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 65/73
www.interviewDuniya.com
Using Choice boxesUsing Choice boxes The code is a little more complex than a TEXT field. The code is a little more complex than a TEXT field.<FORM METHOD="POST" <FORM METHOD="POST"
ACTION="http://localhost:8080/servlet/cw?action=submit"> ACTION="http://localhost:8080/servlet/cw?action=submit">
<<br br ><><br br >question 0 what grade do you want on this coursework? >question 0 what grade do you want on this coursework? <<br br > F > F
<input type="radio" name="q0" value=0 ><input type="radio" name="q0" value=0 >
<<br br >> resit resit
<input type="radio" name="q0" value=1 ><input type="radio" name="q0" value=1 ><<br br > fail > fail
<input type="radio" name="q0" value=2 ><input type="radio" name="q0" value=2 >
<<br br > retake > retake
<input type="radio" name="q0" value=3 ><input type="radio" name="q0" value=3 ><INPUT TYPE="SUBMIT" VALUE="Mark"><INPUT TYPE="SUBMIT" VALUE="Mark">
</form></form>
All the choices associatedwith the same choice box
have the same name!
Each possible choice shouldhave a different value.
When the submit button is
pressed the parameter q0 willhave the value 0 or 1 or 2 or 3
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 66/73
www.interviewDuniya.com
Using Choice boxesUsing Choice boxes You may have one than one independent choice You may have one than one independent choice
box in the same form. The result of each select isbox in the same form. The result of each select ispassed as separate parameters.passed as separate parameters.
Using Choice boxesUsing Choice boxes
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 67/73
www.interviewDuniya.com
Using Choice boxesUs g C o ce bo es In this case one choice is called q0 and the second q1In this case one choice is called q0 and the second q1<FORM METHOD="POST" <FORM METHOD="POST"
ACTION="http://www3.unl.ac.uk:8186/kingj1/servlet/cw?action=subm ACTION="http://www3.unl.ac.uk:8186/kingj1/servlet/cw?action=subm it">it">
<<br br ><><br br >question 0 what grade do you want on this coursework? >question 0 what grade do you want on this coursework? <<br br > F > F
<input type="radio" name=" <input type="radio" name=" q0 q0 " value=0 >" value=0 >
<<br br >> resit resit
<input type="radio" name=" <input type="radio" name=" q0 q0 " value=1 >" value=1 ><<br br ><><br br >question 0 what grade do you want on the exam? >question 0 what grade do you want on the exam?
<<br br > F > F
<input type="radio" name=" <input type="radio" name=" q1 q1 " value=0 >" value=0 >
<<br br >> resit resit <input type="radio" name=" <input type="radio" name=" q1 q1 " value=1 >" value=1 >
<INPUT TYPE="SUBMIT" VALUE="Mark"><INPUT TYPE="SUBMIT" VALUE="Mark">
</form></form>
Thread Unsafe Thread Unsafeimportimport java.iojava.io.*;.*;
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 68/73
www.interviewDuniya.com
Read thenmodify then
write
importp java.ioj . ;;
importimport javax.servletjavax.servlet.*;.*;importimport javax.servlet.httpjavax.servlet.http.*;.*;public class multi extendspublic class multi extends HttpServletHttpServlet {{intint count=0;count=0;public voidpublic void doGet(HttpServletRequestdoGet(HttpServletRequest request,request, HttpServletResponseHttpServletResponse response)response)
throwsthrows IOExceptionIOException,, ServletExceptionServletException {{response.setContentType("textresponse.setContentType("text/html");/html");PrintWriterPrintWriter out =out = response.getWriterresponse.getWriter();();out.printlnout.println("<HTML>");("<HTML>");out.printlnout.println("<HEAD><TITLE> Thread UNSAFE example </TITLE>("<HEAD><TITLE> Thread UNSAFE example </TITLE>
</HEAD> ");</HEAD> ");out.printlnout.println("<BODY>");("<BODY>");out.printlnout.println("<H1> old count is "+count+"</H1>");("<H1> old count is "+count+"</H1>");count=count+1;count=count+1;try { Thread.sleep(4000); } catch (Exception e) {try { Thread.sleep(4000); } catch (Exception e) { }}
out.printlnout.println("<H1> new count is "+count+"</H1>");("<H1> new count is "+count+"</H1>");out.printlnout.println("</BODY>");("</BODY>");out.printlnout.println("</HTML>");("</HTML>");
}}}}
Thread Safe Thread Safe
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 69/73
www.interviewDuniya.com
A good way to make sure A good way to make sure servletsservlets are thread safe is to have noare thread safe is to have noglobal data. But this is not always practical.global data. But this is not always practical.
A partial solution is to store data on a per client basis. But t A partial solution is to store data on a per client basis. But thishisrequiresrequires sessionssessions oror cookies.cookies. It does not work if one clientIt does not work if one clientmachine has two instances of the web browser accessing themachine has two instances of the web browser accessing theservletservlet concurrently concurrently
The best method is to mark the sections of code that access The best method is to mark the sections of code that accessglobal data asglobal data as synchronized.synchronized. This allows the sections that do This allows the sections that donot access global data to run concurrently not access global data to run concurrently
Thread Safe Thread Safe Enclose sections that use global data inEnclose sections that use global data in synchronizedsynchronized sectionssections
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 70/73
www.interviewDuniya.com
Can not beexecutedconcurrently
Enclose sections that use global data inEnclose sections that use global data in synchronized synchronized sectionssectionsimportimport java.iojava.io.*;.*;importimport javax.servletjavax.servlet.*;.*;importimport javax.servlet.httpjavax.servlet.http.*;.*;public class multi extendspublic class multi extends HttpServletHttpServlet {{intint count=0;count=0;Object s=new Object();Object s=new Object();public voidpublic void doGet(HttpServletRequestdoGet(HttpServletRequest request,request, HttpServletResponseHttpServletResponse response) throwsresponse) throws
IOExceptionIOException,, ServletExceptionServletException {{response.setContentType("textresponse.setContentType("text/html");/html");
PrintWriterPrintWriter out =out = response.getWriterresponse.getWriter();();out.printlnout.println("<HTML>");("<HTML>");out.printlnout.println("<HEAD><TITLE> Thread UNSAFE example </TITLE> </HEAD> ");("<HEAD><TITLE> Thread UNSAFE example </TITLE> </HEAD> ");out.printlnout.println("<BODY>");("<BODY>");synchronized (s) {synchronized (s) {
out.printlnout.println("<H1> old count is "+count+"</H1>");("<H1> old count is "+count+"</H1>");count=count+1;count=count+1;try { Thread.sleep(4000); } catch (Exception e) {try { Thread.sleep(4000); } catch (Exception e) { }}out.printlnout.println("<H1> new count is "+count+"</H1>");("<H1> new count is "+count+"</H1>"); }}out.printlnout.println("</BODY>");("</BODY>");
out.printlnout.println("</HTML>");("</HTML>");}}
}}
Servlets vs. JSP
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 71/73
www.interviewDuniya.com
• JSPs– Look like standard HTML or XHTML
• Normally include HTML or XHTML markup
– Known as fixed-template data– HTML codes can be written easily
– Used when content is mostly fixed-template data• Small amounts of content generated dynamically
• Servlets– HTML codes have to be written to the PrintWriter or
OutputStream
– Used when small amount of content is fixed-template data
• Most content generated dynamically
SummarySummary
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 72/73
www.interviewDuniya.com
The The servletservlet life cycle?life cycle?
EachEach servletservlet has the same life cycle:has the same life cycle:
A server loads and initializes the A server loads and initializes the servletservlet (init())(init())
The The servletservlet handles zero or more client requests (service())handles zero or more client requests (service())
The server removes the The server removes the servletservlet (destroy()) (some servers do(destroy()) (some servers do
this step only when they shut down)this step only when they shut down)
8/14/2019 servletsIntroduction Life Cycle
http://slidepdf.com/reader/full/servletsintroduction-life-cycle 73/73
www.interviewDuniya.com
End of End of ServletsServlets BasicsBasics
andand
ServletsServlets Life CycleLife Cycle