[Go to site: main page, start]

0% found this document useful (0 votes)
2 views23 pages

Advanced Java Module 4 (A)

The document discusses the use of servlets in web development, detailing how they handle HTTP requests and generate dynamic content. It covers the lifecycle of servlets, their advantages over CGI, and the setup process for using Apache Tomcat as a servlet container. Additionally, it provides instructions for configuring the environment and deploying servlets effectively.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views23 pages

Advanced Java Module 4 (A)

The document discusses the use of servlets in web development, detailing how they handle HTTP requests and generate dynamic content. It covers the lifecycle of servlets, their advantages over CGI, and the setup process for using Apache Tomcat as a servlet container. Additionally, it provides instructions for configuring the environment and deploying servlets effectively.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

the webSeparate tinformation

[Link] in and Page Drowser static ahow order In


request Sackground
and nne chapter
the This
se. Contents Mail HTTP
CHAPTER
35
Or
classes, server
eparateServer
more
De [Link] *ow Extensions has VE web
web of
tyape header to
generates to this
databases ofCOnsider abrowsers side
ety
A via Processearly those aboutIt MIME of specific understand
page. and
chapter
presents
Process an
days web
to
wishes text/plain.
ty pe(MIME) the an Aand
in
develop of
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

also It to is isretrieved Resource servlet. address


is is handles each servlet formulate possible possible of web understand
URL. available the in each problems.
supported
be to The the and Java.
Software
used
an a
server.
method and is )
of servlet. server. These
are resources clientspace with Therefore, process
for
servlet
open memory that from th e and This
Locator to Third,
anfor to that CGI . each It
with available is to servlet. pass loaded request
invoked
when a request.
of for was
source
by are The calledits HTTP the This The are serviet.
you the First,
a otherclient
ndation.
container/server. on
other
NetBeans.
allocated
allocated memory.
server servlet initialization server
(URL)
these
init( have aJava
web each
expensive
This method into at
project response
for is
specific ), It performance
server Second, techniques
server. addition, [Link] In
IDES, then to seen cansecurity
calls The process
each method to themaps methodsa service(
for request. in
Apache It
sponsored
for read is
address sent web communicate
already, Finally,
machine. servlets It
termet
such can the the HTTP
servletandthe algorithms for
parameters invoked this times manager
is
were
otherany data is browser. to are ), not is
asalso Two servlet.
destroy() the
called request the and are lt
Ecup 10 request. client. that space called by was
be vy popular only the on
has to The
used by to of to
TomcatUsing this than
mand-linenrveairsoonn,mnent vironmlanDeEnt. seamongrvdiffersietscreatioAln thouofgh
youhat
locationuse [Link].
[Link]-8.5.31-windows-x64\apache-tomcat-8.5.31\
whichis n the NOTE
directory \apache-tomcat s C:\a 04-bit the available. needTomcat
because
documentationREMEMBER
1se sercontvlet ainsprogrammi
er, you varniogus edon'netxdperimceonmtchapter
This
[Link] of examples. the is version Ihe to only for t
tomcat-8.5.31
andThe Once Tomcat, then AlI
(or examples it contains
create the the for servlets,
classes
in installed, of
the whichin location
will The command The testing with wi Therefore,
Furthermore, IDEs
the of instructions and instructions conceptsevenif to tools
instructions
intormation
work servlets uses
wing directories
you
You a Tomcat in test
the for
your llne wil download are they such
you the different
may assumed this You for class you
environments.
be
Tomcat if IDEs,
employed. are as
interfaces l
start
wil
needshown Java need
servlets.
chaptershould verydocumentation,
8.5.31 a libraries,
[Link]. slightly
presented are
for using you
NetBeans
given many and not
ectory: version that developing l developing and concerning
in are

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

section the examplofes unpacked range uSing and Furthermore,examples. in


-X64 to Toby the Tomcat ), use time still in command an and an this
dire cto ry environmental a a an they the
IDE,willbe
kcipse

