You are on page 1of 39

3

Servlets
3.1 Introduction to Servlets
Servlets are small programs that execute on the server side of a Web connection.
Servlets are server side applets. Servlets are loaded and executed by the Web
Server in the same manner as applets are loaded and executed by the web
browser.
Servlets are a replacement for CGI scripts and since Servlets are written in java,
they are server platform independent.
Servlet accepts a re!uest from a client via the Web "rowser, performs some
tas# and returns the results as shown below$

Web "rowser %%% &''( )e!uest %% Web Server %% Servlet

* %% &''( )esponse* %% * %%
'he following steps describe the basic flow while using Servlets$

a+ 'he client ma#es a re!uest via an &''(
b+ 'he Web Server receives the re!uest and sends it to the Servlet. If the Servlet
has not yet been loaded, the Web Server will load it into the ,-. and
execute it.
c+ 'he Servlet will receive the &''( re!uest and perform tas#s.
d+ 'he Servlet will return a response to the Web Server
e+ 'he Web Server will forward the response to the client.
3.2 Advantages of servlets over CGI:
CGI (Common Gateway Interface): 'his is one of the most common server
side solutions used to develop web applications. CGI application is an
independent module that receives re!uests from a Web Server. 'he application
process the data it receives and sends it bac# to the server, typically as &'./.
'he server then sends the same to the browser.
Advantages of servlets over CGI:
0. (erformance is significantly better. Servlets execute within the address
space of a Web server. Creating a separate process to handle each client
re!uest isn1t necessary as in CGI.
2. Servlets are platform%independent, because they are written in ,ava.
Several Web servers, from vendors such as Sun, 3etscape, and .icrosoft,
offer the Servlet (I. (rograms developed for this (I can be moved to
any of these environments without recompilation.
4. 'he ,ava Security .anager on the server enforces a set of restrictions to
protect the resources on a server machine. 5ou will see that some servlets
are trusted and others are untrusted.
6. Since servlets are written in java, the full functionality of the ,ava class
libraries is available to a servlet. It can communicate with applets,
databases, or other software via the soc#ets and ).I mechanisms.
3.3 Life cycle of Servlet (!ov2""#) (!ov2""$)(!ov % 2""&)
'he life cycle of a servlet is a simple object oriented design. servlet is
constructed and initiali7ed and then it services 7ero or more re!uests until the
service that it extends shuts down. t this point the servlet is destroyed and
garbage collected.
'hree methods are central to the life cycle of a servlet$ init( ), service( ), and
destroy( ).
'hey are implemented by every servlet and are invo#ed at specific times by the
server.
Consider that a user enters a 8niform )esource /ocator 98)/+ to a Web browser.
'he browser then generates an &''( re!uest for this 8)/ and sends it to the
appropriate server. 'hen, this &''( re!uest is received by the Web server. 'he
server maps this re!uest to a particular servlet. 'he servlet is dynamically
retrieved and loaded into the address space of the server.
1. init () 'et(od
When a service loads a servlet, it runs the servlet1s init method.
'his method is executed only once when the servlet is first loaded. It is not called
for each re!uest.
'he signature of the init 9+ method is $%
)u*lic void init (ServletConfig c) t(rows Servlet+,ce)tion.
'he init 9+ ta#es a ServletConfig as its parameter and you should save this object
so that it can be referenced later. 'he most common way of doing this is to have
the init 9+ method call super.init 9+ passing it the ServletConfig object.
If for some reason the servlet cannot initiali7e the resources necessary to handle
re!uests, the init 9+ method should throw a Servlet:xception.
2. service () 'et(od
'his method handles all the re!uests sent by the client. It cannot start servicing
until the init 9+ method has been executed.
:ach client1s re!uest has its call to the service method run in its own servlet
thread$ the method receives the client1s re!uest, and sends the client its response.
Servlets can run multiple service methods at a time.
'he signature of the service9+ method is$%
)u*lic void service(Servlet-e.uest re./ Servlet-es)onse res)t(rows
Servlet+,ce)tion/ 0ava.io.I1+,ce)tion
3. destroy () met(od
'his method signifies the end of a servlet;s life. When a service is being shut
down, it calls the servlet;s destroy method. 'his is where any resources that were
created in the init 9+ method should be cleaned up.
'he signature of the destroy9+ method is$%
)u*lic void destroy()
3.4 The Java Servlet Development Kit
'he ,ava Servlet <evelopment =it 9,S<=+ contains the class libraries that you
will need to create servlets.
utility #nown as the servletrunner is also included, which enables you to test
some of the servlets that you create.
5ou can download the ,S<= without charge from the Sun .icrosystems Web site
at 0ava.sun.com.
'he directory c:223sd42."22*in contains servletrunner.e,e. 8pdate your (ath
environment variable so that it includes this directory. 'he directory
c:223sd42."22li* contains 0sd4.0ar.
'his ,) file contains the classes and interfaces that are needed to build servlets.
3.5 5omcat $."
'omcat 6.> is currently used development #it. It contains the class libraries docs?
and run%time support that you will need to create and test servlets.
'omcat 6.> is generally installed in c$@(rogram Ailes@pache 'omcat 6.>@
'o start 'omcat, run startup.bat from c$@(rogram Ailes@pache 'omcat 6.>@bin@.
Bnce testing of servlet is finished, to stop tomcat run shutdown.bat.
'omcat contains servlet.jar. 'his jar file contains the classes and interfaces that
are needed to build servlet. c$@(rogram Ailes@pache 'omcat
6.>@common@lib@servet.jar.
8pdate classpath variable so that it includes above path.
3.# Ste)s for *uilding and testing a sim)le servlet
1. Create and compile the servlet source code.
2. Start servletrunnerC'omcat
3. Start web browser and re!uest the servet.
6or 3S78
Compile the source code and place the .class file in the directory named.
C:23S78 2."2e,am)le. 'his ensures that it is located by servletrunner.
1. Create and Com)ile t(e Servlet Source Code
Create a file named 9elloServlet.0ava that contains the following program$
import java.io.D?
import javax.servlet.D?
public class AirstServlet extends GenericServlet
E
public void service9Servlet)e!uest re!uest, Servlet)esponse response+
throws Servlet:xception, IB:xception
E
response.setContent'ype9FtextChtmlF+?
(rintWriter pw G response.getWriter9+?
pw.println9F*htmlH*headH*titleHAirst Servlet*CtitleH*CheadHF+?
pw.println9F*body bgcolorGyellowH*"HF+?
pw.println9F.y Airst ServletIF+?
pw.println9F*&)H*CbodyH*ChtmlHF+?
pw.close9+?
J
J
7escri)tion of t(e code:
'his program imports the 0ava,.servlet pac#age, which contains the classes
and interfaces re!uired to build servlets.
'he program defines 6irstServlet as a subclass of GenericServlet. 'he
GenericServlet class provides functionality that ma#es it easy to
handle re!uests and responses.
'he service( ) method handles re!uests from a client. 'he first argument is
a Servlet-e.uest object. 'his enables a servlet to read data that is provided
via the client re!uest. 'he second argument is an Servlet-es)onse object.
'his enables a servlet to formulate a response for the client.
'he setContent5y)e( ) establishes the .I.: type of the &''( response.
3ext, the get:riter( ) method obtains a ;rint:riter. nything written to
this stream is sent to the client as part of the &''( response. 'hen, )rintln( )
is used to write some simple &'./ source code as the &''( response.
2. Start t(e servletrunner <tility or 5omcat server
6or 3S78 2.":Bpen a command prompt window and type servletrunner to start
that utility. 'his tool listens on port K>K> for incoming client re!uests. Save the
file in examples directory.
6or 5omcat server:Go to start%Hprograms%Hpache 6.>%HStart 'omcat. It will
open another command prompt which starts a tomcat server. Compile the java
source file. nd save the class file in the C$@(rogram Ailes@pache Group@'omcat
6.0@webapps@examples@W:"%I3A@classes directory.
3. Start a :e* =rowser and -e.uest t(e Servlet
6or 3S78 2.":Start a Web browser and enter the 8)/ shown here$
http$CClocalhost$K>K>CservletCAirstServlet
lternatively, you may enter the 8)/ shown here$
http$CC02L.>.>.0$K>K>CservletCAirstServlet
6or 5omcat server: a Web browser and enter the 8)/ shown here$
http$CClocalhost$K>K>CexamplesCservletCAirstServlet
lternatively, you may enter the 8)/ shown here$
http$CC02L.>.>.0$K>K>CexamplesCservletCAirstServlet
3.7 Servlet Architecture (!ov2""&)
'he two pac#ages that ma#e up the servlet architecture are$
a+ javax.servlet % 'his contains the generic classes and interfaces that are
implemented and extended by all servlets.
b+ javax.servlet.http M 'hese contains classes that are extended when creating
&''( specific servlets.
t the heart of this rchitecture is the Servlet Interface, which provides the
framewor# for all servlets. 'he method in this are$
a+ init 9+
b+ getServletConfig 9+
c+ service 9+
d+ getServletInfo 9+
e+ destroy 9+
'he central abstraction in the ,S<= is the Servlet interface. ll servlets
implement this interface, either directly or, more commonly, by extending a class
that implements it such as &ttpServlet. 'he Servlet interface provides for methods
that manage the servlet and its communications with clients. Servlet writers
provide some or all of these methods when developing a servlet.
'hen we have the ServletConfig Interface, which provides the following methods
% getInit(arameter 9+
% getServletContext 9+
% getInit(arameter3ames 9+
'hen we have the GenericServlet, which implements both the above interfaces
and also the java.io.Seriali7able Interface.
Since Servlets do not have a main method, all the servlets must implement the
Servlet Interface. :very time a server receives a re!uest that points to a servlet, it
calls that servlet;s service 9+ method.
If you decide to extend the GenericServlet class, you must implement the service
9+ method. 'he GenericServlet.service 9+ method has been defines as abstract
method in order to force you to allow this framewor#. 'he service 9+ method
prototype is defines as follows $
public abstract void service 9Servlet)e!uest re!, Servlet)esponse res+
throws Servlet:xception, IB:xception
'he Servlet)e!uest object holds information that is being sent to the servlet and
Servlet)esponse object is where you place the data you want to send bac# to the
server.
When a servlet accepts a call from a client it receives two objects$ one is a
Servlet)e!uest and the other is a Servlet)esponse. 'he Servlet)e!uest class
encapsulates the communication from the client to the server, while the
Servlet)esponse class encapsulates the communication from the servlet bac# to
the client.
'he Servlet)e!uest interface allows the servlet access to information such as the
names of the parameters passed in by the client, the protocol 9scheme+ being used
by the client, and the names of the remote host that made the re!uest and the
server that received it. It also provides the servlet with access to the input stream,
ServletInputStream, through which the servlet gets data from clients that are using
application protocols such as the &''( (BS' and (8' methods. Subclasses of
Servlet)e!uest allow the servlet to retrieve more protocol%specific data. Aor
example, &ttpServlet)e!uest contains methods for accessing &''(%specific
header information.
'he Servlet)esponse interface gives the servlet methods for replying to the client.
It allows the servlet to set the content length and mime type of the reply, and
provides an output stream, ServletButputStream, and a Writer through which the
servlet can send the reply data. Subclasses of Servlet)esponse give the servlet
more protocol%specific capabilities. Aor example, &ttpServlet)esponse contains
methods that allow the servlet to manipulate &''(%specific header information.
'he classes and interfaces described above ma#e up a basic Servlet. &''(
servlets have some additional objects that provide session%trac#ing capabilities.
'he servlet writer can use these (Is to maintain state between the servlet and the
client that persists across multiple connections during some time period.
'hen we have the 9tt)Servlet, which extends the GenericServlet and has the
following methods$
a+ doGet 9+
b+ do(ost 9+
c+ do<elete 9+
d+ doBptions 9+
e+ do(ut 9+
f+ do'race 9+
g+ get/ast.odified 9+
h+ service 9+
8nli#e the GenericServlet, we do not have to implement the service 9+ method as
the &ttpServlet class has already implemented the same for us. 'he following is
the prototype
protected void service 9&ttpServlet)e!uest re!, &ttpServlet)esponse res+
throws Servlet:xception, IB:xception
'he &ttpServlet)e!uest and &ttpServlet)esponse are just extension of the
Servlet)e!uest and Servlet)esponse to provide &''( specific information stored
in them.
5(e 9tt)Servlet s(ould not override t(e service met(od. It overrides the doGet
9+ method to handle the G:' re!uests and the do(ost 9+ method to handle the
(BS' re!uests. n &ttpServlet can override both or any of these methods
depending on the way it needs to handle.
'he service 9+ method of the &ttpServlet handles the setup and dispatching to all
the doNNN methods, which is why it should not be overridden. 'he &ttpServlet
can override the do(ut 9+ and do<elete 9+ methods but generally they do not
override the do&ead 9+, do'race 9+ and doBptions 9+ methods. Aor these the
default implementations are sufficient.
When the &ttpServlet.service 9+ method is invo#ed, it reads the method type
stored in the re!uest and determines which method to invo#e based on this value.
'hese are the methods that you will want to override.
If the method type is G:', it will call doGet 9+ and if the method type is (BS', it
will call do(ost 9+. ll these have the same parameter as the service 9+ method.
In a G:' method, the data will be appended to the 8)/
'he main advantage of a Servlet is that it can gather data from the client and send
the same to the Web Server for further processing.
=asic 6low
0. 'his module will cover, how to write a simple servlet, which receives &'./
(BS' re!uest, process parameters, and format the &'./ that will be send bac#
to client.
2. 'he client will ma#e a re!uest to the server to load an &'./ page.
4. Cline side you need to specify a 8)/ , for the servlet to invo#e
6. 'he &''( Web service within the server will receive a re!uest.
O. 'he server will invo#e the servlet to perform the file ICB.
P. 'he &'./ page will be return to client, which can be display with Web browser.

=asic flow wit(in t(e servlet
0. 'he servlet is loaded, which is reside locally, or may be from a remote host.
2. 'he servlet is initialised with init9+ method.
4. Aor an &'./ (BS' re!uest, the do(ost9+ method is called on the servlet.
6. Servlet performs some type of processing and returns the response via an
output stream.
O. 'he Web service 9handling the &''( protocol+ may perform some other type
of processing, such as servlet chaining or servers%side includes.

3.6 5(e Servlet A;I
'wo pac#ages contain the code that is re!uired to build servlets$
o 0ava,.servlet and
o 0ava,.servlet.(tt).
'hese pac#ages are not part of the ,ava core pac#ages. 'hey are standard
extensions. 'o use these pac#ages we need to download and install ,S<= or
'omcat
3.&.1 5(e 0ava,.servlet ;ac4age
o 'he 0ava,.servlet pac#age contains a number of interfaces and classes that
establish the framewor# in which servlets operate.
o 'he following table summari7es the interfaces that are provided in this pac#age.
Interface 7escri)tion
Servlet <eclares life cycle methods for a servlet.
ServletConfig llows servlets to get initiali7ation parameters.
ServletContext :nables servlets to log events and access information
about their environment.
Servlet)e!uest 8sed to read data from a client re!uest.
Servlet)esponse 8sed to write data to a client response.
Single'hread.odel Indicates that the servlet is thread safe.
o 'he following table summari7es the classes that are provided in this pac#age$
Class 7escri)tion
GenericServlet Implements the Servlet and ServletConfig interfaces.
ServletInputStream (rovides an input stream for reading re!uests from a
client.
ServletButputStream (rovides an output stream for writing responses to a
client.
Servlet:xception Indicates that a servlet error occurred.
8navailable:xception Indicates that a servlet is permanently or temporarily
unavailable.
1. 5(e Servlet Interface
o ll servlets must implement the Servlet interface. It declares the init( ),
service( ), and destroy( ) methods that are called by the server during the life
cycle of a servlet.
o method is also provided that allows a servlet to obtain any initiali7ation
parameters.
o 'et(ods:
1. void destroy( ):Called when the servlet is unloaded.
2. ServletConfig getServletConfig():)eturns a ServletConfig object that
contains any initiali7ation parameters.
3. String getServletInfo( ):)eturns a string describing the servlet.
$. void init(ServletConfig sc) t(rows Servlet+,ce)tion:Called when the
servlet is initiali7ed.
>. void service(Servlet-e.uest req/ Servlet-es)onse res) t(rows
Servlet+,ce)tion/ I1+,ce)tion:Called to process a re!uest from a client.
2. 5(e ServletConfig Interface
o 'he ServletConfig interface allows a servlet to obtain configuration data
when it is loaded.
o 'et(ods:
1. ServletConte,t getServletConte,t( ):)eturns the context for this servlet.
2. String getInit;arameter(String param):)eturns the value of the
initiali7ation parameter named param.
3. +numeration getInit;arameter!ames( ):)eturns an enumeration of all
initiali7ation parameter names.
3. 5(e ServletConte,t Interface
'he ServletConte,t interface enables servlets to obtain information about
their environment.
'et(od:
1. 1*0ect getAttri*ute(String attr):)eturns the value of the server attribute
2. String get'ime5y)e(String file):)eturns the .I.: type of file.
3. String get-eal;at((String vpath):)eturns the real path that
corresponds to the virtual path vpath.
$. String getServerInfo( ):)eturns information about the server.
>. Servlet getServlet(String sname)t(rows Servlet+,ce)tion:)eturns
the servlet named sname.
#. +numeration getServlet!ames( ):)eturns an enumeration with the
names of servlets in the same namespace in the server.
&. void log(String s):Writes s to the server log.
?. void log(+,ce)tion e/ String s):Write s and the stac# trace for e to the
server log.
$. 5(e Servlet-e.uest Interface
'he Servlet-e.uest interface enables a servlet to obtain information about a
client re!uest.
'et(ods :%
1. String getAttri*ute(String attr):)eturns the value of the attribute named
attr.
2. String getC(aracter+ncoding( ):)eturns the character encoding of the
re!uest.
3. int getContent@engt(( ):)eturns the si7e of the re!uest.
$. String getContent5y)e( ):)eturns the type of the re!uest.
>. ServletIn)utStream getIn)utStream()t(rows I1+,ce)tion:)eturns a
ServletInputStream that can be used to read binary data from the re!uest.
#. String get;arameter(String pname):)eturns the value of the parameter
named pname.
&. +numeration get;arameter!ames():)eturns an enumeration of the
parameter names for this re!uest.
?. StringA B get;arameterCalues():)eturns an enumeration of the parameter
values for this re!uest.
D. String get;rotocol():)eturns a description of the protocol.
1". =uffered-eader get-eader() t(rows I1+,ce)tion:)eturns a buffered
reader that can be used to read text from the re!uest.
11. String get-eal;at((String vpath):)eturns the real path corresponding to the
virtual path vpath.
12. String get-emoteAddr():)eturns the string e!uivalent of the client I(
address.
13. String get-emote9ost():)eturns the string e!uivalent of the client host
name.
1$. String getSc(eme( ):)eturns the transmission scheme of the 8)/ used for
the re!uest 9e.g. FhttpF, FftpF+.
1>. String getServer!ame( ):)eturns the name of the server.
1#. int getServer;ort( ):)eturns the port number.
>. 5(e Servlet-es)onse Interface
'he Servlet-es)onse interface enables a servlet to formulate a response for a
client.
'et(od:
1. String getC(aracter+ncoding( ):)eturns the character encoding for the
response.
2. Servlet1ut)utStream get1ut)utStream( ) t(rows I1+,ce)tion:)eturns a
ServletButputStream that can be used to write binary data to the response.
3. ;rint:riter get:riter( ) t(rows I1+,ce)tion:)eturns a (rintWriter that can
be used to write character data to the response.
$. void setContent@engt((int size):Sets the content length for the response to size.
>. void setContent5y)e(String type):Sets the content type for the response to type.
#. 5(e Single5(read'odel Interface
'he Single5(read'odel interface is used to indicate that only a single thread
should execute the service( ) method of a servlet.
If a servlet implements this interface, the server creates several instances of it.
When a client re!uest arrives, it is sent to an available instance of the servlet.
Carious im)ortant classes in 0ava,.servlet )ac4age
1. 5(e GenericServlet Class
'he GenericServlet class provides implementations of the basic life cycle
methods for a servlet and is typically subclassed by servlet developers.
GenericServlet implements the Servlet and ServletConfig interfaces.
2. 5(e ServletIn)utStream Class
'he ServletIn)utStream class extends In)utStream. It is implemented by the
server and provides an input stream that a servlet developer can use to read the
data from a client re!uest.
method is provided to read bytes from the stream. Its syntax is shown here$
int read@ine(*yteAB *uffer/ int offset/ int siEe) t(rows I1+,ce)tion
&ere, buffer is the array into which size bytes are placed starting at offset. 'he
method returns the actual number of bytes read, or M0 if an end%of%stream
condition is encountered.
3. 5(e Servlet1ut)utStream Class
'he Servlet1ut)utStream class extends 1ut)utStream. It is implemented by
the server and provides an output stream that a servlet developer can use to write
data to a client response.
It also defines the )rint( ) and )rintln( ) methods, which output data to the
stream.
$. 5(e Servlet+,ce)tion Class
'he Servlet+,ce)tion class indicates that a servlet problem has occurred.
Constructors:
0. Servlet:xception9 +
2. Servlet:xception9String s+
&ere, s is a string that describes the problem.
>. 5(e <navaila*le+,ce)tion Class
'he <navaila*le+,ce)tion class extends Servlet+,ce)tion. It indicates that a
servlet is permanently or temporarily unavailable.
Constructors:
1. <navaila*le+,ce)tion(Servlet servlet/ String s)
2. <navaila*le+,ce)tion(int secs/ Servlet servlet/ String s)
&ere, servlet indicates which servlet is unavailable.
3.? -eading Servlet ;arameters
'he Servlet-e.uest class includes methods that allow you to read the names and
values of parameters that are included in a client re!uest.
'he following example contains two files$
o ;ost;arameters.(tm defines a Web page
o ;ost;arametersServlet.0ava defines a servlet.
+,am)le:
'he &'./ source code for ;ost;arameters.(tm is shown as$ It shows two labels
and two text fields. 'he form also includes a submit button. 3otice that the action
parameter of the form tag specifies a 8)/ of the servlet to process the &''( (BS'
re!uest.
Source code:
6orm1.(tml
*htmlH
*bodyH
*h0 alignGQcenterQHS'8<:3' <:'I/S *Ch0H
*form nameGFAorm0F methodGFpostF
actionGFhttp$CClocalhost$K>K>CservletC(ost(arametersServletFH
Student 3ame$*input typeGQtextQ nameGFt0F si7eGF2>F valueGFFH
*brH
ddress$ *input typeGQtextQ nameGFt2F si7eGF4>F valueGFFH
*brH
*input typeGsubmit valueGFSubmit AormFH
*CbodyH
*ChtmlH
o 'he source code for ;ost;arametersServlet.0ava is shown as$ 'he service9 + method
is overridden to process client re!uests. 'he get;arameter!ames( ) method returns
an enumeration of the parameter names. 'hese are processed in a loop. 5ou can see
that the parameter name and value are output to the client. 'he parameter value is
obtained via the get;arameter( ) method.
o Source code:
;ost;arametersServlet.0ava
import java.io.D?
import java.util.D?
import javax.servlet.D?
public class (ost(arametersServlet extends GenericServlet
E
public void service9Servlet)e!uest re!uest, Servlet)esponse response+
throws Servlet:xception, IB:xception
E
CC Get print writer
(rintWriter pw G response.getWriter9+?
CC Get enumeration of parameter names
:numeration e G re!uest.get(arameter3ames9+?
CC <isplay parameter names and values
while9e.has.ore:lements9++
E
String pname G 9String+e.next:lement9+?
pw.print9pname R F G F+?
String pvalue G re!uest.get(arameter9pname+?
pw.println9pvalue+?
J
pw.close9+?
J
J
Compile the servlet and perform these steps to test this example$
0. Start the servletrunner or start tomcat server.
2. :nter the following <-@ in browsers address bar to display the Web page in a
browser.
http$CClocalhost$K>K>CAorm0.html
4. :nter student name and address in the text fields.
6. Submit the Web page.
3. +,am)les on servlets
1. +,am)le1: Write a servlet that displays s!uare root and cube root of a number,
which will be received from a &'./ file. lso write the code for &'./ file. (!ov %
2""&)
Solution:
Ste)1: Create a html file to accept a number from user.
6orm1.(tml
*htmlH
*headH
*titleHServlet :xample%0*CheadH
*bodyH
*form methodGFpostF actionGFhttp$CClocalhost$K>K>CexamplesCservletCS!uareFH
:nter 3umber $ *input typeGFtextF nameGFnumberFH
*brH
*input typeGFsubmitF valueGQSubmit AormQH
*CformH
*CbodyH
*ChtmlH
Ste)2: Create a java file to accept a number from a html file and use .ath.s!rt
and .ath.cbrt to calculate s!uare root and cube root and display it on the browser.
S.uare.0ava
import java.s!l.D?
import java.io.D?
import javax.servlet.D?
public class S!uare extends GenericServlet
E
public void service9Servlet)e!uest re!, Servlet)esponse res+ throws
Servlet:xception, IB:xception
E
(rintWriter pw G res.getWriter9+?
String s G re!.get(arameter9FnumberF+?
int nGInteger.parseInt9s+?
double s!rtresult G .ath.s!rt9n+?
double cbrtresultG.ath.cbrt9n+?
pw.println9FS!uare root is F R s!rtresult+?
pw.println9FCube root is F R cbrtresult+?
J
J
+,am)le2:Write a servlet that accepts text SfriendThomeQ sent from on &'./
document and displays them on screen as S&elloI AriendT3ameQ. (!ov2""$)
Solution:
Ste)1:Create a html file to accept a friend name from user.
6orm2.(tml
*htmlH
*headH
*titleHServlet :xample%0*CheadH
*bodyH
*form methodGFpostF
actionGFhttp$CClocalhost$K>K>CexamplesCservletC(ost<emoFH
:nter your name$ *input typeGFtextF nameGFnameFH
*brH
*input typeGFsubmitF valueGQSubmit AormQH
*CformH
*CbodyH
*ChtmlH
Ste)2: Create a java file to accept a name from a html file and display it on the
browser as &elloI name.
;ost7emo.0ava
import java.io.D?
import javax.servlet.D?
public class (ost<emo extends GenericServlet
E
public void service9Servlet)e!uest re!, Servlet)esponse res+ throws
Servlet:xception, IB:xception
E
(rintWriter pw G res.getWriter9+?
String s G re!.get(arameter9FnameF+?
pw.println9F&ello F R s+?
pw.close9+?
J
J
+,am)le3:
Write a servlet that accepts a table name sent from an html page and retrieves the
content of that table from the database in a tabular form on the screen. (!ov%
2"">)
Solution:
Ste)1:Create a html file to accept a table name from user.
ta*le.(tml
*htmlH
*headH
*titleHServlet :xample%2*CtitleH
*CheadH
*bodyH
*form method G FpostF
ctionGFhttp$CClocalhost$K>K>CexamplesCservletC'able<emoFH
:nter 'able 3ame $ *input typeGFtextF nameGFtablenameFH
*brH
*input type G FsubmitFH
*CbodyH
*ChtmlH
Ste)2: Create a java file to accept a table name from a html file and display its
content on the browser in table format by using ,<"C (I.
5a*le7emo.0ava
import java.s!l.D?
import java.io.D?
import javax.servlet.D?
import javax.swing.D?
public class 'able<emo extends GenericServlet
E
public void service9Servlet)e!uest re!, Servlet)esponse res+ throws
Servlet:xception, IB:xception
E
try
E
Class.for3ame9Fsun.jdbc.odbc.,dbcBdbc<riverF+?
Connection con G
<river.anager.getConnection9Fjdbc$odbc$empF+?
Statement st G con.createStatement9+?
String s G re!.get(arameter9FtablenameF+?
)esultSet rs G st.executeUuery9FSelect D from FRs+?
(rintWriter pw G res.getWriter9+?
pw.print9F*table borderG121HF+?
while9rs.next9++
E
pw.print9F*trH*tdHF+?
pw.print9rs.getInt90+RF*CtdH*tdHF+?
pw.print9rs.getString92+RF*CtdH*tdHF+?
pw.print9rs.getInt94+RF*CtdH*CtrHF+?
J
pw.print9F*CtableHF+?
pw.close9+?
J
catch9SU/:xception e+
E
pw.println9F<atebase :rrorFRe.get.essage9++?
J
catch9:xception e+
E
pw.println9FGeneral :rrorFRe.get.essage9++?
J
J
J
3.D -eading InitialiEation ;arameters
5ou can provide initiali7ation parameters to a servlet, which is used to open files,
create database connections, or perform other actions.
'his information can be accessed in two ways$
o 'he init( ) method receives a ServletConfig object as its argument. 'his object
provides methods that enable you to read the initiali7ation parameters.
o 'he getServletConfig() method declared by the Servlet interface returns a
ServletConfig object.
'he servletrunner utility defines the initiali7ation parameters for servlets in a file
named servlet.)ro)erties. 'he default location for this file is the
c:220sd42."22e,am)les directory.
+,am)le:
o 'his example contains two files$ servlet.)ro)erties and InitServlet.0ava. 'he file
servlet.)ro)erties defines two properties for a servlet$
0. servlet.name.code$%which enables you to associate a name with the class
that contains the code for the servlet.
2. servlet.name.initargs$%which enables you to define a se!uence of comma
delimited parameter names and values.
o 'he syntax of each parameter name and value is the following$
)name F )value
where pname is the parameter name, and pvalue is the parameter value.
o In the following servlet.)ro)erties, you can see that the name of the servlet is
initservlet. Its code is located in the class InitServlet.
o 'wo initiali7ation parameters, named name and age, have the values -ipul and 6O,
respectively.
servlet.initservlet.codeGInitServlet
servlet.initservlet.initrgsG@
nameG-ipul,@
ageG6O
o 'he source code for InitServlet.0ava is shown as$ 'he getServletConfig( ) method is
called to obtain a ServletConfig object. 'he getInit;arameter( ) method is used to
obtain the values for the two initiali7ation parameters. 'hese are then written to the
&''( response.
import java.io.D?
import javax.servlet.D?
public class InitServlet extends GenericServlet
E
public void service9Servlet)e!uest re!uest, Servlet)esponse response+
throws Servlet:xception, IB:xception
E
CC Get ServletConfig object
ServletConfig s G getServletConfig9+?
CC <isplay two initiali7ation arguments
response.setContent'ype9FtextChtmlF+?
(rintWriter p G response.getWriter9+?
p.println9F*"H3ame$ F R
s.getInit(arameter9FnameF++?
p.println9F*brHge$ F R
s.getInit(arameter9FageF++?
p.close9+?
J
J
o 'o test this example, re!uest for (tt):GGlocal(ost:?"?"GservletGinitservlet in your
browser.
o Butput should appear as follows$
name$ -ipul
age$ 6O
o 'he 8)/ must contain the name that is assigned to this servlet in the
servlet.)ro)erties file, not the name of the servlet class.
3.1" 5(e 0ava,.servlet.(tt) ;ac4age
o 'he 0ava,.servlet.(tt) pac#age contains several interfaces and classes which ma#es
o it easy to build servlets that wor# with &''( re!uests and responses.
o 'he following table summari7es the interfaces that are provided in this pac#age$
Interface 7escri)tion
&ttpServlet)e!uest :nables servlets to read data from an &''( re!uest.
&ttpServlet)esponse :nables servlets to write data to an &''( response.
&ttpSession llows session data to be read and written.
&ttpSession"inding/istener Informs an object that it is bound to or unbound from
a session.
&ttpSessionContext llows sessions to be managed.
o 'he following table summari7es the classes that are provided in this pac#age.
Class 7escri)tion
Coo#ie llows state information to be stored on a client
machine.
&ttpServlet (rovides methods to handle &''( re!uests and
responses.
&ttpSession"inding:vent Indicates when a listener is bound to or unbound from
a session value.
&ttp8tils <eclares utility methods for servlets.
1. 5(e 9tt)Servlet-e.uest Interface
o 'he 9tt)Servlet-e.uest interface enables a servlet to obtain information about a
client re!uest.
o 'et(ods:
1. String getAut(5y)e():)eturns authentication scheme.
2. Coo4ieA B getCoo4ies():)eturns an array of the coo#ies in this re!uest.
3. long get7ate9eader(String field):)eturns the value of the date header
field named field.
$. String get9eader(String field):)eturns the value of the header field
named field.
>. +numeration get9eader!ames():)eturns an enumeration of the header
names.
#. int getInt9eader(String field):)eturns the int e!uivalent of the header
field named field.
&. String get'et(od():)eturns the &''( method for this re!uest.
?. String get;at(Info( ):)eturns any path information that is located after
the servlet path and before a !uery string of the 8)I.
D. String get;at(5ranslated( ):)eturns any path information that is located
after the servlet path and before a !uery string of the 8)I,
1". String getHueryString( ):)eturns any !uery string in the 8)I.
11. String get-emote<ser( ):)eturns the name of the user who issued this
re!uest.
12. String get-e.uestedSessionId():)eturns the I< of the session.
13. String get-e.uest<-I():)eturns that part of the 8)I to the left of any
!uerystring.
1$. String getServlet;at(():)eturns the part of the 8)I that identifies the
servlet.
1>. 9tt)Session getSession(*oolean new):If new is true, creates and returns
a session for this re!uest. Btherwise, returns the existing session for this
re!uest.
1#. *oolean is-e.uestedSessionId6romCoo4ie():)eturns true if a coo#ie
contains the session I<.
1&. *oolean is-e.uestedSessionId6rom<rl():)eturns true if the 8)/
contains the session I<.
1?. *oolean is-e.uestedSessionIdCalid():)eturns true if the re!uested
session I< is valid in the current session context.
2. 5(e 9tt)Servlet-es)onse Interface
o 'he 9tt)Servlet-es)onse interface enables a servlet to formulate an &''(
response to a client.
o 'here are several constants defined, which correspond to the different status codes
that can be assigned to an &''( response. Aor example, SCI18 indicates that
the &''( re!uest succeeded, and SCI!15I61<!7 indicates that the re!uested
resource is not available.
o 'et(ods:
1. void addCoo4ie(Coo4ie cookie):dds cookie to the &''( response.
2. *oolean contains9eader(String field):)eturns true if the &''( response
header contains a field named field.
3. String encode<-@(String url):<etermines whether the session I< must be
encoded in the 8)/ identified as url.
$. String encode-edirect<rl(String url):<etermines whether the session I<
must be encoded in the 8)/ identified as url.
>. void send+rror(int c) t(rows I1+,ce)tion:Sends the error code c to the
client.
#. void send+rror(int c/ String s) t(rows I1+,ce)tion :Sends the error code
c and message s to the client.
&. void send-edirect(String url) t(rows I1+,ce)tion:)edirects the client to
url.
?. void set7ate9eader(String field/long msec):dds field to the header with
date value e!ual to msec
D. void set9eader(String field/ String value):dds field to the header with
value e!ual to value.
1". void setInt9eader(String field/ int value):dds field to the header with
value e!ual to value.
11. void setStatus(int code)$% Sets the status code for this response to code.
12. void setStatus(int code/ String s):Sets the status code and message for this
response to code and s.
3. 5(e 9tt)Session Interface
'he 9tt)Session interface enables a servlet to read and write the state
information that is associated with an &''( session.
'et(ods:
1. long getCreation5ime():)eturns the time when this session was created.
2. String getId():)eturns the session I<.
3. long get@astAccessed5ime():)eturns the time when the client last made a
re!uest for this session.
$. 9tt)SessionConte,t getSessionConte,t( ):)eturns the context associated
with this session.
>. 1*0ect getCalue(String name):)eturns the object bound to name. )eturns
null
if no such binding exists.
#. StringAB getCalue!ames( ):)eturns the names of all objects that are bound
in the session.
&. void invalidate( ):Invalidates this session and removes it from the context.
?. *oolean is!ew( ):)eturns true if the server created the session and it has not
yet been accessed by the client.
D. void )utCalue(String name/ 1*0ect obj):"inds obj to name in this session.
1". void removeCalue(String name):)emoves the object bound to name from
the session.
$. 5(e 9tt)Session=inding@istener Interface
'he 9tt)Session=inding@istener interface is implemented by objects that need
to be notified when they are bound to or unbound from an &''( session.
'et(ods:
1. void value=ound(9tt)Session=inding+vent e)
2. void value<n*ound(9tt)Session=inding+vent e)
&ere, e is the event object that describes the binding.
$. 5(e 9tt)SessionConte,t Interface
'he 9tt)SessionConte,t interface enables a servlet to access sessions that are
associated with it.
'et(ods:
1. +numeration getIds( ):'his is declared to return an enumeration of all
the session I<s in the context.
2. 9tt)Session getSession(String id):maps a session I< to an 9tt)Session
object
Carious im)ortant classes in 0ava,.servlet.(tt) )ac4age
1. 5(e Coo4ie Class (!ov % 2"">) (!ov2""#)(!ov2""$)
&''( is a stateless protocol, so when you re!uest a page, the server does not
#now who you are, what you entered on a form etc.
.aintaining state means remembering information while the user moves from
page to page within a web site. With this information in hand, you can set user
preferences, fill in default form values etc.
Coo#ies are short pieces of data sent by web servers to the client browser. 'he
coo#ies are saved to client;s hard dis# in the form of small text file. Coo#ies help
the web servers to identify web users, by this way server trac#s the user.
'he Coo4ie class encapsulates a coo#ie. Coo#ies are valuable for trac#ing user
activities. Aor example, assume that a user visits an online boo#store. coo#ie
can save the user1s name, address, and other information.
servlet can write a coo#ie to a user1s machine via the addCoo4ie( ) method of
the 9tt)Servlet-es)onse interface.
'he data for that coo#ie is then included in the header of the &''( response that
is sent to the browser
'he names and values of coo#ies are stored on the user1s machine. Some of the
information that is saved includes the coo#ie1s$
a. 5(e !ame of t(e coo4ie
*. 5(e Calue of t(e coo4ie
c. 5(e e,)iration date of t(e coo4ie: 'he expiration date determines when
this coo#ie is deleted from the user1s machine.
d. 5(e domain and )at( of t(e coo4ie: determine when it is included in
the header of an &''( re!uest. If the user enters a 8)/ whose domain
and path match these values, the coo#ie is then supplied to the Web server.
Btherwise, it is not.
Constructor$%
Coo4ie(String name/ String value):'he name and value of the coo#ie are
supplied as arguments to the constructor.
'et(ods of t(e Coo4ie class are
1. 1*0ect clone( ):)eturns a copy of this object.
2. String getComment( ):)eturns the comment.
3. String get7omain( ):)eturns the domain.
$. int get'a,Age( ):)eturns the age 9in seconds+.
>. String get!ame( ):)eturns the name.
#. String get;at(( ):)eturns the path.
&. *oolean getSecure( ):)eturns true if the coo#ie is secure. Btherwise, returns
false.
?. String getCalue( ):)eturns the value.
D. int getCersion( ):)eturns the version.
1". void setComment(String c):Sets the comment to c.
11. void set7omain(String d):Sets the domain to d.
12. void set'a,Age(int secs):Sets the maximum age of the coo#ie to secs. 'his
is the number of seconds after which the coo#ie is deleted.
13. void set;at((String p):Sets the path to p.
1$. void setSecure(=oolean secure):Sets the security flag to secure.
1>. void setCalue(String v):Sets the value to v.
1#. void setCersion(int v):Sets the version to v.
+,am)le using coo4ies:
/et1s develop a servlet that illustrates how to use coo#ies. 'his example contains three
files, as$
0. AddCoo4ie.(tml: llows a user to specify a value for the coo#ie named
Vcoo#iename;
2. ;rocessCoo4ie.0ava: (rocesses the submission of ddCoo#ie.html
4. GetCoo4ies.0ava:<isplays coo#ie values on browser window.
AddCoo4ie.(tml:
'his page contains a text fields in which a value can be entered. 'he page also
includes a submit button. When this button is pressed, the value in the text field is
sent to ;rocessCoo4ie.0ava via an &''( (BS' re!uest.
*htmlH
*bodyH
*centerH
*form nameGFArm0F methodGFpostF
actionGFhttp$CClocalhost$K>K>CservletC(rocessCoo#ieFH
*&4HCoo#ies :xample*C&4H
*(HCreate a coo#ie to send to your browser$
*")H
3ame of the Coo#ie$ *I3(8' typeGQtextQ nameGcoo#iename lengthGF2>FH
*")H
*I3(8' typeGsubmit valueGFSubmit UueryFH
*CAB).H
*C(H
*C"B<5H
*C&'./H
;rocessCoo4ie.0ava :
'his servlet gets the values of the parameters named Fcoo#ienameF. It then creates
a Coo4ie object that has the name F.yCoo#ieF and contains the value of the
parameter. 'he coo#ie is then added to the header of the &''( response via the
addCoo4ie( ) method. feedbac# message is then written to the browser.
import java.io.D?
import javax.servlet.D?
import javax.servlet.http.D?
public class (rocessCoo#ie extends &ttpServlet
E
public void do(ost9&ttpServlet)e!uest re!uest, &ttpServlet)esponse
response+ throws Servlet:xception, IB:xception
E
CC Get parameter from &''( re!uest
String cname G re!uest.get(arameter9Fcoo#ienameF+?
CC Create coo#ie
Coo#ie coo#ie G new Coo#ie9F.yCoo#ieF, cname+?
CC dd coo#ie to &''( response
response.addCoo#ie9coo#ie+?
CC Write output to browser
response.setContent'ype9FtextChtmlF+?
(rintWriter pw G response.getWriter9+?
pw.println9F*"H.yCoo#ie has been set toF+?
pw.println9cname+?
pw.close9+?
J
J
GetCoo4ies.0ava:
'his servlet invo#es the getCoo4ies( ) method to read any coo#ies that are
included in the &''( G:' re!uest. 'he names and values of these coo#ies are
then written to the &''( response.Aor this, it uses the get!ame( ) and
getCalue( ) method.
import java.io.D?
import javax.servlet.D?
import javax.servlet.http.D?
public class GetCoo#ies extends &ttpServlet
E
public void doGet9&ttpServlet)e!uest re!uest, &ttpServlet)esponse
response+ throws Servlet:xception, IB:xception
E
CC Get coo#ies from header of &''( re!uest
Coo#ieWX coo#ies G re!uest.getCoo#ies9+?
CC <isplay these coo#ies
response.setContent'ype9FtextChtmlF+?
(rintWriter pw G response.getWriter9+?
pw.println9F*"HF+?
for9int i G >? i * coo#ies.length? iRR+
E
String name G coo#iesWiX.get3ame9+?
String value G coo#iesWiX.get-alue9+?
pw.println9Fname G F R name R F? value G F R value+?
J
pw.close9+?
J
J
Compile the servlet and perform these steps$
0. Start the servletrunner or 5omcat server.
2. <isplay ddCoo#ie.html in a browser.
4. :nter a value for coo4iename.
6. Submit the Web page.
fter you complete these steps, observe that a feedbac# message is displayed by the
browser.
3ext, re!uest the following 8)/ via the browser$
http$CClocalhost$K>K>CexamplesCservletCGetCoo#ies
'he name and value of the coo#ie are displayed in the browser.
2. 5(e 9tt)Servlet Class
'he 9tt)Servlet class extends GenericServlet.
It is used when developing servlets that receive and process &''( re!uests.
'et(ods:
0. void do7elete(9tt)Servlet-e.uest req/ 9tt)Servlet-es)onse res) t(rows
I1+,ce)tion/ Servlet+,ce)tion :(erforms an &''( <:/:':.
2. void doGet(9tt)Servlet-e.uest req/9tt)Servlet-es)onse res)t(rows
I1+,ce)tion/ Servlet+,ce)tion:(erforms an &''( G:'.
4. void do1)tions(9tt)Servlet-e.uest req/ 9tt)Servlet-es)onse res) t(rows
I1+,ce)tion/ Servlet+,ce)tion:(erforms an &''( B('IB3S.
6. void do;ost(9tt)Servlet-e.uest req/ 9tt)Servlet-es)onse res) t(rows
I1+,ce)tion/ Servlet+,ce)tion:(erforms an &''( (BS'.
O. void do;ut(9tt)Servlet-e.uest req/ 9tt)Servlet-es)onse res) t(rows
I1+,ce)tion/ Servlet+,ce)tion:(erforms an &''( (8'.
P. void do5race(9tt)Servlet-e.uest req/ 9tt)Servlet-es)onse res)
t(rowsI1+,ce)tion/ Servlet+,ce)tion:(erforms an &''( ')C:.
L. void service(9tt)Servlet-e.uest req/ 9tt)Servlet-es)onse res) t(rows
I1+,ce)tion/ Servlet+,ce)tion:Called by the server when an &''( re!uest
arrives for this servlet. 'he arguments provide access to the &''( re!uest and
response, respectively.
K. long get@ast'odified(9tt)Servlet-e.uest req):)eturns the time 9in
milliseconds since midnight, ,anuary 0, 0YL>, 8'C+ when the re!uested resource
was last modified.
3.5(e 9tt)Session=inding+vent Class
'he 9tt)Session=inding+vent class extends +vent1*0ect.
It is generated when a listener is bound to or unbound from a value in an
9tt)Session object.
Constructor:
&ttpSession"inding:vent9&ttpSession session, String name+
&ere, session is the source of the event, and name is the name associated with the
object that is being bound or unbound.
'et(ods:
a. String get!ame( ):'his method obtains the name that is being bound or
unbound.
*. 9tt)Session getSession( ):'his method obtains the session to which the
listener is being bound or unbound.
$. 5(e 9tt)<tils Class
'he 9tt)<tils class provides three static methods, summari7ed next, that are
useful for servlet developers$
'et(od:
1. static String=uffer get)e!uest8)/9&ttpServlet)e!uest req+:)eturns the 8)/
that was issued by the client.
2. static 9as(ta*le )arse;ost7ata(int size/ ServletIn)utStream sis):)eturns a
hash table that contains #eyCvalue pairs. 'his method is useful for parsing &''(
forms that are submitted via the (BS' method. 'he first argument is the number
of bytes in the input stream. 'he second argument is the input stream.
3. static 9as(ta*le )arseHueryString(String s):(arses the !uery string and
returns a hash table containing the #eyCvalue pairs.
3.11 9andling 955; -e.uests and -es)onses
'he 9tt)Servlet class provides speciali7ed methods that handle the various types
of &''( re!uests.
9tt)Servlet, which extends the GenericServlet and has the following methods$
0. doGet 9+
2. do(ost 9+
4. do<elete 9+
6. doBptions 9+
O. do(ut 9+
P. do'race 9+
L. get/ast.odified 9+
K. service 9+
'he G:' and (BS' methods are commonly used when handling
form input. 'herefore, this section presents examples of these cases.
'here are essentially two ways to pass information from your web browser to a
servlet or CGI program.
o G:'
o (BS'
G+5: In this method servlet encodes the information in the 8)/ of your client1s
re!uest. In this case, the web browser encodes the parameters and appends them
to the end of the 8)/ string. 'he server decodes them and passes them to the
application.
;1S5$%&ere, client encodes the information and sends it as a stream to the
program, which decodes it. (osting can be used to upload large amounts of form
data or other data, including files.
'he primary difference between GET and POST is that they can see the GET
information in the encoded 8)/ shown in their web browser. 'his can be useful
because the user can cut and paste that 8)/ 9the result of a search, for example+
and mail it to a friend or boo#mar# it for future reference. POST information is not
visible to the user and ceases to exist after it1s sent to the server. 'his behavior
goes along with the protocol1s perspective that GET and POST are intended to have
different semantics.
3.11.1 9andling 955; G+5 -e.uests
o 'his section develops a servlet that handles an &''( G:' re!uest.
o 'he example contains two files$ Get;aram.(tml defines a Web page, and
Get;aramServlet.0ava defines a servlet.
+,am)le:
Get;aram.(tml:
It defines a form that contains a two labels and two textfields and a
submit button. 3otice that the action parameter of the form tag specifies a 8)/. 'he
8)/ identifies a servlet to process the &''( G:' re!uest.
Get;aram.(tml
*htmlH
*headH
*titleHget parameter servlet *CtitleH
*CheadH
*body bgcolorGpin#H
*form methodGget
actionGFhttp$CClocalhost$K>K>CexamplesCservletCGet(arameterServletFH
*tableH
*trH
*tdH*bHstudent name$*CbH*CtdH
*tdH*input typeGFtextF nameGFnameF si7e G 2O valueGF FH*CtdH
*CtrH
*trH
*tdH*bHroll no$*CbH*CtdH
*tdH*input typeGFtextF nameGFrollnoF si7e 0> valueGF FH*CtdH
*CtrH
*CtableH
*input typeGFsubmitF valueGQsubmit this formQH
*CformH
*CbodyH
*ChtmlH
Get;aramServlet.0ava:
'his servlet uses doGet( ) method that is overridden to process any &''( G:'
re!uests that are sent to this servlet. It uses the get;arameter( ) method of
9tt)Servlet-e.uest to obtain the selection that was made by the user.
'he 4 methods used to retrieve re!uest parameters are the Servlet)e!uest;s
a) +numeration get;arameter!ames ()
*) String get;arameter (String name)
c) String AB get;arameterCalues (String name)
% 'he get;arameter!ames () returns the parameter names for the re!uest as an
enumeration of strings or an empty enumeration if there are no parameters. It is
used as a supporting method to get(arameter 9+.
% When you have the enumerated list of parameter names, you can iterate over
them, calling get;arameter () with each name in the list.
% 'he get(arameter 9+ returns a string containing the single value of the specified
parameter or null if the parameter is not contained in the re!uest. 'his method
should be used only if you are sure that the re!uest contains only one value for the
parameter. If the parameter has multiple values, you should use
get;arameterCalues ().
'he get;arameterCalues () returns the value of the specified parameter as an
array of strings or null if the named parameter does not exist in the re!uest.
import javax.servlet.D?
import java.io.D?
import java.util.D?
public class Get(arameterServlet extends &ttpServlet
E
public void doGet9&ttpServlet)e!uest re!, &ttpServlet)esponse res+
throws Servlet:xception, IB:xception
E
res.setContent'ype9FtextChtmlF+?
CC then get the writer and write the response data
(rintWriter out G res.getWriter9+?
CC get the enumeration of parameter names
:numeration e G re!.get(arameter3ames9+?
CC display the parameter names and values
while 9e.has.ore:lements9++
E
String pnameG9String+e.next:lement9+?
out.print9pnameRF G F+?
String pvalueGre!.get(arameter9pname+?
out.println9pvalue+?
J
out.close9+?
J
J
o Compile the servlet and then perform these steps to test this example$
0. Start the servletrunner.
2. <isplay the Web page in a browser.
4. Insert the data in a web page.
6. Submit the Web page.
o fter completing these steps, the browser displays the response that is dynamically
generated by the servlet.
o (arameters for an &''( G:' re!uest are included as part of the 8)/ that is sent to
the Web server. 'he 8)/ sent from the browser to the server is the following$
http$CClocalhost$K>K>CexamplesCservletCGet(aramServletZnameGrchana[rollnoG6O
o 'he characters to the right of the !uestion mar# are #nown as the query string.
3.11.2 9andling 955; ;1S5 -e.uests
o 'his section develops a servlet that handles an &''( (BS' re!uest.
o 'he example contains two files$ ;ost;aram.(tml defines a Web page, and
;ost;aramServlet.0ava defines a servlet.
;oat;aram.(tml
It defines a form that contains a select element and a submit button. 3otice that the action
parameter of the form tag specifies a 8)/. 'he 8)/ identifies a servlet to process the
&''( (BS' re!uest.
*htmlH
*bodyH
*centerH
*form nameGFAorm0F
methodGFpostF
actionGFhttp$CClocalhost$K>K>CservletC(ost(aramServletFH
*"HColor$*C"H
*select nameGFflavorF si7eGF0FH
*option valueGF"utterscotchFH"utterScotch*CoptionH
*option valueGF-anillaFH-anilla*CoptionH
*option valueGF"lac#forestFH"lac#Aorest*CoptionH
*CselectH
*brH*brH
*input typeGsubmit valueGFSubmitFH
*CformH
*CbodyH
*ChtmlH
;ost;aramServlet.0ava
'he servlet uses do;ost( ) method that is overridden to process any &''( (BS' re!uests
that are sent to this servlet. It uses the get;arameter( ) method of 9tt)Servlet-e.uest
to obtain the selection that was made by the user.
import java.io.D?
import javax.servlet.D?
import javax.servlet.http.D?
public class (ost(aramServlet extends &ttpServlet
E
public void do(ost9&ttpServlet)e!uest re!uest, &ttpServlet)esponse response+
throws Servlet:xception, IB:xception
E
String color G re!uest.get(arameter9FflavorF+?
response.setContent'ype9FtextChtmlF+?
(rintWriter pw G response.getWriter9+?
pw.println9F*"H'he selected Alavor is$ F+?
pw.println9flavor+?
pw.close9+?
J
J
o Compile the servlet and then test it by performing the same steps described in the
previous section.
o 3ote that parameters for an &''( (BS' re!uest are not included as part of the 8)/
that is sent to the Web server. In this example, the 8)/ sent from the browser to the
server is the following$
http$CClocalhost$K>K>CservlerC(ost(aramServlet
'he parameter names and values are sent in the body of the &''( re!uest.
3.12 Session 5rac4ing (!ov % 2""&) (!ov2""#) (!ov2""$)
&''( is a stateless protocol, which means that each re!uest is independent of the
previous one. &owever, in some applications, it is necessary to save state
information so that information can be collected from several interactions
between a browser and a server.
'here are a number of problems that arise from the fact that &''( is a FstatelessF
protocol. In particular, when you are doing on%line shopping, it is a real
annoyance that the Web server can1t easily remember previous transactions. 'his
ma#es applications li#e shopping carts very problematic$ when you add an entry
to your cart, how does the server #now what1s already in your cartZ :ven if
servers did retain contextual information, you1d still have problems with e%
commerce.
'here are three typical solutions to this problem.
o <sing clientside coo4ies or <-@ rewriting$%. Client%side coo#ies are a
standard &''( mechanism for getting the client web browser to cooperate
in storing state information for you. coo#ie is basically just a
nameCvalue attribute that is issued by the server, stored on the client, and
returned by the client whenever it is accessing a certain group of 8)/s on
a specified server. Coo#ies can trac# a single session or multiple user
visits.
o 8)/ rewriting appends session%trac#ing information to the 8)/, using
GET%style encoding or extra path information. 'he term FrewritingF applies
because the server rewrites the 8)/ before it is seen by the client and
absorbs the extra information before it is passed bac# to the servlet. In
order to support 8)/ rewriting, a servlet must ta#e the extra step to
encode any 8)/s it generates in content 9e.g., &'./ lin#s that may
return to the page+ using a special method of the HttpServletResponse
object.
o 9idden form fields. &'./ forms have an entry that loo#s li#e the
following$ <INPUT
TYPE="HIDDEN" NAME="session" VALUE=""!. 'his
means that, when the form is submitted, the specified name and value are
included in the GET or POST data. 'his can be used to store information
about the session. &owever, it has the major disadvantage that it only
wor#s if every page is dynamically generated, since the whole point is that
each session has a uni!ue identifier.
Servlets provide a technical solution$ the 9tt)Session A;I. 'his is a high%level
interface built on top of coo#ies or 8)/%rewriting.
'he servlet container uses this interface to create a session between an &''(
client and an &''( server. 'he session persists for a specified time period, across
more than one connection or page re!uest from the user. session usually
corresponds to one user, who may visit a site many times.
'his interface allows servlets to
o -iew and manipulate information about a session, such as the session
identifier, creation time, and last accessed time
o "ind objects to sessions, allowing user information to persist across
multiple user connections
Session is a place to store state information for a specific client, so that the
information is available to different servlets.
session is associated with one client;s browser session and spans many &''(
re!uests.
Session trac#ing is supported by the servlet engine.
'et(ods:
0. getSession( ) : session can be created via the getSession( ) method of
9tt)Servlet-e.uest. n 9tt)Session object is returned. If argument for this
method is true, the server gives you the session for this client, or false to get
an existing session without giving the server permission to create new one.
'his object can store a set of bindings that associate names with objects.
6ollwing met(ods are used for *iniding:%
2. )utCalue( ): "inds the specified object into the session1s application layer
data with the given name. ny existing binding with the same name is
replaced.
a. ;arameters:
i. n"#e % the name to which the object is bound? cannot be null
ii. v"l$e % the object to be bound? cannot be null
4. getCalue( ): 'his method returns value for specified object
a. ;arameters:
i. n"#e % a string specifying the name of the object
6. getCalue!ames( ): )eturns an array of the names of all the application layer
data objects bound into the session. Aor example, if you want to delete all of
the data objects bound into the session, use this method to obtain their names.
O. removeCalue( ): )emoves the object bound to the given name in the
session1s application layer data. <oes nothing if there is no object bound to the
given name. 'he value that implements the &ttpSession"inding/istener
interface will call its value8nbound9+ method.
a. ;arameters:
i. name % the name of the object to remove
Some Session servlet +,am)les
+,am)le:1: 'he following servlet gives the information about number of times
user re!uested this page and also it uses some methods of &ttpSession interface to
display information about current session.
import java.io.D?
import java.util.:numeration?
import javax.servlet.D?
import javax.servlet.http.D?
public class SessionInfoServlet extends &ttpServlet
E
public void doGet 9&ttpServlet)e!uest re!, &ttpServlet)esponse res+ throws
Servlet:xception, IB:xception
E
&ttpSession session G re!.getSession9true+?
ServletButputStream out G res.getButputStream9+?
res.setContent'ype9FtextChtmlF+?
out.println9F*&:<H*'I'/:H SessionServlet Butput
*C'I'/:H*C&:<H*"B<5HF+?
out.println9F*h0H Session Servlet Butput *Ch0HF+?
Integer ival G 9Integer+session.get-alue9FcounterF+?
if 9ivalGGnull+
E
i G new Integer90+?
J
else
E
i G new Integer9i.int-alue9+ R 0+?
J
session.put-alue9FcounterF, i+?
out.println9F5ou have hit this page *bHF R i R F*CbH times.*pHF+?
out.println9F*pHF+?
out.println9F*h4H)e!uest and Session <ata$*Ch4HF+?
out.println9FSession I< in )e!uest$ F R re!.get)e!uestedSessionId9++?
out.println9F*brHSession I< in )e!uest from Coo#ie$ F R
re!.is)e!uestedSessionIdAromCoo#ie9++?
out.println9F*brHSession I< in )e!uest from 8)/$ F R
re!.is)e!uestedSessionIdArom8rl9++?
out.println9F*brH-alid Session I<$ F R re!.is)e!uestedSessionId-alid9++?
out.println9F*h4HSession <ata$*Ch4HF+?
out.println9F3ew Session$ F R session.is3ew9++?
out.println9F*brHSession I<$ F R session.getId9++?
out.println9F*brHCreation 'ime$ F R session.getCreation'ime9++?
out.println9F*brH/ast ccessed 'ime$ F R session.get/astccessed'ime9++?
out.println9F*h4HSession Context <ata$*Ch4HF+?
&ttpSessionContext context G session.getSessionContext9+?
for9:numeration e G context.getIds9+? e.has.ore:lements9+ ?+
E
out.println9F-alid Session$ F R 9String+e.next:lement9+R F*brHF+?
J
out.println9F*C"B<5HF+?
out.close9+?
J
J
1ut)ut
SessionServlet !utput
5ou have hit this page 11 times.
"e#uest an$ Session Data%
Session I< in )e!uest$ 2:42>">P:OYAYKLK>A<"KLA:0"0KP<L
Session I< in )e!uest from Coo#ie$ true
Session I< in )e!uest from 8)/$ false
-alid Session I<$ true
Session Data%
3ew Session$ false
Session I<$ 2:42>">P:OYAYKLK>A<"KLA:0"0KP<L
Creation 'ime$ 0222PO2OK>L>4
/ast ccessed 'ime$ 0222PO2P02>P2
Session &onte't Data%
+,am)le2:
&ere1s a simple servlet that shows how to store some string information to trac# a
session$
import java.io.D?
import javax.servlet.Servlet:xception?
import javax.servlet.http.D?
import java.util.:numeration?

