Advanced Java Module 4 (A)
Advanced Java Module 4 (A)
interface
of to handle of
in dynamiits c response [Link] user to web
an
ferent read order the business. to of
pages text/html. The are servers the
That enters
COver
connection.
several
introduction
datknown
a obtain each
to Web, must
make content.
Hypert e xt
request
used file cooperate
indicates
advantages
a
Introducing
examples.
Servlets
all.
it
this This
anguages from theasclthieentserver informatbeion woulAssumed thfoirsreturned theto of
a Uniform
is Instead,
The
to
the request. dynamically the
Markuppurpose. appropriate to
servlets, topic
servlets.
wereComneces
mon sary could include that type in Resource
provide we
HTTP ofan
will of
used dynamiThceally accessible Language an HTTP you servlets
focus
Servlets
[Link] generated itemsonline content. web must For the Locatorcontent
build and tofor store
example, response on isare
the quitesmall
to sale, (HTML) server.(URL) tohave
CGllnwrteirtetace constItruct cust
would
refleoctmersprices, uses ordinary The toThe into user. basica a corelarge,
concepts,programs
programcso. mdamut(aCnGItoic).ated open pagintormation
a latestthe t via
e availabidatlityabase
asource
Multipurpose the understanding
browser.
web Consider
browser.
a of and
the
These HTTP CGl
connections
by web , code ASCIl server a interfaces.
beyond
execute
it
isthaton
to oftext The maps request
withcreatto
ing pages. The
store web aInternet
1121
included al owed the one a orders,
The
has
a this for
the
1122
Development
Options
Servlet The
byOracle
an ones To its methodwhich HTTP been
Important process the when [Link]
the aserver.
browser server.
destroy(Three Life with the significantly
the introduced. the also
necessary procesSOr
etBeans.
pen-SOurce experiment
are
objects Finally,the remains
servlet
The Fourth,
particular
servlet Third, Second, First, platform-independent
fullserver other Servlets expensive CGI However,
and thisrequestsprovided the methods
Let
Glassfish
can
determination
data
relinquish
to the
servlet
so th e
then
assume us ).
They
Cycle functionality
softwareenforces better. to programs and
is HTTP the servlet. this Among
offer
Bothprovided then may inserver mnay itserver generatesconsider are create to CGI
product with server
received HTTP memory
Tomcat and be be
th e
request. first
is
The
that are
central
of via of set a Servlets several
a these were suffered open
Apache
servlets,
garbagesaved any may HTTP invokes configure invokes implemented a
a the thebecauseof separate
with
is from
the in loaded servlet request an user
typical a Servlet not and
are resources
maintained
and
resources decide
made request. You HTTP enters
to sockets
restrictionsJava advantages
executeservlets. close serious
the
assfish Tomcat. Java
you
collected. a
persistent
to
are
clients.
address
server's
to
space
wi l
th e
itself. into
init(
the
dynamically received
is is
request
user
by
t
l
h
if
e
e platform-independent.
class they process
database to
byEE need
will
such
specific unload The
service()
It see memory.
)
a
scenarioevery cycle
Uniform
and
libraries to to ar e within in performance create
may that method RMI comparison
Glassfish
the writtenhandle
can SDK. as service( for protect
Apache access store. file the also method it It the
by
this
servlet
to
of a
mechanisms is
the connections
separate
a
neededdirectorTomcat
y. Development
to in
adjust this
to by
set the was wide
assumechoose follow the
At
you
are different. here install
ony the
the
readers
Thus, here using SImply is and
itused
tomcat ale
-
[Link] and8.5.31. variable need
paths
wil book. the
root Yo u
version run-time different in
a experiment tools.
just
that only a
work
in must
for this refer the for useful
andcommand this wav
The very
the code mettheofhod code. ) is the Thihandles the example, [Link]): (ServletRequest
request,
steps annd
[Link] the
earlier:. previous and HTTP
HTTP text/html. client. enables is
service( only chapter. extends request
Tomcat rplesponse.
ace obtains estServl
arequests
aThiblissehestResponse the method service()
the it
provides
and Serviet detail. in
) interfaces
Next, the
section. the response. a servlet from class GenericServlet
must indicates the versions
provides
the notthate it Source
servlet.
running
be Hel oServlet .clasAlso,
ad
Then
Pr
Wr
i
i
n
te
t
r. that
MIME
object. data
read
to
client.
met
(whi
a c h hod. program
is of [Link]
required
contains
that
Chapter
Therefore, the in
core
packages
of
Hello!
You Alternatively,
wil be
can
web a
Web
a
PART IV
in will
this in done
observe browser Applying
interface which be API are Servlet contain bold
in also chapter. because you
this
servlets
package available
servlet
supported has type. the Browser and
interfaces provided they API. the may
enter
or
package. been
are KeepThese
output
exxtend contains specification to classes 127.0.0.1l enter
operate. most in not the and
are The by a by are of the
a processincluded in and the is URL
Tomcat Java
environment. their Allows
Used Used Enables Description also most number
Declares class
The
a readers [Link]
EE.
mind
interfaces defined
servlet
URL Request
shown
very that 4.) shown
to to following 8.5.31 of that
write read servlets servlets significant
implements
life important. and Thisongoing with in as
of these here:
cycle interfaces chapter Java that th e the here: the
data data works is and
to to table version packages
SE. are
browser IP
tofrom
a initialization
get
log methods
these
of development
with [Link].
discusses Instead, required
address Servlet
client aevents sumnmarizes
the
client and 3.1. display
interface. all
fo r are of
ponse. and is classes modern (As
request. a Servlet. they not to the
the aand area. local
access servlet.
parameters. build
several that corepoint ar e part
The enhancement.
versions theof It
information
ServletRequest
Alestablish
l of ofprovided They of the [Link] l
servlets key the
interest, the
servlets contain
Servlet
constituteJava
interfaces
the by
about must The core the
thods
Table
The init(ServletConfig destroy)void Method
voisdc) String
rvice(ServletRequest
getServletConfig)
ServletConfig
voidreq, getServletInfo()
by called the
information destroy( Tablein Indicates
Indicates Encapsulates
Encapsulates Description
Implements
Servlet servlet
AThe to byServlet
and the
Calledption
ed [Link]
[Link].
etExtoception when when a
getServletConfig( [Link] the
developer
(fo r methods
) server
any
interface. classes servletservlet
a a
an an the classes
core
inputServlet
process
tocan
res be
tor the stSer
ringvletConfig the example, initializationduring in
unavailable
iserror
output
Chapter35
thrownnitializbeed. servlet.
the version the cyclparameters. reading
rey. troam e cycle the writing Introducing
Servlets
1127
s The d that is init
generaleredspoaseclienL oblIniatthunedeiitalvzatlon cotains getServletlnfo
number). called methods of ).
servicet
servlet. a
reiest:
responsesintertaror
the
in
nsegetOcontutpeunttcontStreentam()
Sets Sets
the the
Retdagetta utoWrnsriter() to DescriptioServl
dataReturnRets urns
n etRequest
the a the a the Description
type length
ServletOutputStream
response. Print response.
has character
Writer been
ReturnsReturns for ReturnsReturnsinvokedthrown teReturns
Returns
the from
xt Returns Returns
parameter
the request. this Returns been
Keturns
1llegalStateException
previously
used returned
Returns
read
to
returnedif
Returns ReturnsReturns Keturns
the the
Chapter
35
request if a a an an the a ifthe the
tor tor has An An the t he the the the on the
buffered ServletinputStream
getlnputStream description
the the be n
that previously encoding port nametransmission string string this request.
enumeration value
array the type the character
size value
l egalStatetxception
responseresponspreevilouseglyalStateEusexcdbe
can
eption
invoked that tothre
number. of equivalent
example,"htp'the ,
(for
equivalent
object.
reader
An of
specified
containing invoked
the
of
binary
data cannot the
type
unavailable
size
of isthe
encoding
of
(ServletRequest
IOExcept
get
request. (0;
paramneter
and
[Link]
[Link]
name="e" name=p" PostParametersServlet
class
public
type=submit
value="Submit"
the
and
names
())
ements");
=
response)
ServletResponse
type=textbox )is
to of getParameter()
name
enumeration
overridden
ServletException, parameter i(pvalue)
Enumeration<String>
=
writer. enumeration
of e
[Link]
1host
extboX
[Link].*;
import GenericServlet
extends hasMoreEle
+
(pname
[Link]
"http:/
/local td><B>
Employee</tas
type=tE ctd><B>
Phone<
/tds
code:
for
that
the
parameter
*;
[Link].
import
service = =pname=pvalue
"Form1" it *;
[Link].
import print
nmethod="post method
an PrintWriter Display ();
[Link]
sourcereturnsthe
void String
<centersaction=<table> <td><input<td><input
name
<form </table></html> service( via
obtained
Get
throws
public
//
Get
while
(e. String
</body> The 7/
ctrs </trs
<trs </tr> <input method
see
//
can
generated to HTTP can
[Link]! such easy of a
important client to reque
that
the
[Link], request.
response. process responses. response
it machine. codes
dynamically use makes a
the basic about HTTP
normally HTTP
update written. mostto status
the functionality
HTTP clientand HTTP
example: order information the
requests
and fields. in illustrate
will
an
chapter: froman and
The
a an different
that
is defined in on
that to chapter.
directory,
this you datadataread
class stored formulate
indicat
text response its HTTP
test to HTTP,
interfaces this be this obtain the
the GenericServlet,
see,responses. read towrite
this be
to
appropriate in extend to handle to to SC_OK
steps in will used to to data 35-5.
number adisplay with servlets
servlets in information to correspond
servlet
and workingyou interfaces
Description
session used to servlet The
HttpServletRe
Interface
methodsThe
HttpServletRequest
Interface
theserunning). and typically Table
example
theperform phone will Package
[Link]
he classes As requests Enables Allows classes
Enables
a in
a
enables
and [Link].
browser. Description
state enables
shown These
to already browser when the
theServletResponse, thedevelopers Provides
itcopy and Allows For
Then, used However, summarizes
HTTP summarizes interface interface
defined.
not ain name the
are response
Next, page page. have methods
described.
is employeesteps, with Servlet
servlet. it(if web HttpServletRes
are
web examples
servlets.
in worktable HttpServletRequestHTTP
constants
Tomcat these classes table
previouslythe the ServletRequest, HttpServletResponse
HttpServletRequestHttpServlet. its
the an
Display thatfollowing following of
following
Submit
servlet.
the
by precedingand
of Several an
Compile Start Enter functionality
servlets HttpSession HttpServlet to
Several
interfaces Interface assigned
as 1. 2. 3. 4. The Theis requests. Cookie request.
file, After The build these Class client.
as The The
be
1133 invalidated.
field. returns available. All
field. the theafter request. [Link] the isthat
35-7.
Introducing
Servlets named
named after after
field. URL URL
session andthe ID. ID.
in
valid intornation
Table been
request.
field
named
this fieldheader
names.
header
located
of
string
located
field request. the the
of
string URL.
this
issued
the
identifiesreturned.
a
If
returns
creates
session
Otherwise,the
session
the
is[D
session
not
tisesource sestateinummar
alreadyized
header is is request. exists,
this that that who contains contains
the hassession
in that then request.
request
[Link]
requested
Il egalStat
Returns cookies header
authentication
scheme. the the for query query the
date informationinformation user session. session
of method [Link] URL and
of
equivalent a this request. cookie
this false. URLfalse.
returns returns
Otherwise,Otherwise,context.
session
Cårrent writeare
andmeththeods
a stringthe
the the theenumeration the for created Table
Chapter
35
arravvalue
of
of of value
int
HTTP
before before
pathand pathandto
real
of the
a querynameof Returns
ID
of session
URI. Returns
the the
URL. part is
no for
and this session
aif
the the
if
true true true
if
Http35-SerVar5viltheoeustRinsummar
equest ized
read if
Descriptionan the the an it any the the
thethe anypath anypathtranslating that the one truefor that
Returns Returns Returns
existing
exist, is session indicates toservlet its
Keturns
KeturnsS Returns Returns
Returns Keturns Returns Returns Returns
servlet servlet ReturnsReturns ReturnsReturns
not
new
If a
FOUND
Inte rface
ofSeveral
areinterface aenablsessi
es on.
bool
isRequest
by
Tabl ean edSessionldValid() interface
Defined
e
)IsRequestedSessionldFromCookie(
HttpSession
getSession(boolean
new) 1SRequestedSessionldFromURL()
NOT HttpSessio HTTP
anthro
field) String
)
getRequestedSessionld(
StringBuffer
getRequestURL() this
ofmethods
oetDateHeader(String
longfield) getintHeader(String
field) Methods SC
getPathTranslated(
)String an
getStArmutg hType()
)getCookies(
],Cookie/ getHeader(String
Sring Names()
eetieader
String> )getPathlnfo(
Suing
)getMethod(
Suing
StringgetRemoteUser()
String )getRequestURI(
)getQueryString( String
HtpSession
getSession()
getServletPath(
)
and
HttpSess
me
with
with
not he
the
fonnd of
milliseconds
l.1970,GMT thesession.
when
removes [Link] val
created specified
the
in fromwhenincluded commonlmethodsy
iated
is ofsessinn
{in
time
and
by
invoking server
passed
deleted path not.
deieted signature 35-8.
enumeration GMT) is and
Genreequest
[Link].
oftr ID session accessed
attribute
Chapter
35 assor
nullif he creatinn (in
session the
valueattr.
is is
itwhen is
domain
it Table
Otherwise, assupplied is The
value
Returns
Desciption
the an
with
January time
1970,the this if
the the the1, on Invalidates
associated
midnight,Returns
truebeen the
request Keturns
Kemoves
in
thepassed
Associates
itcookie,
cookie determine the
whose has
summar
in ized It
ReturnsReturnsReturns Returns January yet
name
HtpSessionthisato ItCookie. are HTTP
server.
value)cookie
atty. not
whenassigned URL
cookie 35-9.
process
determines a web
the enters for Stringthe are
Class
C extendsTable
HttpServlet
val) by
Object Defined
explicitly the class
ofvalue
constructor
and
class inSumm
of
unid
removeAttribute(String
attr)
date
pathuserto
suppliednane, Cookie
Cookie(String
attr)
)
getLastAccessedTime( attr, Methods not and the and receive
getAt ri buteN
getAttribute(String,
) )getCreationTime(
&
long
eNames(
<String>
Various
expiration If
setAttribute(String is
date
ends.
domain
session
then
One
TPrequest.
is
nameofthe
tnemethods
HttpServlet
that
Introducing
Servlets
midnight,
since
arrives
to
access
request
requested
HITP
respectively.
provide
HITP are
of ). of
types doTrace
These
various
input.
A this form
methods
scopehandling
invokedHTML fornn
is
ispage tthat the
web
servlet [Link].
Theformotparameter
request.
adefines GET
:8080/examples/ ervlets/
ColorGetServlet">
request. request.
request.
milliseconds
the response, andthe
beyond The
A
files.
arguments methods. when HTTP
when an the doPut(), two It action
request.
POST PUT
HHTTPTRACE
GMT)
modified.
when
handle is used [Link]
and
Responses followinprocess
Chapter
35 HITP
Description
an an
HTTP
the
Therequest
servlet.
by HTTP
resource
January this
Called
that
these), requests
of
commonly GET
doPost( cases.
one HTTP these
methods
), are
overrides
example
in
g
HTTP definediNoticto
that
e
servlet
the button.
""R>eGrd"1>eVaRen<ldu
doOptions( The
forthe
and of requests Requests
an
submitted. identifies
specializedtypes ofexamples handlesisservlet inshown
submit
a
"1">
req)
35-9
by
HtpServiet typically
Requests ),
different
POST that a is [Link] "[Link]
Size=
ServletException
IOException, :(HttpServletRequest
ServletException
ServletException ServletException provides doHead( presents servletand aandURL
[Link].
HttpServletResponse
res)
AoTrace(HttpServletRequest
req, HttpServletResponse
req,res) developerthe
and GET is
page "color"
HttpServletResponse
res) HttpServletResponse
res)
ioPost(HttpServletRequest
req, doPut(HttpServletRequest
iwdareq The
:element
name="Form1"
<form
Defined
service(HttpServletRequest of
class ), description
GET HTTP
section adeyelon web
HTTP doGet(
requests.
servlet
A the
form
a
on
URL. value
<opti
1OException, wsIOException, Methods
IOException, HttpServlet However,
this Handling for a
select
specifies
name
<B>Color:
dCtion=
etLastModified doDelete(), will code
Handling Therefore,
Method throws throws throws throws
The
The
complete
book.
we defined
a
nerewhen
in a
SOurce
Tag
<center> <select
Contains <html>
<body> <o
Handling
Requests anThe
[Link]
anyof then
method color
handles is
servlet
submitted.
thebe <option
>Green</option>
woDtion process
value="Blue">Blue</option> iresponse
s
response)
HttpservletResponse the selected perform
response.
that a
thatshould
eXCept 1u
>Red</option>type-submit
<option value="Submit
"
)
to getParameter( [Link].*i
lmport
setContentType
HTTP
POST [Link].
andfor be POST
method : overridden
Jovelop
aserviet different
servlet.
tag "[Link]
size= ("<B>The and
is code
page [Link]
identical
value="
Green" for
A
user. *;
[Link].
1mport
doPost
(color)
i
=
servlet
name="Color" pw
web The
Source value="Red!
codeis the import
*;
[Link].
=
"Form1
name=
<form String
Color [Link]( the
a HTMI. thataspecifies
method="post"
<B>Color:</B> theby
method
sourceusesmade void .
[Link]
PrintWriter
;()
[Link] itP
wil form
On
to specifies
class response
def
we awhen
in
ined <htm l><centersaction=
cbody> select
</select>
<br><br></body>
</form> ) It was
ThedoPost(
</html> servlet. public
publicthrows
Here <input
that
tes
it
}
when MyCookie. gets
here: Thisthe to is
invoked on It message
added
listing. listing.
Localnost summarized
named
button
:8080/examples/servlets/servlet/ColorPostServlet. has
then
to http:7 is following that feedback
sent servlet [Link] following
is
object
is cookie cookie
that as to
is Thefiles a sent A
URLserver request. the thealso theCookiemethod.
The
the cookies.
three for in is is in {
the value shown field
There "> parameter. HttpServlet
of
HTTP shown
a
request,
partto contains of value-"
)
createsaddCookie(
browser submission text
as the use aspecify
included of values.
cookie is entered.
[Link] is
to the [Link]
the body then {
howexample in size=25 "data" (HttpServl
IOExc
from to extends
not the the
illustratesDescription
user be value It
MyCookie:</B>
> thethe
"data".
value="Submit"
are sent in Processes can HttpServ
response
The aAllows the of via
URI sent
request value data"
pressed, value
namedresponse
AddCookieServl
the are submitted. *;
POST values
example, that for a name=" [Link]
codewhich the
HTTP
servlet is parameter
contains
*;
and request. for HTTP servlet. doPost
button
[Link]
[Link]
source for
type=textbox browser.
this names is in name="Form1"
<form type=submit
<input
an page
àdevelop code io.*;
import
java.
ln
Parameters
for Cookies
Using [Link]
field value
"post"
method= andthe
[Link]
web HTMLtext
thisPOST the"MyCookie"
source javax.
javax. void
class
When of to
the
a of
web s ona HTTP <centter><B>Enter </body>
acontains header throws
let The </html>
</form> Thevalue public
Ce Ine <body>
<html> <input written import public
import
NOTE Now,1ormFile page.
an the the
1141
invokesThethe
request.
that
Introducing
Servlets Itlisting. Observe
GET
HTTP
following information.
response.
the
the in HTTP: {HttpServlet
in includedthis
Chapter
35 data); shown the obtain request, 0;[Link]
request.
. get Wi++)tmritler()Value
("data");
MyCookie",
to");
.getWriter(); is are to
written
to
that called
("t
(HttpServletRequest
IOEXception e
() xt/h
:") ;
{
lengt0;.gethN; ame
;
response
("text/html"
): set [Link] extends { HTTP (i].get
request
..getParameter
been
cookies
thenare response)
HttpServletResponse Cooki[i]eCOOki
s. value);
tentType COokies es"+
response. +name
+
response
(" respomse.
(cookie);
[Link] anyare methods
GetCookiesServlet
of
header cookies.
HTTP Cookie response.
setContentType
("
<B>MyCookie readcookies Exception,
*;[Link].
request. from
from
new
.addCooki
ie t o
HTTP to )Value( *;
these
method
[Link].
[)Cookie
= setConte
response
these= <B>i =
cookies ;
") <
=("name
[Link]
(data):
[Link] doGet cookies pw 0; name value =value
=
Create
/cOokie t o
parameter
cookie
Cookiecookie
output
iter
pw
=
();
for
code of get *;
[Link]
[Link] ) Values
[Link].
import Servlet Display [Link]
PrintWriter
("
=
=
";
();
[Link]
classvoid
data
and
getCookies( i String
WritePrintWr: source (intString
Get
String Add andgetName() publicthrows
Get
17 for
The names importpublic
import 77
ba
sharedgetsgetAttribute(
) Date current
"date"
saved
session such associate
However, methoda
theexample:
update
by
displayed 8080/httpe:xampl
/ localehs/ostservl: ets/servlet/GetCookiesServlet
the then
browser
via is
be
canprovide
andis
HttpServletRequest.
state
that Session) The
is
obiect
thename
information ),getAttributeNames(encapsulating the
cookiecookie one.
Sessions bindings getSession(accessed.
browser. That bind
andthis the previous exist.
ismessage bindings. "date". to
directory,
test the
the when thatserver. alreadylast called
to theto that of The
object
assigned
expires theso set name
steps feedback in observe of was
appropriate displayed of information
a
and method
a these state.
getAttribute(),
not
is
Date
page method
these independent store the
cookie
explicitly browser can managesession does HttpServ
perform browser: and to thisA
athat
are thesetMaxAge() state getSession( ) oneboundaccessed.)
)
running. object when setAttribute(
the browser. observe cookieTherefore, HttpSession
useif
client.
a created
to Then, the not is savebetween to isthattime
them request This), first
already via theisdate setAttribute(
a how extends
described. a will to with and
object
copy MyCookie. URL
[Link]
in using
of expiration necessary thereturned. illustrates
interactions
is
sessiondateispageThe
you value Cookie. Each via of associated *;
[Link]
following
Next, not [Link], by protocol. created methods thethethecreated. DateServ
previously
[Link]
is and
of
experiment is is The newobtain
servlet encapsulates
when
*;
servlet.
for
ifTomcat,
value
web these
the
name an method
example, Tracking
-ession
machine. it object
severalbe [Link] A
applications, )removeAttribute( then *; [Link].*
[Link].
import
the completing stateless canHttpSession that session.
to
following binding
theas Display request the called is javax. class
a Submit can from session
mechanism.
a servlets time
file, Start
Compile Enter that setMaxAge(
) client with current
object.
to
this
[Link]
browser.
the
Next, this You a collected is thatsuchand
Observe is
HTTP some The method
A namesall
1. 2. 3. 4. After import publiC
import
import
In ends. the object
no
An the date
on in by is
date
line the
current
Introducing
Serviets
irst shows
theThe line
withdisplayed.
second
line
one are The
Chapter
35 "<br>");
linesaccessed.
displays
(true): date"); two
public request.
():
response.
("text/html")
; date):
+
browserinvocations,
last
[Link](accesa
(" +
[Link]
Void
doGet
(HttpServletRequest
throws
ion,
IOEXception [Link]
date
date)
;
the was servlet
HttpServle
response)
object.
last +
date/time.
"
servlet, subsequent
date:
of
.setContentType [Link]
(""Last
access: the
on
HttpSessi
("
date" this
[Link] when
date/time
etResponse "Current
( reguest
servletExcept: {
(Date) current
Date();
= = [Link]
("<B>"); null) On time
hs
1/
Get
pw
writer time.
information.
HttpSession
ter = != first and
the
// Display new [Link]
Display
PrintWrit date and
(date you date
Get = date
Date date When the
| i£ |/ time current
shows
and