pache servlets lomcatselect, ing


build stop assume Kit 64-bitversion of
8.5.31. deploying
lDE apply. anIDE elsewhere
development not
chapter.
of environment just
is you in from readers. this and/or Itwill you using
nameslomcat instal ed. this Windows
appropriate writing, and
This servlets isIt to
provides
since line
possible are hapter35

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

If can several this that simple, nearly


environment.
8.5.31lib [Link], toyou
If to vou directly, to servletchapter [Link]
the It chapter to book vOu andIntroducing
trom JAVA_HOME
matchinstàl make load download
your of uses also
is deplovment
the Servlets
1123
the Tomcatversionssupport container/server, are mechanics with vet any develop
assume (an
in
bin those à approprtateTomcat the
environment. based servletsa widely
different effectivereader
instructinns fine to
servlet diretly
diusedfterent detauit
Assuming Tomcat is otthat tools that of
address
tonls streamline
and
to in usedTomcat you on of availahle serlets rather deply
apijar also in version
the
by the
changes a location
consut
Tomcat preparing servlet
Understand.
are
way nnly tor oach the
top- ditferent that trom here rewil to
thunder
e: version
level to and iset. in the hnr hat
is a the 1
Servlet
Simple A
simple</servlet-mapping>
To <servlet-mapping> Next, C:\apache-tomcat-8.5.31-
</servlet><servlet> lines For
Follow <servlet examples\WEB-
windows-x64\apache-tomcat-8.5.31\webapps\ INF Next,
examples\WEB-INF\classes won'
is t name this
directory Javac
/HelloServlet</url-pattern>
>HelloServlet</servlet-name>
become windows-x64\apache-tomcat-8.5.31\webapps\
-name
<servlet-class>Hell0servlet</servlet-class> C:\apache-tomcat-8.5.31- x64following includes it To
1.
>Hell0Servlet</servlet-name>
<servlet-name
instance,
in First,
the C:\apache-tomcat-8.5.31
Once make
file. to servlet.
ml
Create
this you
the \apache-tomcat-8.5.31\lib\servlet
add procedure have intomeans Alternatively,
[Link]
the familiar same wil section the copy aand you command [Link]
to putting
proper and The add assuming servlet's [Link]
general the create
[Link] have
the that
compile basic with that servlet's it
compiled you
ctory, any compiles can
following defines the name you file. into
steps the procedure files file
the key first class wil that directory
To a -windowsaccessible,
specify
and or keep a
are follow. -classpath the
file Tomcat servlet,
servlet
and the
example,
servlet lines mapping directories
the servlets: things first this
add for into update
following:
Source all
to under you -x64\apache-tomcat
servlet file
the concepts, the called the supplies
of to simple, must when
section following just Tomcat's -api. your
et's
code.
the
HelloServlet, "C:\apache-tomcat-8.5.31-wWindows
the
tofor example:
you CLASSPATH
we examples. [Link]
experiment its the
enable jar"
that compile
me Then, will directory: examples ownwebapps Tomcat
defines
example -8.5.3I\11b\servlet-api.
begin file
nd copy the
you in with in to
the by the the directory servlets. environment
will this find
building the
vlet's servlet following servlets.
add sample chapter it.
and For For
to and mappings: the
variable
class directory:
This use our
servlets. entering
example,
following
testing way, thpurposes
e
file iax
so
its the
Here you thot
a
Tomcat
StartStart
described
earlier.
as
directory HTML sent Program,
Content ServletkRequest
formulate
The
request. Overridden. creation
used
GenericServlet.
Inside as about Let's ("<B>Hello!
contains
ofpackage
more This
public ijmaporvax.t begiCrn, eate
throws
ServletResponse
DrintWriter
[Link]
[Link] "): response)
response.
public
[Link],
import * To Let
examine
us Tomcat. [Link] 2.
Nextto, Start.
mcat CompiltheSOurce
is the as call The is. of look class
createefile and
as client theHTML response the aHelloServlet, You a these IOException
Exception,
Servlet void a
tosecond This servlet. closely
MIME (); each o web
as described getWsetriCteontr( entType()
code as object.
method
need
later
setContentType
("text/html
pw
HelloServlet.
service
servlet
Compilea browser
ained source aspart source type argument
in the
for
s GenericServlet
supply For The
in the
program. First,
this
at =
named these of

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

println( the type ice functionality


Notinherited init( defines imports to
the
Code 35
betore HelloServlet tile Anythin)g browser of This that that and )
build
following
the
Introducing
vou is the enables is from HelloServlet [Link]
try tothe
in used
writotIen shouldHTTP provided titrhste destroy( that
to theproper write GenericServlet)
the simplifies program.
execute to response. servletargument via ), as Servlets g
[Link] some this interpret the whi c h learn
wi l
a lomcat stream cl
toient the apackage.
subclass
servlet. tile, simple the thisIn is may
be a is 1125
is
[Link]
PackageThe Servlet
TheAPI 126
that The specification.
and framework
implement API, servletTomcat.
servlet Tomcat packages. described the Two This /HelloServletStartStart
string [Link]
:8080/examples/servlets/servlet
Response ServletConfigServlet
ServletContext
ervletRequest Interface
ServletResponse [Link]
http:/ [Link]:8080/examples/servlets/servlet/HelloServlet
provided
this
are which
specification
supports
9 They
Servlet
The

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()

icServlet Class packafollowing


ge: The
hrows ServletException
vletException,
35-1 throws is obtain byAlsoInterface
defineddostrovl)
to These Servlet Servlet
All The
also
provide
are
ServletOutputStream
ServletException
Theprovided servlets UnavailableException
Let ServletinputGener
Stream
Exception invoked
initialization init( us
ServletResponse res) invoked
a methods examine
string ), that must
by service(
the with byshownallows
implement table
are that sethes
parameters.
Defined server. the
useful server. ),
and servlet a are interfaces
summariZes

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