public class ShowSession extends &ttpServlet
E
public void do(ost9&ttpServlet)e!uest re!uest, &ttpServlet)esponse response+
throws Servlet:xception, IB:xception
E
doGet9 re!uest, response +?
J
public void doGet9&ttpServlet)e!uest re!uest, &ttpServlet)esponse response+
throws Servlet:xception, IB:xception
E
&ttpSession session G re!uest.getSession9+?
boolean clear G re!uest.get(arameter9FclearF+ IG null?
if 9clear+
session.invalidate9+?
else
E
String name G re!uest.get(arameter9F3ameF+?
String value G re!uest.get(arameter9F-alueF+?
if 9 name IG null [[ value IG null +
session.setttribute9 name, value +?
J
response.setContent'ype9FtextChtmlF+?
(rintWriter out G response.getWriter9 +?
out.println9F*htmlH*headH*titleHShow Session*CtitleH*CheadH*bodyHF+?
if 9 clear +
out.println9F*h0HSession Cleared$*Ch0HF+?
else E
out.println9F*h0HIn this session$*Ch0H*ulHF+?
:numeration names G session.getttribute3ames9 +?
while 9 names.has.ore:lements9 + +
E
String name G 9String+names.next:lement9 +?
out.println9 F*liHFRnameRF G F Rsession.getttribute9 name + +?
J
J
out.println9F*CulH*pH*hrH*h0Hdd String*Ch0HF
R F*form methodG@F(BS'@F actionG@FF
R re!uest.get)e!uest8)I9 + RF@FHF
R F3ame$ *input nameG@F3ame@F si7eG2>H*brHF
R F-alue$ *input nameG@F-alue@F si7eG2>H*brHF
R F*brH*input typeG@Fsubmit@F valueG@FSubmit@FHF
R F*input typeG@Fsubmit@F nameG@Fclear@F valueG@FClear@FH*CformHF+?
JJ
When you invo#e the servlet, you are presented with a form that prompts you
to enter a name and a value. 'he value string is stored in a session object
under the name provided. :ach time the servlet is called, it outputs the list of
all data items associated with the session. 5ou will see the session grow as
each item is added 9in this case, until you restart your web browser or the
server+.
Bur %oGet&' method generates the form, which refers bac# to our servlet via
a POST method. We override %oPost&' to delegate bac# to our %oGet&'
method, allowing it to handle everything. Bnce in %oGet&', we attempt to
fetch the user session object from the re($est parameter using
)etSession&'. 'he HttpSession object supplied by the re!uest functions
li#e a hashtable. 'here is a setAttri*$te&' method, which ta#es a string
name and an O*+e,t argument, and a corresponding )etAttri*$te&'
method. In our example, we use the )etAttri*$teN"#es&' method to
enumerate the values currently stored in the session and to print them.
"y default, )etSession&' creates a session if one does not exist. If you want
to test for a session or explicitly control when one is created, you can call the
overloaded version )etSession&-"lse', which does not automatically create
a new session and returns n$ll if there is no session. 'o clear a session
immediately, we can use the inv"li%"te&' method. fter calling
inv"li%"te&' on a session, we are not allowed to access it again, so we set a
flag in our example and show the FSession ClearedF message. Sessions may
also become invalid on their own by timing out. 5ou can control session
timeout in the application server or through the web.xml file 9via the Fsession%
timeoutF value of the Fsession configF section+. 8ser sessions are private to
each web application and are not shared across applications.
+,am)le3:
'he following servlet illustrates how to use session state. 'he getSession( )
method gets the current session. new session is created if one does not
already exist. 'he getCalue( ) method is called to obtain the object that is
bound to the name FdateF. 'hat object is a 7ate object that encapsulates the
date and time when this page was last accessed. 9Bf course, there is no such
binding when the page is first accessed.+
7ate object encapsulating the current date and time is then created. 'he
)utCalue( ) method is called to bind the name FdateF to this object.
import java.io.D?
import java.util.D?
import javax.servlet.D?
import javax.servlet.http.D?
public class <ateServlet extends &ttpServlet E
public void doGet9&ttpServlet)e!uest re!uest,
&ttpServlet)esponse response+
throws Servlet:xception, IB:xception E
CC Get the &ttpSession object
&ttpSession hs G re!uest.getSession9true+?
CC Get writer
response.setContent'ype9FtextChtmlF+?
(rintWriter pw G response.getWriter9+?
pw.print9F*"HF+?
CC <isplay dateCtime of last access
<ate date G 9<ate+hs.get-alue9FdateF+?
if9date IG null+ E
pw.print9F/ast access$ F R date R F*brHF+?
J
CC <isplay current dateCtime
date G new <ate9+?
hs.put-alue9FdateF, date+?
pw.println9FCurrent date$ F R date+?
J
J
When you first re!uest this servlet, the browser displays one line with the current
date and time information. Bn subse!uent invocations, two lines are displayed.
'he first line shows the date and time when the servlet was last accessed. 'he
second line shows the current date and time.
+,am)le$:
Write a Session Servlet program to create a form which accepts user information and
find number of visits to the page. (!ov2""#)
Solution:
Ste)1: Create a html file to enter user information.
6orm1.(tml
*htmlH
*headH
*CheadH
*bodyH
*form methodGFgetF actionGFhttp$CClocalhost$K>K>CexamplesCservletCStateServletFH
:nter ur nameG *input typeGFtextF nameGFnameFH
*input typeGFsubmitFH
*CformH
*CbodyH
*ChtmlH
Ste)2: Write a servlet file which receives user information from user and displays
number of times user has visited this page. 'his servlet uses &ttpSession interface and
its methods as gettrribute, getSession.
StateServlet.0ava
import java.io.D?
import java.util.D?
import javax.servlet.D?
import javax.servlet.http.D?
public class StateServlet extends &ttpServlet
E
public void doGet9&ttpServlet)e!uest re!uest, &ttpServlet)esponse response+
throws IB:xception, Servlet:xception
E
int m G >?
&ttpSession session G re!uest.getSession9true+?
Integer mm G 9Integer+ session.getttribute9FcountF+?
if9mm IG null+ m G mm.int-alue9+?
mRR?
session.setttribute9FcountF, new Integer9m++?
String name G re!uest.get(arameter9FnameF+?
if9name GG null+ name G F8serF?
response.setContent'ype9FtextChtmlF+?
(rintWriter out G response.getWriter9+?
out.println9F*htmlHF+?
out.println9F*headH*titleHWelcome 8ser*CtitleH*CheadHF+?
out.println9F*bodyHF+?
out.println9F*h0 alignG1center1HF R F&elloF R F F R name R F*Ch0HF+?
out.println9F*bH3umber of re!uests $*CbHF R m+?
out.println9F*CbodyHF+?
out.println9F*ChtmlHF+?
out.close9+?
J
J
+,am)le>:
:rite a servlet w(ic( dis)lay information a*out current session:
import java.io.D?
import java.util.D?
import javax.servlet.D?
import javax.servlet.http.D?
public class Session<emo extends &ttpServlet
E
public void doGet9&ttpServlet)e!uest re!,&ttpServlet)esponse res+ throws
Servlet:xception,IB:xception
E
(rintWriter out G res.getWriter9+?
&ttpSession session G re!.getSession9true+?
<ate created G new <ate9session.getCreation'ime9++?
<ate accessed G new <ate9session.get/astccessed'ime9++?
out.println9FI< F R session.getId9++?
out.println9FCreated$ F R created+?
out.println9F/ast ccessed$ F R accessed+?
String data3ame G re!.get(arameter9Fdata3ameF+?
if9data3ame IG null [[ data3ame.length9+ H >+
E
String data-alue G re!.get(arameter9Fdata-alueF+?
session.put-alue9data3ame, data-alue+?
J
StringWX value3ames G session.get-alue3ames9+?
if9value3ames IG null [[ value3ames.length H >+
E
for9int i G >? i * value3ames.length? iRR+
E
String name G value3amesWiX?
String value G
session.get-alue9name+.toString9+?
out.println9name R F G F R value+?
J
J
J
J
+J+-CIS+:
0. :xplain /ife cycle of Servlets. 93ov%2>>P+ 93ov%2>>6+93ov M 2>>L+
2. :xplain the ,ava Servlet rchitecture. 93ov M 2>>L+
4. Write a servlet that displays s!uare root and cube root of a number, which will be
received from a &'./ file. lso write the code for &'./ file 93ov M 2>>L+
6. What is the need for Session trac#ing in the ServletZ What are the different
techni!ues used for Session trac#ingZ 93ov M 2>>L+ 93ov%2>>P+ 93ov%2>>6+
O. <istinguish between 93ov M 2>>O+
P. &ttp Servlet )e!uest and &ttpservlet )esponse
L. What is a Coo#ieZ &ow is it used in session trac#ingZ 93ov M 2>>O+ 93ov%2>>P+
K. Write a servlet that stores the user id into a Coo#ie and retrieves it later 93ov M
2>>O+
Y. Write a servlet that accepts a table name sent from an html page and retrieves the
content of that table from the database in a tabular form on the screen. 93ovM
2>>O+
0>. Write a Session Servlet program to create a form which accepts user information
and find number of visits to the page. 93ov%2>>P+
00. &ow can &''( )e!uest and )esponse are handle by the ServletsZ 93ov%2>>6+
02. Write a servlet that accepts text SfriendThomeQ sent from on &'./ document
and displays them on screen as S&elloI AriendT3ameQ. 93ov%2>>6+
04. :xplain Coo#ies for Servlets 93ov%2>>6+
06. /ist at least 4 methods in &ttpSessionZ 93ov%2>>P+
0O. :xplain javax.servlet (I
0P. :xplain javax.servlet.&ttp (I

You might also like