Antead d should tserhe descr


vlet ibing servlet overrides
are declares
It more [Link] and that
tequest servlet the the detail
exceptiou trom is
becan objeunlct oaded.
is the method ) life life
Servlet(onfig
for for
provided
are

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

il lhe servlet trom by The Irom javax


a lo any the the ot methods to
servlet clrieethentquest cllet k.
A
This
servi) eserviet
t method nd
A).
ent ent
: servlet
or ilogt methmet
od hod
locn to
is
Table 1128
voidgetServerlnfo()
void
log(String
voids)String
getRealPath(Stringvpath)
StringString
getMimeType(String file)Object
getAttribute(String attr)Method
35-2
setAttribute(String
log(String ServletResponse ofThe
Interface The Several
ServletRequest The The Several
ServletContext
Interface
its
The The
Interface
Enumeration<String>
getServletName( String Method
getInitParameter(String
param)
String getServletContext()
) ServietContext
The The The
ServletConfig
Interface PART IV
Various ServletResponse
methods ServletRequest
of
ServletContext
getlnitParameterNames(
of
) methods
ServletConfig
s, its its
Throwable methods methods ApplyingJava
Methods are declared
attr, summarized
Defined interface interface
are
interface
Object e) interface are by
summarized summarized this
Context
by val)
in
enables
enables enables interfaceallows
Table
a
35-4. a in
servlet
a servlets
in servlet
are
servlet Table Table
passed Returns Returns
SetsWritesWrites
[Link] corresponds Returns
Returns
Description Returns Returnsparam.
parameter
names. named Returnspsummarized
Returns
Descri tion to
35-2. to
the to
35-3.
obtain
to
obtain the an the the
obtain
S s the the the formulate
attribute information
and to
the
torealMIME
value enumeration
name valuecontext
configurathere:ion
the
servlet the (i.e., information information of
of
specified stack relative type the
of
the the for
about
a
absolute) response this
trace log. server
of
invoking initialization
all
of
by for the path file. about
about servlet. data
attr e [Link]. path
attribute initialization
to for their servlet. when
to the that a a parameter
the client. client it
servlet named environmer is
value loaded.
reques
attr. Seve
log
Size)ServletOutputStream
ength(int
void void
IOException
throws Print
getOutputStream() StrinMethod
getCharacterEncodingl) g
Methods
Table
getServerPort()
35-3
StgetScheme(
int getRemoteHost()
getServerName() throws
getParameterNames()
St)Enumeration<String>
getProtocol(
BuferedReader
getReader(
String )String String IOException
ring getRemoteAddr() ring ) Stringl throws getContentLength(int )
String IOException
getParameter(String
phame) : SergetvlentputlnputStSretram(eam )getCContharact t ributStreing(Stg(, rOib)njaectg,Mre)thod
Sterinntg getSeArEncodi
ringYpe) IOException
throws getParameter ]
Writer
Various
get
Writer(
tType( )
Values(String
)
Defined
name)
by by

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

request. request. attribute


the
of
Introducing
Servlets
can server. scheme IllegalStateException that the by parameter of on is
thrown from
to to name. th e this be
type. [Link] write on response.
be of of has ) protocol. can
values
parameter the
determined. of
is this isused of
the the
been object. if that
request. A The thenamed

thrtvhiwnis t aster [Link] writeto


char client be associated getReader)
named null
on ftp). the client can value
URL host previously used be value
reqe
attr
IP to namespname. An
obievt it hin used name address. read with
is Iis
ars is tor has
1129
from values and
ar is encountered.
servlet illustrates
[Link],
It
aaddition. method indicates
that the
Employee
method data to also
and
listing.
afor servlet method data extends of POST
methods it
the OutputStream, parameter
this occurred. thea write namesthat following
In the readInputStream, by is HTTP
interfaces.
of
Theis implementedstream. which servlet labels
by to condition to which the
cycle signatures implemented offset. use action
that use read
UnavailableException, thethe the
IOException can the ServletException, develop a
lifeServletConfig exception can at end-of-stream by to in in of process
to the
basic The from
developer starting developer
data you defined One shown
is provided that
the available. inherited It allow will
is OutputStream.
output unavailable. fields. to
an here:throws is is Notice
servlet
of ItInputStream. placed servlet [Link].
[Link]
implementations
and
is
eand
servlet methods that
We page
text
shown an which request.
is methods size)areif is methods web button.
two the
Servlet
file Class a
ServletOutputStream first is
log, a -1 that ds, is identifies
log Class that is int bytes
ServletinputStream
The output Classes servlet
second A and
the It ofset, or
input extends
streammetho The Servlet
Parameters
Reading client
files. submit
theserver extends
stream stream. sizeread includes labels
Class implements to
GenericServlet
Theprovides appended the)
exceptions.
Thea a two
e) the int which bytes that in a URL
the Throwable classinput the buffer,
to
class
output
to Exception
println( occurred. contains
included
indicates interface for twoalso
to from intoof addition
ServletOutputStream The
class string addition
ServletInputStream code contains
is
an number an defines
[Link]
two in There
GenericServlet be provides ] array
readLine(byte[ providesand example
defined
Source
URL.
GenericServlet to bytes are
aappendvoid
log(String
s) s,
log(String
string In
In ) has It ServletRequest a
request.
read the actual print(
response. Servlet ServletException.
problem that [Link]
and is and parametersis HTML
Theservlet table
here:
shown the to buffer
to container the the
container is
method void is provided use. a othertag
servlet. sHere, client int The
returns definesThe
client servlet The defines <body>
<html>
The The Here, theira form
The The and the
a a a of
introducing
Serlets
1131
The You
is
) [Link]
listing
getParameterNames
a parameter
followingin
value="d
the
processed
The
ParameterNames();
value""
in are client.
shownTheThese
(pname);
Chapter
35 the
a
:8080examplealaarrlat
size-"25" size-"25"
[Link]
is names.
[Link]
output request,
pw names. values.
()[Link]
Parameter
servlet,
|Post
ParametersServlet' parameter
client
are
processvalue
method.
i
ion
;

(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

Method Enumeratior Succeeded,


The
Several
associ
ofthe
The
boolean boolean
String
t
information
msecGMT).
[Link]. information.
All client. a
state theheader
contains that
encoded
encodedurl.,processed url. be to
1970,to to code.
the returns should
thereturns
the
equal of
assume method the
contains
returns returns equalequal the
1,January to
header
value
response.
HTTP be
response
bebe Otherwise,
Otherwise,
shouldmust ) sendRedirect(
client. smessage
to
valuevalue
response other
store. in of
Some
must so, so, date andexample, ) included
and addCookie(
servlet lDIfurl. method. with with the
ID Ifurl. the withmidnight, this client address. machine.
HTTP session session
as url.
to and url.
header header header
for For
visits
url.
0dentified
as then
identified ccode ccode to a
field.
the the the version
of aby
generated of to
this
client sincethe the code on activities.
she
name, theis
ionnamedifDetermines ifDeterminespassed
the version user's
Descritocookie
ptiftrue method.
this
by by error error the
the to (milliseconds status stored or cookie
URL processed to to
field fieldfield he via following:
Returns modified
URLmodified
URLS the theRedirects HttpServletResponseuser's the
the is user time machine
Adds field the URLS the Sends Sends Adds AddsAddsSets COokie thatbrowser.
on
All tracking
the each for stored
a in in the
save cookie
A data
data
user's includes cookie
cookie. the are
for can this Theto cookies the
ato
msec) cookie
valuable sent the
value)value) by a enter [Link]
cookie cookie
of
ur)
encodeRedirectURL(String
String encapsulates is of of path
field)
containsHeader(String
boolean long Defined date
Stringint A to thatvalues
Java
Applying feld, Cookie
Class are
The [Link] each the the and
cookie)
addCookie(Cookie
void ur) encodeURL(String
String field, HttpServletResponse
response expiration
s) url)
sendRedirect(String
void setDateHeader(String Methods Cookies domain
String field,
setintHeader(String class online andfor of valueof
not can saved name
throwsIOException
throwsIOException
IOException throws setHeader(Stringcode)
setStatus(int
void names
c)sendError(int
void c, does
sendError(int Various Cookie an servletHTTP be The The The The
information.
visits
user
IVPART Thecan "
A the "
Method 35-6
Table
The userThe that
of
void void void void
134
in
ereinn esson
thas
context
attribute
It browseran the
machune ot values, constructoc developing
lIhe
Introducing
Servlets passed mate
ivnkingmidnight. and the header
unco the
current
name
names
milliseconds last
from
session from
the user's
the
these whenbydetined
attrihite the since
client attr with
the the in match here: the
shown toarguments used
it the

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

Method Object Enumerati getld()


Stringvoid )isNew(
boolean
)invalidate(
The
expiration is There
The
35-7
COokie
111
The
The
are
Servlets
class

long void Table


the
false to
returns attribute. added the
deleted.
isattribute
is request.
is This
Otherwise, HttpOnly [Link] request.
request.
request.
HttpOnlycookie OPTIONS
seconds). HttpOnlyto DELETE HEAD
cookie the GET
secure. the
has the which secure. HTTP HTTP HTTP HTTP
the
object. (in
is cookie thefalse,
age cookie then of after to Description an an an
thiscomment.
the
Returnsmaximum age an
domain.
the
Returns the C.
version.
Returns
the tO [Link] true, seconds flag
ishttpOnly
maximum v. to
v. Handles Handles Handles Handles
(contin
name.
the
Returns
path.
the the
Returns value.
the
Returns comment
domain p.
to security
to version
of
Description
copy
the
iftrue
if
true is
httpOnly of
path value
If
Returns
a Returns Returns Returns the the cookie. thenumber
the the the the HttpSe
SetsSets Sets Sets Sets Sets Sets
If Cookie
res)throws ServletExXception
IOException,
throws
ServletException
IOException,
HttpServletResponse voidres)throws
IOException
ServletExcep
req,HttpServletResp
doOptions(HttpSer
ServletException
req,
void HttpServletResponse
res)
doDelete(HttpServletRequest
res) doHead(HttpServletRequest
void
req throws
httpOnly)
setHttpOnly(boolean
void req,HttpServletResponse
IOException, by
by Defined
Defined (HttpServletRequest
secure)
Applying c)
(String secs)
setMaxAge(int
void
d)setDomain(String
void Methods Methods
(boolean v)setValue(String
voidv)setVersion(int
)getComment(
String isHttpOnly()
boolean p) void
)Domain( )getSecure(
boolean (String
)getName(
String
)getMaxAge(
int )Path( )getValue(
String
setComment
)getVersion(
int setSecure The The
)clone(
Object
IVPART setPath doGet
Method get get 35-8 Method Table
35-9
String String
void voidvoid Table void
1136
1137

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

Handles Handles Handles


an
(in
time
1970,
the1,
Returns
last
was
server

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

long svoid Table


ugarmade [Link] UKL
It the [Link]
:8080/examp
color=Red
servlet.
was dynamically
thesubmits
The the of
[Link]
thisselection update
part
string.
and
example: as
to
following is option
sent and that included query
arethe this
directory, response
red the
thethatobtain test are the as
("color"); request known
in requests HttpServlet
request, to the selects
shownto
HttpServletRequest ");
appropriate
steps display is
GET are
;[Link]()
;("text/html")
[Link] userserver
is GET
[Link] is:
[Link]
IOException
ServletException,
throws
theserunning. mark
value="Blue">Blue</option>
<option
value="Submit">
type=submit
<input HTTP formulated.
(HttpServletRequest
extends color theperform browser.
will HTTP
browser
the
the
thatto question
response)
HttpServletResponse to already an browser
any selected it Assume
copy
Then, for
*; ColorGetServlet
[Link]. ina the Parameters the
process
of then not
method Next, [Link], server.
is page the of
("<B>The
described. right
;[Link]. ;(color)
[Link] it
for to is
response = servlet. if web web theseservlet. from
overridden doGet Tomcat, color. web
code getParameter(
) [Link].*; =
color
pw
the the
point:sent the
[Link] thepreviously
();
PrintWriter completing
the to
source A void [Link] a Submit the
Display URL characters
class
Compile Start Select by other
to
is user.
</select> String sentThe
generated
<brs<br>
</body>Themethod
</html> public One
<torm> the import public
import
import as 1. 2. 3. 4. After is form.
file, that The
the by
1139
invoked 9t this
selection tosection
explicitly
for
the
form
Servlets page iris servlet/ColorPostSeri
is
servlet
web
listing.
Theto
sentthe
listing. obtain
previous
Introducing tag
[Link] are
A following form
parameter that
Thefiles. following the
request.
two
the
for
toHttpServletRequest
requests described
in
containsthe
35
Chapter POST in
action
parameter
8080/examples/servlets/
the
in POST HttpServlet
(extends
ColorPostServlet
request, ;("color")
[Link]
vletR("equest
t();egetxt/Whtrimtel"r)
shOwn formulated.
HWTTP in
example
defined
is method
the
and
[Link]
used,
shown
is
HTTP (Ht p|SerIOException
ServletException,
;
same
");
is:
assteps

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

You might also like