8/14/2019 servlet notes.doc
1/103
Chapter Four
Servlet(Server Side programming)
---------------------------------------------------------------------------
Servlets are server side components that provide a powerful mechanism for
developing server side programs.
Servlets provide component-based, platform-independent methods for
building Web-based applications.
Servlets are server as well as platform-independent. Using servlets web
developerscan create fast and efficient server side application which can run
on any servlet enabled web server.
Servlets run entirely inside the Java Virtual Machine. Since the Servlet runs at
server side so it does not checs the browser for compatibility. Servlets can
access the entire family of Java !"#s, including the J$%& !"# to access
enterprise databases. Servlets can also access a library of '(("-specific calls,
receive all the benefits of the mature )ava language including portability,
performance, reusability, and crash protection. Servlets are the popular choice
for building interactive web applications.
Servlets are not designed for a specific protocol. %ut they are most commonly
used with the '((" protocols.
Servlets uses the classes in the )ava pacages )ava*.servlet and
)ava*.servlet.http. Servlets provides a way of creating the sophisticated server
http://www.roseindia.net/servlets/what-is-servlets.shtmlhttp://www.roseindia.net/servlets/what-is-servlets.shtmlhttp://www.roseindia.net/servlets/what-is-servlets.shtmlhttp://www.roseindia.net/servlets/what-is-servlets.shtmlhttp://www.roseindia.net/servlets/what-is-servlets.shtmlhttp://www.roseindia.net/servlets/what-is-servlets.shtml8/14/2019 servlet notes.doc
2/103
side e*tensions in a server as they follow the standard framewor and use the
highly portable )ava language.
'((" Servlet typically used to+
"rovide dynamic content lie getting the results of a database uery and
returning to the client.
"rocess andor store the data submitted by the '(M.
Manage information about the state of a stateless '((". e.g. an online
shopping car manages reuest for multiple concurrent customers.
Life cycle of Servlet
/. oading and #nstantiation: (he servlet container loads the servlet during
startup or when the first reuest is made. (he loading of the servlet depends
on the attribute 0load-on-startup1 of web.*ml file. #f the attribute 0load-on-
startup1 has a positive value then the servlet is load with loading of the
container otherwise it load when the first reuest comes for service. !fter
loading of the servlet, the container creates the instances of the servlet.
2. #nitiali3ation: !fter creating the instances, the servlet container calls the init45
method and passes the servlet initiali3ation parameters to the init45 method.
(he init45 must be called by the servlet container before the servlet can service
http://www.roseindia.net/servlets/what-is-servlets.shtmlhttp://www.roseindia.net/servlets/what-is-servlets.shtml8/14/2019 servlet notes.doc
3/103
any reuest. (he initiali3ation parameters persist until the servlet is destroyed.
(he init45 method is called only once throughout the life cycle of the servlet.
(he servlet will be available for service if it is loaded successfully otherwise
the servlet container unloads the servlet.
6. Servicing the 7euest: !fter successfully completing the initiali3ation
process, the servlet will be available for service. Servlet creates separate
threads for each reuest. (he servlet container calls the service45 method for
servicing any reuest. (he service45 method determines the ind of reuestand calls the appropriate method 4do8et45 or do"ost455 for handling the
reuest and sends response to the client using the methods of the response
ob)ect.
9. $estroying the Servlet: #f the servlet is no longer needed for servicing any
reuest, the servlet container calls the destroy45 method . ie the init45
method this method is also called only once throughout the life cycle of the
servlet. &alling the destroy45 method indicates to the servlet container not to
sent any reuest for service and the servlet releases all the resources
associated with it. Java Virtual Machine claims for the memory associated
with the resources for garbage collection.
8/14/2019 servlet notes.doc
4/103
ife &ycle of a Servlet
Advantages of Java Servlets
/. Portability
2. Powerful
6. Efficiency
8/14/2019 servlet notes.doc
5/103
9. Safety
:. Integration
;. Extensibility
t do. Servlets can share data among each other, they even mae
the database connection pools easy to implement. (hey can maintain the session by
using the session tracing mechanism which helps them to maintain information
from reuest to the reuest. #t can do many other things which are difficult to
implement in the &8# programs.
?fficiency
!s compared to &8# the servlets invocation is highly efficient. When the servlet getloaded in the server, it remains in the server>s memory as a single ob)ect instance.
'owever with servlets there are = threads but only a single copy of the servlet class.
Multiple concurrent reuests are handled by separate threads so we can say that the
servlets are highly scalable.
8/14/2019 servlet notes.doc
6/103
Safety
!s servlets are written in )ava, servlets inherit the strong type safety of )ava
language. Java>s automatic garbage collection and a lac of pointers means that
servlets are generally safe from memory management problems. #n servlets we can
easily handle the errors due to Java>s e*ception handling mechanism. #f any
e*ception occurs then it will throw an e*ception.
#ntegration
Servlets are tightly integrated with the server. Servlet can use the server to translate
the file paths, perform logging, chec authori3ation, and M#M? type mapping etc.
?*tensibility
(he servlet !"# is designed in such a way that it can be easily e*tensible. !s it
stands today, the servlet !"# support 'ttp Servlets, but in later date it can be
e*tended for another type of servlets.
#ne*pensive
(here are number of free web servers available for personal use or for commercial
purpose. Web servers are relatively e*pensive. So by using the free available web
servers you can add servlet support to it.
Advantages of Servlets over CGI
Servlets are server side components that provide a powerful mechanism for
developing server web applications for server side. ?arlier &8# was developed to
provide server side capabilities to the web applications. !lthough &8# played a
ma)or role in the e*plosion of the #nternet, its performance, scalability and
reusability issues mae it less than optimal solutions. Java Servlets changes all that.
8/14/2019 servlet notes.doc
7/103
%uilt from ground up using Sun>s write once run anywhere technology )ava servlets
provide e*cellent framewor for server side processing.
Using servlets web developers can create fast and efficient server side applications
and can run it on any servlet enabled web server. Servlet runs entirely inside the Java
Virtual Machine. Since the servlet runs on server side so it does not depend on
browser compatibility.
Servlets have a number of advantages over &8# and other !"#>s. (hey are+
"latform#ndependence
Servlets are written entirely in )ava so these are platform independent. Servlets
can run on any Servlet enabled web server. @or e*ample if you develop an web
application in windows machine running Java web server, you can easily run the
same on apache web server 4if !pache Serve is installed5 without modification or
compilation of code. "latform independency of servlets provides great
advantages over alternatives of servlets.
"erformance
$ue to interpreted nature of )ava, programs written in )ava are slow. %ut the )ava
servlets runs very fast. (hese are due to the way servlets run on web server. @or
any program initiali3ation taes significant amount of time. %ut in case of
servlets initiali3ation taes place first time it receives a reuest and remains in
memory till times out or server shut downs. !fter servlet is loaded, to handle a
new reuest it simply creates a new thread and runs service method of servlet. #n
comparison to traditional &8# scripts which creates a new process to serve the
reuest.
8/14/2019 servlet notes.doc
8/103
?*tensibility
Java Servlets are developed in )ava which is robust, well-designed and ob)ect
oriented language which can be e*tended or polymorphed into new ob)ects. So
the )ava servlets tae all these advantages and can be e*tended from e*isting
class to provide the ideal solutions.
Safety
Java provides very good safety features lie memory management, e*ception
handling etc. Servlets inherits all these features and emerged as a very powerful
web server e*tension.
Secure
Servlets are server side components, so it inherits the security provided by the
web server. Servlets are also benefited with Java Security Manager.
Introduction to Java Servlets
Java Servlets are server side Java programs that reuire either a Web Server or an
!pplication Server for e*ecution. ?*amples for Web Servers include !pacheAs
(omcat Server and MacromediaAs J7un. !pplication Servers include #%MAs
Weblogic and %?!As Websphere server. ?*amples for other Server programs
include Java Server "ages 4JS"s5 and ?nterprise Java %eans 4?J%s5.
%asic Servlet Structure
8/14/2019 servlet notes.doc
9/103
Java servlets are server side programs or to be more specific, web applications that
run on servers that comply '((" protocol. (he )ava*.servlet and )ava*.servlet.http
pacages provide the necessary interfaces and classes to wor with servlets. Servlets
generally e*tend the 'ttpServlet class and override the do8et or the do"ost methods.
#n addition, other methods such as init45, service45 and destroy45 also called as life
cycle methods might be used. (he seleton of a servlet is given in "rogramm.
8/14/2019 servlet notes.doc
10/103
Servlets Life Cycle
(he first time a servlet is invoed, it is the init method which is called. !nd
remember that this is called only once during the lifetime of a servlet. So,
you can put all your initiali3ation code here.
(his method ne*t calls the service method. (he service method in turn
calls the do8et or do"ost methods 4whichever the user has overridden5.
@inally, the servlet calls the destroy method. #t is in a sense euivalent to
the finally method. Bou can reset or close references connections done
earlier in the servletAs methods 4e.g. init, service or do8et do"ost5. !fter
this method is called, the servlet ceases to e*ist for all practical purposes.
'owever, please note that it is not mandatory to override all these
8/14/2019 servlet notes.doc
11/103
methods. More often than not, it is the do8et or do"ost method used with
one or more of the other life cyclemethods.
! Servlet "rogram
8/14/2019 servlet notes.doc
12/103
8/14/2019 servlet notes.doc
13/103
Cutput Screens
(o appreciate the e*ecution of the servlet life cycle methods, eep refreshing the
browser 4@: in Windows5. #n the bacground, what actually happens is D with
8/14/2019 servlet notes.doc
14/103
each refresh, the do8et method is called which increments iAs value and displays
the current value.
8/14/2019 servlet notes.doc
15/103
Installation, Configuration and running Servlets
#n this section, we will see as how to install a Web Server, configure it and finally
run servlets using this server. (hroughout this tutorial, we will be using !pacheAs
http://roseindia.net/servlets/introductiontoconfigrationservlet.shtmlhttp://roseindia.net/servlets/introductiontoconfigrationservlet.shtml8/14/2019 servlet notes.doc
16/103
(omcat server as the Web Server. (omcat is not only an open and free server, but
also the most preferred Web Server across the world. ! few reasons we can attribute
for its popularity is D ?asy to install and configure, very less memory footprint, fast,
powerful and portable. #t is the ideal server for learning purpose.
#nstallation of (omcat Server and J$E
!s mentioned earlier, !pacheAs (omcat Server is free softwareavailable for
download F www.apache.org. (he current version of (omcat Server is ;.G 4as of
=ovember 2GG
8/14/2019 servlet notes.doc
17/103
successfully installed as follows+
Step /
K 8o to &+I"rogram @ilesI!pache Software @oundationI(omcat ;.GIbin and double
clic on tomcat;
C7
K 8o to Start-1"rograms-1!pache (omcat ;.G -1 Monitor (omcat. Bou will notice
an icon appear on the right side of your Status %ar. 7ight clic on this icon and
clic on Start service.
Step 2
K Cpen your %rowser 4e.g. MS #nternet ?*plorer5 and type the following U7 +
http+localhost 4#f you have changed to port L to G5
C7
K Cpen your %rowser 4e.g. MS #nternet ?*plorer5 and type the following U7 +
http+localhost+GG 4#f you have =C( changed the default port L5
#n either case, you should get a page similar to the one in @igure- which signifies
that the (omcat Server is successfully running on your machine.
&ompile and ?*ecute your Servlet
(his section through a step by step 4and illustration5 approach e*plains as how to
compile and then run a servlet using (omcat Server. (hough this e*planation is
specific to (omcat, the procedure e*plained holds true for other Web servers too.
your servlet progra" Step#$%o"pile
8/14/2019 servlet notes.doc
18/103
(he first step is to compile your servlet program. (he procedure is no different from
that of writing and compiling a )ava program. %ut, the point to be noted is that
neither the )ava*.servlet. nor the )ava*.servlet.http. is part of the standard J$E. #t
has to be e*clusively added in the &!SS"!('. (he set of classes reuired for
writing servlets is available in a )ar file called servlet-api.)ar. (his )ar file can be
downloaded from several sources. 'owever, the easiest one is to use this )ar file
available with the (omcat server 4&+I"rogram @ilesI!pache Software
@oundationI(omcat ;.GIlibIservlet-api.)ar5. Bou need to include this path in
&!SS"!('. Cnce you have done this, you will be able to successfully compile
your servlet program. ?nsure that the class file is created successfully.
Step & $ %reate your Web application fol'er
(he ne*t step is to create your web applicationfolder. (he name of the folder can be
any valid and logical name that represents your application 4e.g. banHapps,
airlineHticetsHbooing, shoppingHcart,etc5. %ut the most important criterion is that
this folder should be created under webapps folder. (he path would be similar or
close to this - &+I"rogram @ilesI!pache Software @oundationI(omcat ;.GIwebapps.
@or demo purpose, let us create a folder called demo-e*amples under the webapps
folder.
http://roseindia.net/servlets/introductiontoconfigrationservlet.shtmlhttp://roseindia.net/servlets/introductiontoconfigrationservlet.shtml8/14/2019 servlet notes.doc
19/103
@igure- depicts the same.
Step $ %reate the WE)*I+ fol'er
(he third step is to create the W?%-#=@ folder. (his folder should be created under
your web application folder that you created in the previous step. @igure-/G shows
the W?%-#=@ folder being placed under the demo-e*amples folder.
@igureD W?%-#=@ folder inside web application folder
Step- $%reate the web.x"l file an' the classes fol'er
(he fourth step is to create the web.*ml file and the classes folder. ?nsure that the
8/14/2019 servlet notes.doc
20/103
web.*ml and classes folder are created under the W?%-#=@ folder. @igure-// shows
this file and folder being placed under the W?%-#=@ folder.
@igure D web.*ml file and the classes folder
=ote D #nstead of creating the web.*ml file an easy way would be to copy an
e*isting web.*ml file 4e.g. &+I"rogram @ilesI!pache Software @oundationI(omcat
;.GIwebappsIe*amplesIW?%-#=@5 and paste it into this folder. Bou can later edit
this file and add relevant information to your web application.
Step / $ %opy the servlet class to the classes fol'er
We need to copy the servlet class file to the classes folder in order to run the servlet
that we created. !ll you need to do is copy the servlet class file 4the file we obtained
from Step /5 to this folder. @igure-/2 shows the servletHlifecycle5 class being placed
in the classes folder.
8/14/2019 servlet notes.doc
21/103
@igure D servlet class file placed under classes folder
Step 0 $ E'it web.x"l to inclu'e servlet1s na"e an' url pattern
(his step involves two actions vi3. including the servletAs name and then mentioning
the url pattern. et us first see as how to include the servletAs name in the web.*ml
file. Cpen the web.*ml file and include the servletAs name as shown in @igure-/6.
8/14/2019 servlet notes.doc
22/103
@igureD #nclude servletAs name using the 0servlet1 0servlet1 tag
+ote $ (he servlet-name need not be the same as that of the class name. Bou can
give a different name 4or alias5 to the actual servlet. (his is one of the main reasons
as why this tag is used for.
=e*t, include the url pattern using the 0servlet-mapping1 0servlet-mapping1 tag.
(he url pattern defines as how a user can access the servlet from the browser.
@igure-/9 shows the url pattern entry for our current servlet.
8/14/2019 servlet notes.doc
23/103
@igure D #nclude url-pattern using the 0servlet-mapping1 0servlet-mapping1 tag
+oteD "lease remember that the path given in the url-pattern is a relative path. (his
means that this path is w.r.t. your web applications folder 4demo-e*amples in this
case5.
Step 2 $ Run 3o"cat server an' then execute your Servlet
(his step again involves two actions vi3. running the Web Server and then e*ecuting
the servlet. !fter ensuring that the web server is running successfully, you can run
your servlet. (o do this, open your web browser and enter the url as specified in the
web.*ml file. (he complete url that needs to be entered in the browser is+
http+localhostdemoe*amplesservletHlifecycle
8/14/2019 servlet notes.doc
24/103
@igure D Cur servletAs outputN
Bou can eep refreshing the browser window and see for yourself as how i value is
incremented 4a proof that the do8et is called every time you re-invoe a servlet5.
'ow to 7un a Servlet
(o run a servlet one should follow the steps illustrated below+
4ownloa' an' Install the to"cat server: #nstall the tomcat server in a
directory in which you want to install and set the classpath.for the variable
5678O9E in the environment variable. (o get details about the
installation process and setting the classpath clic the lin (omcat installation.
Set the class for the ar file: Set the classpath of the servlet-api.)ar file in the
variable %;SSP38 inside the environment variable by using the
following steps.
@or Windows O",
http://roseindia.net/servlets/HowToRunAServlet.shtmlhttp://roseindia.net/servlets/HowToRunAServlet.shtmlhttp://roseindia.net/servlets/HowToRunAServlet.shtmlhttp://roseindia.net/servlets/HowToRunAServlet.shtml8/14/2019 servlet notes.doc
25/103
8o to Start-1&ontrol "anel-1System-1!dvanced-1?nvironment Variables-
1=ew button and Set the values as
6ariable +a"e: %;SSP38
6ariable 6alue: &+I"rogram @ilesIJavaI(omcat ;.GIlibIservlet-api.)ar
@or Windows 2GGGand =(
8o to Start-1Settings-1&ontrol "anel-1System-1?nvironment Variables-
1=ew button and Set the values as
6ariable +a"e: %;SSP38
6ariable 6alue: &+I"rogram @ilesIJavaI(omcat ;.GIlibIservlet-api.)ar
&reate a )ava source file and a web.*ml file in a 'irectory structure.
&ompile the )ava source file, put the compiled file 4.class file5 in the classes
folder of your applicationand deploy the directory of your application in the
webapps folder inside the tomcat directory.
Start the tomcat server, open a browser window and type the U7
http:
8/14/2019 servlet notes.doc
26/103
method whenever web server receives the 8?( reuest from the servlet. (he
do8et45 method taes two arguments first is 'ttpServlet7euest ob)ect and the
second one is 'ttpServlet7esponse ob)ect and this method throws the
Servlet?*ception.
Whenever the user sends the reuest to the server then server generates two ob)ects,
first is 'ttpServlet7euest ob)ect and the second one is 'ttpServlet7esponse ob)ect.
'ttpServlet7euest ob)ect represents the client>s reuest and the
'ttpServlet7esponse represents the servlet>s response.
#nside the do8et445 method our servlet has first used the set&ontent(ype45method ofthe response ob)ect which sets the content type of the response to text/html. #t is the
standard M#M? content type for the 'tml pages. !fter that it has used the method
getWriter45 of the response ob)ect to retrieve a PrintWriter ob)ect. (o display the
output on the browser we use the println45 method of the PrintWriterclass.
3he co'e the progra" is given below:
import )ava.io.*;import javax.servlet.*;import javax.servlet.http.*;
public class HelloWorld extends HttpServlet{public void doGet(HttpServletRequest request, HttpServle throws ServletException response.set"ontent#$pe(%text&ht'l%;
)rintWriter p + response.etWriter(; p.println(%-ht'l%; p.println(%-head-titleHello World-&title-&title% p.println(%-/od$%; p.println(%-h0Hello World-&h0%; p.println(%-&/od$-&ht'l%; 1
http://roseindia.net/servlets/HelloWorld.shtmlhttp://roseindia.net/servlets/HelloWorld.shtml8/14/2019 servlet notes.doc
27/103
1
web.x"l file for this progra":
-2x'l version+%0.3% encodin+%S!4556740%2-844-89!"#:)E e/4app
)
8/14/2019 servlet notes.doc
28/103
4isplaying 4ate in Servlet
#n this e*ample we are going to show how we can display a current date and time on
our browser. #t is very easy to display it on our browser by using the 4ateclass of
theava.utilpacage.
3he co'e the progra" is given below:
import )ava.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class 9ispla$in9ate extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response
throws ServletException, !Exce
)rintWriter p + response.etWriter(;
9ate toda$ + new 9ate(;
p.println(%-ht'l%D%-/od$-h0#oda$ 9ate is-&h0%;
p.println(%-/%D toda$D%-&/-&/od$%D %-&ht'l%;
1
1
http://roseindia.net/servlets/DisplayingDate.shtmlhttp://roseindia.net/servlets/DisplayingDate.shtml8/14/2019 servlet notes.doc
29/103
web.x"l file for this progra"
-2x'l version+%0.3% encodin+%S!4556740%2
-844-89!"#:)E e/4app
)
8/14/2019 servlet notes.doc
30/103
Simple Counter in Servlet
#n this e*ample we are going to now how we can mae a program on counterwhich
will eep trac how many times the servlet has been accessed.
(o mae this program firstly we have to mae one class Si"ple%ounterInServlet.
(he name of the class should follow the naming convention. 7emember to eep the
name of the class in such a way that it becomes easy to understand what the program
is going to do )ust by seeing the class name. !fter maing a class define one variable
counter which will eep record for how many times the servlet has been accessed.
=ow use method either 'o?et(! or 'oPost(! to write a logic of the program. Cur
program logic is simple. We have to )ust increment the value of the counter by /. (o
display the output use the method getWriter(!method of the response ob)ect which
will in turn return the ob)ect of the "rintWriter class. =ow display the value of the
counter.
3he co'e of the progra" is given below:
http://roseindia.net/servlets/SimpleCounterInServlet.shtmlhttp://roseindia.net/servlets/SimpleCounterInServlet.shtml8/14/2019 servlet notes.doc
31/103
import )ava.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Si'ple"ounter extends HttpServlet{
int counter + 3;
public void doGet(HttpServletRequest request, HttpServletResponse response
throws ServletException, !Exception
{
response.set"ontent#$pe(%text&ht'l%;
)rintWriter p + response.etWriter(;
counterDD; p.println(%t present the value oF the counter is % D
1
1
3he output of the progra" is given below:
Holistic Counter
#n this program we are going to mae a such a servlet which will count the number it
has been accessed and the number of threads created by the server.
http://roseindia.net/servlets/SimpleCounterInServlet.shtmlhttp://roseindia.net/servlets/HolisticCounterInServlet.shtmlhttp://roseindia.net/servlets/SimpleCounterInServlet.shtmlhttp://roseindia.net/servlets/HolisticCounterInServlet.shtml8/14/2019 servlet notes.doc
32/103
#n this e*ample firstly we are going to create one class named as
'olistic&ounter#nServlet. =ow declare a variable counterof init with initial value G,
the value of this counter will be different for each servlet and create a 8ashtable
ob)ect. (his ob)ect will be shared by all the threads in the container. #nside the
do8et45 method use the method getWriter45 method of the response ob)ect which
will return the "rintWriter ob)ect.
3he co'e of the progra" is given below:
import )ava.io.*;
import java.io.!Exception;import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Holistic"ounter extends HttpServlet{
int counter + 3; &&separate or Each Servlet
static Hashta/le hash#a/le + new Hashta/le(; &&Shared /$
public void doGet(HttpServletRequest request, HttpServletR
throws ServletException, !
{
response.set"ontent#$pe(%text&ht'l%;
)rintWriter p + response.etWriter(;
counterDD;
p.println(%#his servlet has /een accessed% D counter D
hash#a/le.put(this,this;
p.println(%#here are currentl$% D hash#a/le.sie( D %t
http://roseindia.net/servlets/HolisticCounterInServlet.shtmlhttp://roseindia.net/servlets/HolisticCounterInServlet.shtmlhttp://roseindia.net/servlets/HolisticCounterInServlet.shtmlhttp://roseindia.net/servlets/HolisticCounterInServlet.shtml8/14/2019 servlet notes.doc
33/103
1
1
3he output of the progra" is given below:
Counter in init( !et"od
#n this program we are going to mae such a servlet which will count and displays
the number of times it has been accessed and by reading the init parameter to now
from where the counting will begin.
#n this program we are going to mae use of the init method of the Servletinterface
which taes one argument of Servlet&onfig. @irstly declare a variable counter which
will have the initial value of the counter. (he init45 method accepts an ob)ect which
implements Servlet&onfig interface. #t uses the method get#nit"arameter45 method
8/14/2019 servlet notes.doc
34/103
of the Servlet&onfig interface to the value of the init parameter initialwhich we
have defined in the deployment descriptor file. Bou need to parsethe String value
which you will get from the getInitPara"eter(! method to a #nteger.
3he co'e of the progra" is given below:
import )ava.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class "ounternnit extends HttpServlet { int counter;
public void init(Servlet"onFi conFi throws ServletExc
super.init(conFi;
Strin initIalue + conFi.etnit)ara'eter(%initial%;
try{
counter + nteer.parsent(initIalue;
1
catch(Au'/eror'atException e
{
counter + 3;
1
1
protected void doGet(HttpServletRequest request, HttpSer
throws ServletException, !Exception {response.set
)rintWriter p + response.etWriter(;
counterDD;
p.println(%Since loadin this servlet has /een accessed
http://roseindia.net/servlets/CounterInInit.shtmlhttp://roseindia.net/servlets/CounterInInit.shtml8/14/2019 servlet notes.doc
35/103
1
1
web.x"l file for this progra":
-2x'l version+%0.3% encodin+%S!4556740%2-844-89!"#:)E e/4app
)
8/14/2019 servlet notes.doc
36/103
-e/4app-servlet -servlet4na'eHello-&servlet4na'e -servlet4class"ounternnit-&servlet4class-&servlet
-servlet4'appin-servlet4na'eHello-&servlet4na'e-url4pattern&"ounternnit-&url4pattern-&servlet4'appin-&e/4app
3he output of the progra" is given below:
Getting Init #arameter $ames
#n this e*ample we are going to retrieve the init parameter values which we have
given in the web.x"lfile.
Whenever the container maes a servlet it always reads it deployment descriptor file
i.e. web.*ml. &ontainer creates namevalue pairs for the Servlet%onfig ob)ect. Cnce
the parameters are in Servlet%onfigthey will never be read again by the &ontainer.
(he main )ob of the Servlet%onfig ob)ect is to give the init parameters.
(o retrieve the init parameters in the program firstly we have made one class named
?ettingInitPara"eter+a"es. (he container calls the servlet>s service(! method
then depending on the type of reuest, the service method calls either the do8et45 or
8/14/2019 servlet notes.doc
37/103
the do"ost45. %y default it will be do8et45 method. =ow inside the 'o?et(! method
use getWriter(! method of the responseob)ect which will return a ob)ect of the
"rintWriter class which helps us to print the content on the browser.
(o retrieve all the values of the init parameter use method
getInitPara"eter+a"es(!which will return the ?numeration of the init parameters.
3he co'e of the progra" is given below:
import )ava.io.*;import javax.servlet.*;import javax.servlet.http.*;
import java.util.*;
public class nitServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response throws ServletException, !Exception { )rintWriter p + response.etWriter(; p.print(%nit )ara'eters are B %; Enu'eration enu'eration + etServlet"onFi(.etnit)ara'eterAa'es(; while(enu'eration.has>oreEle'ents({ p.print(enu'eration.nextEle'ent( D % %; 1 p.println(%Jn#he e'ail address is % D etServlet"onFi(.etnit)ara'eter(%d'inE'a p.println(%#he address is % D etServlet"onFi(.etnit)ara'eter(%ddress%;
p.println(%#he phone no is % D etServlet"onFi(.etnit)ara'eter(%)honeAo%; 11
web.x"l file of this progra":
http://roseindia.net/servlets/GettingInitParameterNames.shtmlhttp://roseindia.net/servlets/GettingInitParameterNames.shtml8/14/2019 servlet notes.doc
38/103
-2x'l version+%0.3% encodin+%S!4556740%2-89!"#:)E e/4app
)
8/14/2019 servlet notes.doc
39/103
(his is a very simple e*ample in which we are going to display the name on the
browser which we have entered from the 'tml page.
(o get the desired result firstly we have to mae one html form which will have only
one field named as name in which we will enter the name. !nd we will also have
one submit button, on pressing the submit button the reuest will go to the server
and the result will be displayed to us.
#n the servlet which will wor as a controller here pics the value from the html page
by using the method getPara"eter(!. (he output will be displayed to you by the
ob)ect of the PrintWriterclass.
3he co'e of the progra" is given below:
-ht'l-head-titleAe )ae 0-&title-&head
-/od$
-h?=oin-&h?-p)lease enter $our userna'e and passord-&p-For' 'ethod+%GE#% action+%&ht'lFor'&=oinServlet% -p serna'e -input t$pe+%text% na'e+%userna'e% sie+%?3%-&p -p )assord -input t$pe+%text% na'e+%passord% sie+%?3%-&p -p-input t$pe+%su/'it% value+%Su/'it% na'e+%
8/14/2019 servlet notes.doc
40/103
Strin pass + request.et)ara'eter(%passord%; out.println(%-ht'l%; out.println(%-/od$%; out.println(%#hanLs >r.% D % % D na'e D % % D %For visitin roseindia-/r% out.println(%Ao $ou can see $our passord B % D % % D pass D %-/r%; out.println(%-&/od$-&ht'l%;
11
web.x"l file for this progra":
-2x'l version+%0.3% encodin+%S!4556740%2-844-89!"#:)E e/4app)
8/14/2019 servlet notes.doc
41/103
!ultiple values for a single parameter
#n our program it may be that we may have multiples values for a single parameter
lie in checbo*es. We are going to mae one program over it.
(o mae such a servlet in which we have made one html form from where the values
will be passed to the controller. #n this program we have used the checbo* which
will have the same name but with different values. We have one more submit button,
on pressing this button the reuest will be forwarded.
8/14/2019 servlet notes.doc
42/103
=ow in the servlet that is woring lie a controller will retrieve the values we have
entered in the html form by the method getPara"eter6alues(!which returns the
arrayof String. !t last to retrieve all the values from the array use for loop. (he
output will be displayed to you by the PrintWriterob)ect.
3he co'e of the progra" is given below:
In'ex.ht"l
-89!"#:)E H#>= )= N.30 #ransitional&&EA%
-ht'l-head-titlensert title here-&title-&head-/od$-For' 'ethod + %post% action + %&Get)ara'eterServlet&Get)ara'eterIalues%-pWhich oF the hisL$ $ou liLe 'ost-&p
-input t$pe + %checL/ox% na'e +%hisL$% value + %Ro$al"hallene%Ro$al"hallene.--input t$pe + %checL/ox% na'e +%hisL$% value + %Ro$alSta%Ro$alSta.-/r-input t$pe + %checL/ox% na'e +%hisL$% value + %
8/14/2019 servlet notes.doc
43/103
import java.io.*;import javax.servlet.*;import javax.servlet.http.*;
public class Get)ara'eterIalues extends HttpServlet{protected void do)ost(HttpServletRequest request, HttpServletResponse response throws ServletException, !Exception { response.set"ontent#$pe(%text&ht'l%; )rintWriter p + response.etWriter(; StrinOP hisL$ + request.et)ara'eterIalues(%hisL$%; for(int i+3; i-hisL$.lenth; iDD{ p.println(%-/rhisL$ B % D hisL$OiP; 1 11
web.x"l file for this progra":
-2x'l version+%0.3% encodin+%S!4556740%2-844-89!"#:)E e/4app
)
8/14/2019 servlet notes.doc
44/103
8ere is the result of the above selection:
Send 'edirect in Servlet
When we want that someone else should handle the response of our servlet, then
there we should use sen'Re'irect(!method.
8/14/2019 servlet notes.doc
45/103
#n send 7edirect whenever the client maes any reuest it goes to the container,
there the container decides whether the concerned servlet can handle the reuest or
not. #f not then the servlet decides that the reuest can be handle by other servlet
or )sp. (hen the servlet calls the sen'Re'irect(!method of the response ob)ect and
sends bac the response to the browser along with the status code. (hen the browser
sees the status code and loo for that servlet which can now handle the reuest.
!gain the browser maes a new reuest, but with the name of that servlet which can
now handle the reuest and the result will be displayed to you by the browser. #n all
this process the client is unaware of the processing.
#n this e*ample we are going to mae one html in which we will submit the user
name and his password. (he controller will chec if the password entered by the
user is correct or not. #f the password entered by the user is correct then the servlet
will redirect the reuest to the other servlet which will handle the reuest. #f the
password entered by the user is wrong then the reuest will be forwarded to the html
form.
3he co'e of the exa"ple is given below:
ht"l file for this progra":
-ht'l
-head-titleAe )ae 0-&title-&head
-/od$
-For' 'ethod+%)!S#% action+%&SendRedirect&SendRedirectServlet% -pEnter $our na'eMn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp; -input t$pe+%text% na'e+%userna'e% sie+%?3%-&p -pEnter $our passordMn/sp; -input t$pe+%text% na'e+%passord% sie+%?3%-&p
8/14/2019 servlet notes.doc
46/103
-pMn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp; Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp; -input t$pe+%su/'it% value+%Su/'it% na'e+%
8/14/2019 servlet notes.doc
47/103
-2x'l version+%0.3% encodin+%S!4556740%2-89!"#:)E e/4app)
8/14/2019 servlet notes.doc
48/103
8/14/2019 servlet notes.doc
49/103
Session rac)ing
!s we now that the 'ttp is a statelessprotocol, means that it can>t persist the
information. #t always treats each reuest as a new reuest. #n 'ttp client maes aconnection to the server, sends the reuest., gets the response, and closes the
connection.
#n session management client first mae a reuest for any servlet or any page, the
container receives the reuest and generates a uniue session #$ and gives it bac to
the client along with the response. (his #$ gets stores on the client machine.
(hereafter when the client reuest again sends a reuest to the server then it also
sends the session #d with the reuest. (here the container sees the #d and sends bac
the reuest.
Session (racing can be done in three ways+
/. 8i''en or" iel's:(his is one of the ways to support the session tracing.
!s we now by the name, that in this fields are added to an '(M form
which are not displayed in the client>s reuest . (he hidden form fields are sent
bac to the server when the form is submitted. #n hidden form fields the html
entry will be lie this + 0input type QPhiddenP name Q PnameP valueQPP1. (his
means that when you submit the form, the specified name and value will be
get included in get or post method. #n this session #$ information would be
embedded within the form as a hidden field and submitted with the 'ttp
"CS( command.
2. @R; Rewriting: (his is another way to support the session tracing.
@R;Rewritingcan be used in place where we don>t want to use cooies. #t is
used to maintain the session. Whenever the browser sends a reuest then it is
8/14/2019 servlet notes.doc
50/103
always interpreted as a new reuest because http protocol is a stateless
protocol as it is not persistent. Whenever we want that out reuest ob)ect to
stay alive till we decide to end the reuest ob)ect then, there we use the
concept of session tracing. #n session tracing firstly a session ob)ect is
created when the first reuest goes to the server. (hen server creates a toen
which will be used to maintain the session. (he toen is transmitted to the
client by the response ob)ect and gets stored on the client machine. %y default
the server creates a cooie and the cooie get stored on the client machine.
6. %ooAies: When cooie based session management is used, a toen is
generated which contains user>s information, is sent to the browser by the
server. (he cooie is sent bac to the server when the user sends a new
reuest. %y this cooie, the server is able to identify the user. #n this way the
session is maintained. &ooie is nothing but a name- value pair, which is
stored on the client machine. %y default the cooie is implemented in most of
the browsers. #f we want then we can also disable the cooie. @or security
reasons, cooie based session management uses two types of cooies.
o *etermine +"et"er t"e Session is $e+ or ld
#n this program we are going to mae one servlet on session in which we will chec
whether the session is new or old.
(o mae this program firstly we need to mae one class named
%hecAing3heSession. #nside the 'o?et(!method, which taes two ob)ects one of
reuest and second of response. #nside this method call the method getWriter(!of
the response ob)ect. Use getSession(! of the reuest ob)ect, which returns the
8ttpSession ob)ect. =ow by using the 8ttpSessionwe can find out whether the
session is new or old.
8/14/2019 servlet notes.doc
51/103
3he co'e of the progra" is given below:
import java.io.*;import javax.servlet.*;import javax.servlet.http.*;
public class "hecLin#heSession extends HttpServlet{protected void doGet(HttpServletRequest request, HttpServletResponse response throws ServletException, !Exception { response.set"ontent#$pe(%text&ht'l%; )rintWriter p + response.etWriter(; p.println(%"hecLin hether the session is ne or old-/r%; HttpSession session + request.etSession(; if(session.isAe({ p.println(%:ou have created a ne session%; 1 else{ p.println(%Session alread$ exists%;
1 11
web.x"l file for this progra":
-2x'l version+%0.3% encodin+%S!4556740%2-844-89!"#:)E e/4app)
8/14/2019 servlet notes.doc
52/103
#re- ./isting Session
#n this e*ample we are going to find out whether the session ispre-existingor not.
&onsider a situation where servlet want to use only a e*isting session. #t is not
always a good idea to create a new session. (o perform this wor we have one
overloaded method getSession(boolean!of the reuest ob)ect. #f we don>t want to
create a new session then we should use getSession(false!.
#n the e*ample below we have used the method getSession(false!which will test
whether the session is null or not. #f there will be no session then the new session
will be created by the method getSession(!.
3he co'e of the progra" is given below:
PreExistingSessionServlet.ava
import java.io.*;
8/14/2019 servlet notes.doc
53/103
import javax.servlet.*;import javax.servlet.http.*;
public class )reExistinSessionServlet extends HttpServlet{protected void doGet(HttpServletRequest request, HttpServletResponse response throws ServletException, !Exception {
response.set"ontent#$pe(%text&ht'l%; )rintWriter p + response.etWriter(; p.println(%#estin #he Session B %; HttpSession session + request.etSession(false; if(session++null{ p.println(%#here is no session%; p.println(%"an e create a session For $ou. "reatin.........%; session + request.etSession(; 1 else{ p.println(%Session alread$ exists%; 1 11
web.x"l file for this progra":
-2x'l version+%0.3% encodin+%S!4556740%2-89!"#:)E e/4app)
8/14/2019 servlet notes.doc
54/103
Session Last Accessed ime ./ample
(his e*ample illustrates to find current access time of session and last access time of
session. Sessions are used to maintain state and user identity across multiple page
reuests. !n implementation of 'ttpSession represents the server>s view of the
session. (he server considers a session to be new until it has been )oined by the
client. Until the client )oins the session, is=ew45 method returns true.
8ere is the source co'e of ;astccess3i"e.ava
import java.io.*;import javax.servlet.*;import javax.servlet.http.*;import java.net.*;import java.util.*;import javax.servlet.Servlet"onFi;import javax.servlet.ServletException;import javax.servlet.Servlet!utputStrea';import javax.servlet.http.HttpSession;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;
public class =astccess#i'e extends HttpServlet {public void doGet(HttpServletRequest request,HttpServletResponse response throws ServletException, !Exception {
8/14/2019 servlet notes.doc
55/103
HttpSession session + request.etSession(true; response.set"ontent#$pe(%text&ht'l%; )rintWriter out + response.etWriter(; Strin head; nteer count + new nteer(3; if (session.isAe( { head + %Ae Session Ialue %; 1 else { head + %!ld Session value%; nteer oldcount +(nteersession.etIalue(%count%;
if (oldcount 8+ null { count + new nteer(oldcount.intIalue( D 0; 1 1 session.putIalue(%count%, count;
out.println(%-H#>=-
session was created. (he get;astccesse'3i"e(!method is used to find when last
time session was accessed by the user.
8ere is the "apping of servlet (B;astccess3i"e.avaB! in the web.x"l file:
0servlet1
0servlet-name1ast!ccess(ime0servlet-
name1
0servlet-class1ast!ccess(ime0servlet-
class1
0servlet1
0servlet-mapping1
0servlet-name1ast!ccess(ime0servlet-
8/14/2019 servlet notes.doc
56/103
name1
0url-pattern1ast!ccess(ime0url-pattern1
0servlet-mapping1
Running the servlet by this url:
http:
8/14/2019 servlet notes.doc
57/103
Get Session Id
#n this e*ample we are going to mae a program in which we will find the session id
which was generated by the container.
8ttpSession session C reDuest.getSession(!#nside the service method we as for
the session and every thing gets automatically, lie the creation of the 'ttpSession
ob)ect. (here is no need to generate the uniue session id. (here is no need to mae
a new &ooie ob)ect. ?verything happens automatically behind the scenes.
!s soon as call the method getSession(!of the reuest ob)ect a new ob)ect of the
session gets created by the container and a uniue session id generated to maintain
the session. (his session id is transmitted bac to the response ob)ect so that
whenever the client maes any reuest then it should also attach the session id with
the reuest ob)ect so that the container can identify the session.
3he co'e of the progra" is given below:
import java.io.*;import javax.servlet.*;import javax.servlet.http.*;
public class SessiondServlet extends HttpServlet{protected void doGet(HttpServletRequest request, HttpServletResponse response throws ServletException, !Exception{ response.set"ontent#$pe(%text&ht'l%; )rintWriter p + response.etWriter(; HttpSession session + request.etSession(; Strin id + session.etd(; p.println(%Session d is B % D id; 11
web.x"l file for this progra":
-2x'l version+%0.3% encodin+%S!4556740%2-89!"#:)E e/4app)
8/14/2019 servlet notes.doc
58/103
%httpB&&java.sun.co'&dtd&e/[email protected]%
-e/4app-servlet-servlet4na'eulFiqar-&servlet4na'e-servlet4classSessiondServlet-&servlet4class
-&servlet-servlet4'appin-servlet4na'eulFiqar-&servlet4na'e-url4pattern&SessiondServlet-&url4pattern-&servlet4'appin-&e/4app
3he output of the progra" is given below:
*isplay session value %sing Servlet
Sometime while developing web application it is necessary to interact with the
different values of the Session ob)ect. #n this e*ample we will e*plore the different
values of the Session ob)ect and then learn how to use it in our programming code.
Bou will learn how to find all the session related information lie+
getI'.(his method is used to find the identifier of the session which is
uniue.
8/14/2019 servlet notes.doc
59/103
is+ew.(his method is used when find, whether session is newly created or
pree*isted. #f session has never seen by user then this method return PtrueP but
if session is pree*isted then it return PfalseP.
get%reation3i"e.(his method is used to find the creation time of session. (o
use of this method we can find the following details about session i.e. day,
month, date, time, 8M(4?reenwich 9ean 3i"e5 and year will be displayed.
get;astccesse'3i"e.(his method is used to find the last accessed time of
session. #t returns the time, in milliseconds.
get9axInactiveInterval.(his method returns the total time, in seconds,
during which session remains active if user does not accesses the session for
this ma*imum time interval. !fter this time the session will be invalidated
automatically. ! negative value indicates that the session should never
timeout.
8ere is the sa"ple co'e for 8ttpSession4isplay.ava:
import java.io.*;import javax.servlet.*;import javax.servlet.http.*;import java.net.*;import java.util.*;
public class HttpSession9ispla$ extends HttpServlet
{ Strin head;
public void doGet(HttpServletRequest request, HttpServletResponse response throws ServletException, !Exception
{ HttpSession session + request.etSession(true; response.set"ontent#$pe(%text&ht'l%; )rintWriter out + response.etWriter(; nteer count + new nteer(3;
8/14/2019 servlet notes.doc
60/103
if (session.isAe( { head + %Ae Session Ialue%; 1 else { head + %!ld Session value%; nteer oldcount +(nteersession.etIalue(%count%
if (oldcount 8+ null { count + new nteer(oldcount.intIalue( D 0; 1 1 session.putIalue(%count%, count;
out.println(%-H#>=-
%-#R
0servlet1
0servlet-name1'ttpSession$isplay0servlet-name1
0servlet-class1'ttpSession$isplay0servlet-class1
0servlet1
0servlet-mapping1
0servlet-name1'ttpSession$isplay0servlet-name1
8/14/2019 servlet notes.doc
61/103
0url-pattern1'ttpSession$isplay0url-pattern1
0servlet-mapping1
Run this exa"ple by this url:
http:
8/14/2019 servlet notes.doc
62/103
Hit Counter Servlet ./ample
(his e*ample illustrates about counting how many times the servlet is accessed.
When first time servlet 4%ounterServlet5 runs then session is created and value of
the counter will be 3ero and after again accessing of servlet the counter value will
be increased by one. #n this program is+ew(!method is used whether session is new
or old and get6alue(!method is used to get the value of counter.
8ere is the source co'e of %ounterServlet.ava:
import java.io.*;import javax.servlet.*;import javax.servlet.http.*;
public class "ounterServlet extends HttpServlet{public void doGet(HttpServletRequest request, HttpServletResponse response
throws ServletException, !Exception { HttpSession session + request.etSession(true; response.set"ontent#$pe(%text&ht'l%; )rintWriter out + response.etWriter(; nteer count + new nteer(3; Strin head; if (session.isAe( { head + %#his is the Ae Session%; 1 else {
8/14/2019 servlet notes.doc
63/103
head + %#his is the old Session%; nteer oldcount +(nteersession.etIalue(%count%;
if (oldcount 8+ null { count + new nteer(oldcount.intIalue( D 0; 1 1 session.putIalue(%count%, count; out.println(%-H#>=-
D% -#HnFor'ation #$pe-#HSession "ountJn%D%-#RJn% D% -#9#otal Session ccessesJn% D
%-#9% D count D %Jn% D %-
9apping of Servlet (B%ounterServlet.avaB! in web.x"l file
0servlet1
0servlet-name1&ounterServlet0servlet-name1
0servlet-class1&ounterServlet0servlet-class1
0servlet1
0servlet-mapping1
0servlet-name1&ounterServlet0servlet-name1
0url-pattern1&ounterServlet0url-pattern1
0servlet-mapping1
Running the servlet by this url:
http:
8/14/2019 servlet notes.doc
64/103
When servlet is hit two ti"es by the user the counter value will be increase' by
two as shown in figure below:
Inserting *ata In *ata0ase ta0le using Statement
#n this program we are going to insert the data in the database from our )ava program
in the table stored in the database.
(o accomplish our goal we first have to mae a class named as
ServletInserting4ata,which must e*tends the abstract 8ttpServletclass, the name
of the class should be such that other person can understand what this program is
going to perform. (he logic of the program will be written inside the 'o?et(!
method that taes two arguments, first is HttpServletRequest interface and the
second one is the HttpServletResponse interface and this method can throw
ServletException.
#nside this method call the getWriter(! method of the PrintWriterclass. We can
insert the data in the database only and only if there is a connectivity between our
database and the )ava program. (o establish the connection between our database
and the )ava program we first need to call the method for+a"e(!,which is static in
nature of the class &lass. #t taes one argument which tells about the database driver
8/14/2019 servlet notes.doc
65/103
we are going to use. =ow use the static method get%onnection(! of the
4river9anager class. (his method taes three arguments and returns the
Connectionob)ect. SR statements are e*ecuted and results are returned within the
conte*t of a connection. =ow your connection has been established. =ow use the
method createState"ent(! of the Connectionob)ect which will return the Statement
ob)ect. (his ob)ect is used for e*ecuting a static SR statement and obtaining the
results produced by it. We have to insert values into the table so we need to write a
uery for inserting the values into the table. (his uery we will write inside the
execute@p'ate(!method of the Statement ob)ect. (his method returns int value.
#f the record will get inserted in the table then output will show Precord has been
inserted otherwise PsorryN failureP.
3he co'e of the progra" is given below:
import java.io.*;import java.sql.*;import javax.servlet.*;import javax.servlet.http.*;
public class 9atansertion extends HttpServlet
{public void doGet(HttpServletRequest request,
HttpServletResponse response throwsServletException, !Exception{
response.set"ontent#$pe(%text&ht'l%; )rintWriter out + response.etWriter(; "onnection conn; ResultSet rs; try{ "lass.ForAa'e(%sun.jd/c.od/c.Qd/c!d/c9river%; conn + 9river>anaer.et"onnection(Ujd/cBod/cBdsn6V; State'ent state'ent + conn.createState'ent(; Strin quer$ + %nsert into ser values(sanja$X,XLrutiLX%;
int i + state'ent.executepdate(quer$; if(i8+3{ out.println(%#he record has /een inserted%;
8/14/2019 servlet notes.doc
66/103
1 else{ out.println(%Sorr$8 ailure%; 1
rs + state'ent.executeYuer$(%select * Fro' ser%; while(rs.next({ out.println(%-p-ta/le% D rs.etStrin(0
D % % D rs.etStrin(? D %-&p -&ta/le%; 1 rs.close(; state'ent.close(; 1 catch (Exception e{ S$ste'.out.println(e; 1 1
1
web.x"l file for this progra"
-2x'l version+%0.3% encodin+%S!4556740%2-844-89!"#:)E e/4app)
8/14/2019 servlet notes.doc
67/103
3able in the 'atabase after Insertion:
mysl1 select from empHsalT
------------------
?mp=ame salary ------------------
3ulfiar /:GGG
------------------
/ row in set 4G.G2 sec5
'etrieving *ata from t"e ta0le using Statement
#n this program we are going to fetch the data from the database in the table from
our )ava program.
(o accomplish our goal we first have to mae a class named as
Servletetching4atawhich must e*tends the abstract 8ttpServletclass, the name
of the class should be such that the other person can understand what this program is
going to perform. (he logic of the program will be written inside the 'o?et(!
method which taes two arguments, first is HttpServletRequest interface and the
second one is the HttpServletResponse interface and this method can throw
ServletException.
#nside this method call the getWriter(! method of the PrintWriterclass. We can
retrieve the data from the database only and only if there is a connectivity between
8/14/2019 servlet notes.doc
68/103
our database and the )ava program. (o establish the connection between our
database and the )ava program we firstly need to call the method for+a"e(!which
is static in nature of the class %lass;oa'er. #t taes one argument which tells about
the database driver we are going to use. =ow use the static method get%onnection(!
of the 4river9anager class. (his method taes three arguments and returns the
Connectionob)ect. SR statements are e*ecuted and results are returned within the
conte*t of a connection. =ow your connection has been established. =ow use the
method createState"ent(! of the Connectionob)ect which will return the Statement
ob)ect. (his ob)ect is used for e*ecuting a static SR statement and obtaining the
results produced by it. !s we need to retrieve the data from the table so we need to
write a uery to select all the records from the table. (his uery will be passed in the
executeFuery(! method of Statement ob)ect, which returns the ResultSet ob)ect.
=ow the data will be retrieved by using the getString(! method of the ResultSet
ob)ect.
3he co'e of the progra" is given below:
8/14/2019 servlet notes.doc
69/103
import java.io.*;import java.sql.*;import javax.servlet.*;import javax.servlet.http.*;
public class Servletetchin9ataro'9ata/ase0 extends HttpServlet{public void doGet(HttpServletRequest request, HttpServletResponse response thr
ServletException, !Exception{ response.set"ontent#$pe(%text&ht'l%; )rintWriter p + response.etWriter(; Strin connectionR= + %jd/cB'$sqlB&&localhost&ulFiqar%; "onnection connection+null; try{ "lass.ForAa'e(%co'..'$sql.9river%; connection + 9river>anaer.et"onnection(connectionR=, %root%, %ad'in%; State'ent st + connection.createState'ent(; ResultSet rs + st.executeYuer$(%Select * Fro' e'pCsal%; while(rs.next({ p.println(%E'pAa'e% D % % D %E'pSalar$% D %-/r%;
p.println(rs.etStrin(0 D % % D rs.etStrin(? D %-/r%; 1 1 catch (Exception e{ p.println(e; 1 11
web.x"l file for this progra":
-2x'l version+%0.3% encodin+%S!4556740%2-844-89!"#:)E e/4app)
8/14/2019 servlet notes.doc
70/103
3he output of the progra" is given below:
Inserting data from t"e H!L page to t"e data0ase
#n this program we are going to mae program in which we are going to insert the
values in the database table from the html form.
(o mae our program woring we need to mae one html form in which we will
have two fields, one is for the name and the other one is for entering the password.
!t last we will have the submit form, clicing on which the values will be passed to
the server.
(he values which we have entered in the 'tml form will be retrieved by the server
side program which we are going to write. (o accomplish our goal we first have to
mysl1 select from empHsalT
------------------ ?mp=ame salary
------------------
3ulfiar /:GGG
vinod /2GGG
------------------
2 rows in set 4G.GG sec5
8/14/2019 servlet notes.doc
71/103
mae a class named as ServletInserting4ata@sing8t"lwhich must e*tends the
abstract 8ttpServletclass, the name of the class should be such that the other
person can understand what this program is going to perform. (he logic of the
program will be written inside the 'o?et(!method which taes two arguments, first
is HttpServletRequest interface and the second one is the HttpServletResponse
interface and this method can throw ServletException.
#nside this method call the getWriter(! method of the PrintWriterclass. We can
insert the data in the database only and only if there is a connectivity between our
database and the )ava program. (o establish the connection between our database
and the )ava program we firstly need to call the method for+a"e(!which is static in
nature of the class &lass. #t taes one argument which tells about the database driver
we are going to use. =ow use the static method get%onnection(! of the
4river9anager class. (his method taes three arguments and returns the
Connectionob)ect. SR statements are e*ecuted and results are returned within the
conte*t of a connection. =ow your connection has been established. =ow use the
method prepareState"ent(! of the Connection ob)ect which will return the
PreparedStatementob)ect and taes one a uery which we want to fire as its input.
(he values which we have got from the html will be set in the database by using the
setString(!method of thePreparedStatementob)ect.
#f the record will get inserted in the table then output will show Precord has been
insertedP otherwise PsorryN @ailureP.
3he co'e of the progra" is given below:
-ht'l
-head-titleAe )ae 0-&title
8/14/2019 servlet notes.doc
72/103
-&head
-/od$
-For' 'ethod+%)!S#% action+%&n9ata
8/14/2019 servlet notes.doc
73/103
p.println(s?; "lass.ForAa'e(%444%; connection + 9river>anaer.et"onnection(4444 ;
)reparedState'ent pst +connection.prepareState'ent(%insert into ser values(2,2%; pst.setStrin(0,s0; pst.setStrin(?,s?; int i + pst.executepdate(; if(i8+3{ p.println(%-/rRecord has /een inserted%; 1 else{ p.println(%Failed to insert the data%; 1 1 catch (Exception e{ p.println(e; 1 1
1
web.x"l file for this progra":
-2x'l version+%0.3% encodin+%S!4556740%2-89!"#:)E e/4app)
8/14/2019 servlet notes.doc
74/103
3he output of the progra" is given below:
3his is the output of the above input.
'etrieving data from t"e ta0le using #reparedStatement
#n this program we are going to fetch the data from the database in the table from
our )ava program using Prepare'State"ent.
(o accomplish our goal we first have to mae a class named as
Servletetching4ataro"4atabasewhich must e*tends the abstract 8ttpServlet
class, the name of the class should be such that the other person can understand what
this program is going to perform. (he logic of the program will be written inside the
8/14/2019 servlet notes.doc
75/103
'o?et(! method which taes two arguments, first is HttpServletRequest interface
and the second one is theHttpServletResponseinterface and this method can throw
ServletException.
#nside this method call the getWriter(! method of the PrintWriterclass. We can
retrieve the data from the database only and only if there is a connectivity between
our database and the )ava program. (o establish the connection between our
database and the )ava program we firstly need to call the method for+a"e(!which
is static in nature of the class %lass;oa'er. #t taes one argument which tells about
the database driver we are going to use. =ow use the static method get%onnection(!
of the 4river9anager class. (his method taes three arguments and returns the
Connectionob)ect. SR statements are e*ecuted and results are returned within the
conte*t of a connection. =ow your connection has been established. =ow use the
method prepareState"ent(! of the Connection ob)ect which will return the
PreparedStatementob)ect and taes a uery as its parameter. #n this uery we will
write the tas we want to perform. (heResultsetob)ect will be retrieved by using the
e*ecuteRuery45 method of the PreparedStatement ob)ect. =ow the data will be
retrieved by using the getString(!method of theResultSetob)ect.
3he co'e of the progra" is given below:
8/14/2019 servlet notes.doc
76/103
import java.io.*;import java.sql.*;import javax.servlet.*;import javax.servlet.http.*;
public class Servletetchin9ataro'9ata/ase extends HttpSpublic void doGet(HttpServletRequest request, HttpServle throws ServletException, !Exceptio { response.set"ontent#$pe(%text&ht'l%; )rintWriter p + response.etWriter(; Strin connectionR= + %jd/cB'$sqlB&&localhost&ulFiqar%; "onnection connection+null; try{ "lass.ForAa'e(%or.jt.''.'$sql.9river%; connection + 9river>anaer.et"onnection(connectionR=, %root%, %ad'in%; )reparedState'ent pst + connection.prepareState'ent(%Select * Fro' e'pCsal%
ResultSet rs + pst.executeYuer$(; while(rs.next({ p.println(rs.etStrin(0 D% % D rs.etStrin(?D%-/r%; 1 1 catch (Exception e{ p.println(e; 1 p.println(%hello%; 11
3he output of the progra" is given below:
8/14/2019 servlet notes.doc
77/103
3able in the 'atabase:
mysl1 select from
empHsalT
------------------ ?mp=ame salary
------------------
3ulfiar /:GGG
vinod /2GGG
------------------
2 rows in set 4G.GG sec5
Getting Columns $ames using Servlets
3he co'e of the progra" is given below:
8/14/2019 servlet notes.doc
78/103
import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.sql.*;
public class ServletGettin"olu'nsAa'es extends HttpServlet{public void doGet(HttpServletRequest request, HttpServletResponse response throws ServletException, !Exception{ response.set"ontent#$pe(%text&ht'l%; )rintWriter p + response.etWriter(; Strin connectionR= + %jd/cB'$sqlB&&localhost&ulFiqar%; "onnection connection+null; try{ "lass.ForAa'e(%or.jt.''.'$sql.9river%; connection + 9river>anaer.et"onnection(connectionR=, %root%, %ad'in%; )reparedState'ent pst + connection.prepareState'ent(%select * Fro' e'pCdeta ResultSet rs + pst.executeYuer$(; ResultSet>eta9ata rs'd + rs.et>eta9ata(; int no!F"olu'ns + rs'd.et"olu'n"ount(;
&&t shos the nu'/er oF colu'ns p.println(%#he nu'/er oF colu'ns are % D no!F"olu'ns D %-/r%; &&t shos the na'e oF the colu'ns p.println(%#he na'e oF the colu'ns areB -/r%; for(int i +0; i-+no!F"olu'ns;iDD{ Strin na'es + rs'd.et"olu'nAa'e(i; p.println(na'es; 1 1 catch(Exception e{ p.println(%#he exception is % D e; 1 11
web.x"l ile for this progra":
-2x'l version+%0.3% encodin+%S!4556740%2-89!"#:)E e/4app)
8/14/2019 servlet notes.doc
79/103
3able in the 'atabase:
mysl1 select from empHdetailsT
--------------------------------------
-----------------------------------
user#d =ame surname address/
address2 town country 3ipcode
--------------------------------------
----------------------------------
-
8/14/2019 servlet notes.doc
80/103
import java.io.*;import java.sql.*;import javax.servlet.*;import javax.servlet.http.*;
public class ServletGettinAo!F"olu'ns extends HttpServletpublic void doGet(HttpServletRequest request, HttpServle throws ServletException, !Exception{ response.set"ontent#$pe(%text&ht'l%; )rintWriter p + response.etWriter(; Strin connectionR= + %jd/cB'$sqlB&&localhost&ulFiqar%; "onnection connection+null; try{ "lass.ForAa'e(%co'.'$sql.jd/c.9river%.nenstance(; connection + 9river>anaer.et"onnection(connectionR=, %root%, %ad'in%; )reparedState'ent pst + connection.prepareState'ent(%select * Fro' e'pCdeta ResultSet rs + pst.executeYuer$(;
ResultSet>eta9ata rs'd + rs.et>eta9ata(; int no!F"olu'ns + rs'd.et"olu'n"ount(; &&t shos the nu'/er oF colu'ns p.println(%#he nu'/er oF colu'ns are % D no!F"olu'ns; 1 catch(Exception e{ p.println(%#he exception is % D e; 1 11
web.x"l file for this progra":
-2x'l version+%0.3% encodin+%S!4556740%2-89!"#:)E e/4app)
8/14/2019 servlet notes.doc
81/103
------------------------------------------------
------------------------
--
user#d =ame surname address/ address2
town country 3ipcode
------------------------------------------------
------------------------
--
;6
8/14/2019 servlet notes.doc
82/103
import java.io.*;import java.sql.*;import javax.servlet.*;import javax.servlet.http.*;
public class ServletGettinAo!FRos extends HttpServlet{public void doGet(HttpServletRequest request, HttpServle throws ServletException, !Exception{ int ros+3; response.set"ontent#$pe(%text&ht'l%; )rintWriter p + response.etWriter(; Strin connectionR= + %jd/cB'$sqlB&&localhost&ulFiqar%; "onnection connection; try{ "lass.ForAa'e(%or.jt.''.'$sql.9river%; connection + 9river>anaer.et"onnection(connectionR=, %root%, %ad'in%; )reparedState'ent pst + connection.prepareState'ent(%%;
ResultSet rs + pst.executeYuer$(%select count(* Fro' e'pCsal%; while (rs.next({ ros + rs.etnt(0; 1 p.println(%#he nu'/er oF ros are % D ros; 1 catch(Exception e{ p.println(%#he exception is % D e; 1 11
web.x"l ile for this progra":
-2x'l version+%0.3% encodin+%S!4556740%2-89!"#:)E e/4app)
8/14/2019 servlet notes.doc
83/103
mysl1 select from empHsalT
------------------
?mp=ame salary
------------------
3ulfiar /:GGG vinod /2GGG
------------------
2 rows in set 4G.G: sec5
3he output of the progra" is given below:
*eleting 'o+s from a0le
3he co'e of the progra" is given below:
import javax.servlet.*;import javax.servlet.http.*;import java.io.*;import java.sql.*;
public class Servlet9eletinRosro'#a/le extends HttpServlet{public void doGet(HttpServletRequest request, HttpServletResponse response thr ServletException, !Exception{ int ros;
response.set"ontent#$pe(%text&ht'l%; )rintWriter p + response.etWriter(; Strin connectionR= + %jd/cB'$sqlB&&localhost&ulFiqar%; "onnection connection; try{ "lass.ForAa'e(%or.jt.''.'$sql.9river%; connection + 9river>anaer.et"onnection(connectionR=, %root%, %ad'in%; )reparedState'ent pst + connection.prepareState'ent (%delete Fro' e'pCsal here E'pAa'e + [vinod[%; int i + pst.executepdate(;
8/14/2019 servlet notes.doc
84/103
if (i++3{ p.println(%Ro has /een deleted%; 1 else{ p.println(%Ao ros has /een deleted%; 1
1 catch(Exception e{ p.println(%#he exception is % D e; 1 11
web.x"l file for this progra":
-2x'l version+%0.3% encodin+%S!4556740%2-89!"#:)E e/4app)
8/14/2019 servlet notes.doc
85/103
3able in the 'atabase after 'eletion:
mysl1 select from empHsalT
------------------
?mp=ame salary
------------------
3ulfiar /:GGG
------------------
/ row in set 4G.G: sec5
*eleting All 'o+s &rom t"e data0ase a0le
3he co'e of the progra" is given below:
8/14/2019 servlet notes.doc
86/103
import java.io.*;import java.sql.*;import javax.servlet.*;import javax.servlet.http.*;
public class Servlet9eletinllRosro'#a/le extends HttpServlet{public void doGet(HttpServletRequest request, HttpServletResponse response throws ServletException, !Exception{ response.set"ontent#$pe(%text&ht'l%; )rintWriter p + response.etWriter(; Strin connectionR= + %jd/cB'$sqlB&&localhost&ulFiqar%; "onnection connection; try{ "lass.ForAa'e(%or.jt.''.'$sql.9river%; connection + 9river>anaer.et"onnection(connectionR=, %root%, %ad'in%; )reparedState'ent pst + connection.prepareState'ent(%delete Fro' e'pCsal%; int i + pst.executepdate(; if (i++3{ p.println(%ll ros are deleted%;
1 else{ p.println(%no ros has /een deleted%; 1 1 catch(Exception e{ p.println(%#he exception is % D e; 1 11
web.x"l file for this progra":
-2x'l version+%0.3% encodin+%S!4556740%2-89!"#:)E e/4app)
8/14/2019 servlet notes.doc
87/103
mysl1 select from empHsalT
------------------
?mp=ame salary
------------------
3ulfiar /:GGG vinod /2GGG
------------------
2 rows in set 4G.GG sec5
3he output of the progra" is given below:
3able in the 'atabase after 'eletion:
mysl1 select from empHsalT
?mpty set 4G.G2 sec5
Ho+ to add a column in a ta0le
&onsider a situation where the reuirement of the client gets changed and you have
ased to modify the structure of the table. #n reality it is the wor of the database
administrator but as a Java programmer you should now how you can modify thestructure of the table. (he problem is that we have to add a new column to our
database by using the )ava program. (here is no need to get panic. What we simply
need is to use a Dueryfor adding a new column in the database table.
8/14/2019 servlet notes.doc
88/103
(o get the desired result firstly we need to mae a connection with our database.
!fter connection has been established pass the uery in the prepareState"ent(! for
adding new column in the database. (his method will return the
Prepare'State"ent ob)ect. %y the ob)ect of the Prepare'State"ent we will call
the execute@p'ate(!which will tell the status of the table.
3he co'e of the exa"ple is given below:
import java.io.*;import java.sql.*;import javax.servlet.*;import javax.servlet.http.*;
public class ServletddinAe"olu'n extends HttpServlet{public void doGet(HttpServletRequest request, HttpServletResponse response thr
ServletException, !Exception{ response.set"ontent#$pe(%text&ht'l%; )rintWriter p + response.etWriter(; Strin connectionR= + %jd/cB'$sqlB&&localhost&ulFiqar%; "onnection connection; try{ "lass.ForAa'e(%or.jt.''.'$sql.9river%; connection + 9river>anaer.et"onnection(connectionR=, %root%, %ad'in%; )reparedState'ent pst + connection.prepareState'ent (%alter ta/le e'pCdetails add colu'n sal int(6%; int i + pst.executepdate(; if (i++0{ p.println(%"olu'n has /een added%; 1 else{ p.println(%Ao colu'n has /een added%; 1
1 catch(Exception e{ p.println(%#he exception is % D e; 1 11
web.x"l file for this progra":
8/14/2019 servlet notes.doc
89/103
-2x'l version+%0.3% encodin+%S!4556740%2-89!"#:)E e/4app)t mean
that you can>t send parameters to the server. %ut the total amount of characters in a
8?( is really limited. #n get method the data we send get appended to the U7 so
whatever you will send will be seen by other user so can say that it is not even
secure.
8/14/2019 servlet notes.doc
90/103
POS3
(he "ost method is more powerful reuest. %y using "ost we can reuest as well as
send some data to the server. We use post method when we have to send a big chun
of data to the server, lie when we have to send a long enuiry form then we can
send it by using the post method.
(here are few more rarely used http methods including '?!$, "U(, (7!&?,
$??(?, C"(#C=S and &C==?&(.
Select Color
#n this program we are going to selected the various color and on the basis of the
selection the output will be displayed to the user.
(o mae this program firstly we need to mae one html page. #nside the page we
will have one select option in which we will have our colors. We will also have a
submit, clicing on which the values we have entered will be transferred to the
server.
Cn the server we will create a session. (he values which we have entered in the html
form will be retrieved by the getPara"eter6alues(!of the reDuestob)ect. #t returns
the array of String. We will chec the condition if there is any session available or
not. #f yes then we will set the attribute by using the setttribute(! method of the
8ttpSession ob)ect. (he attribute we have set will be retrieved by the get!ttribute
method of the 8ttpSessionob)ect in the ne*t page and the value will be displayed
on the browser by the PrintWriterob)ect.
3he co'e of the progra" is given below:
8/14/2019 servlet notes.doc
91/103
-89!"#:)E H#>= )= N.30#ransitional&&EA%-ht'l-head
-'eta http4equiv+%"ontent4#$pe% content+%text&ht'l;charset+S!4556740%-titleSelect the list oF colors-&title-&head-/od$
-For' action + %&Servlet)roject&"olor)ae%-select na'e + %colors% sie + 6 'ultiple
-option selectedGreen-&option-optionRed-&option-option:ello-&option
-option
8/14/2019 servlet notes.doc
92/103
1
&* (non4Qava4doc* Ksee javax.servlet.http.HttpServletdoGet
(HttpServletRequest request,HttpServletResponse response*&protected void doGet(HttpServletRequest request,HttpServletResponse responsethros ServletException, !Exception {&& #!9! uto4enerated 'ethod stu/response.set"ontent#$pe(%text&ht'l%;)rintWriter p + response.etWriter(;HttpSession session + request.etSession(;
Strin colorsOP + request.et)ara'eterIalues(%colors%;iF(session8+null{session.setttri/ute(%color%,colors;session.set>axnactiventerval(T3;1p.println(%-ht'l-/od$ /color +c$an%;For(int i + 3; i-colors.lenth; iDD{p.println(%#he selected colors are% D colorsOiPD%-/r%;1p.println(%-For' action + &Servlet)roject&Get"olors%;p.println(%-input t$pe + su/'it na'e+ su/'it%;p.println(%-&For'-&/od$-&ht'l%;1
&* (non4Qava4doc* Ksee
javax.servlet.http.HttpServletdo)ost(HttpServletRequestrequest,HttpServletResponse response
*&protected void do)ost(HttpServletRequest request,HttpServletResponse responsethros ServletException, !Exception {
8/14/2019 servlet notes.doc
93/103
&& #!9! uto4enerated 'ethod stu/11
import )ava.io.T
import )ava*.servlet.T
import )ava*.servlet.http.T
Servlet implementation class for Servlet+ 8et&olors
public class 8et&olors e*tends 'ttpServlet Y
4non-Java-doc5
Fsee )ava*.servlet.http.'ttpServletL'ttpServlet45
public 8et&olors45 Y
super45T
Z
4non-Java-doc5
Fsee )ava*.servlet.http.'ttpServletLdo8et4'ttpServlet7euest reuest, 'ttpServlet7esponse response5
protected void do8et4'ttpServlet7euest reuest, 'ttpServlet7esponse response5
throws Servlet?*ception, #C?*ception Y
(C$C !uto-generated method stub
response.set&ontent(ype4Pte*thtmlP5T
"rintWriter pw Q response.getWriter45T
'ttpSession session Q reuest.getSession4false5T
if4session QQ null5
Y
pw.println4P=o session is availableP5T
pw.println4PWe are creating a session for you. &reating.....P5T
session Q reuest.getSession45T
Z
else
8/14/2019 servlet notes.doc
94/103
Y
String get&olors[\ Q 4String[\5session.get!ttribute4PcolorP5T
pw.println4P0html10body bgcolor Q cyan1P5T
for4int iQ GT i0get&olors.lengthTi5
Ypw.println4P(he selected colors are P get&olors[i\ P0br1P5T
Z
pw.println4P0html10body1P5T
Z
Z
4non-Java-doc5
Fsee )ava*.servlet.http.'ttpServletLdo"ost4
'ttpServlet7euest reuest, 'ttpServlet7esponse response5
protected void do"ost4'ttpServlet7euest reuest, 'ttpServlet7esponse response5
throws Servlet?*ception, #C?*ception Y
(C$C !uto-generated method stub
Z
Z
3he output of the progra" is given below:
8/14/2019 servlet notes.doc
95/103
send'edirect
#n send 7edirect whenever the client maes any reuest it goes to the container,
there the container decides whether the concerned servlet can handle the reuest or
not. #f not then the servlet decides that the reuest can be handle by other servlet
or )sp. (hen the servlet calls the sen'Re'irect(!method of the response ob)ect and
sends bac the response to the browser along with the status code. (hen the browser
sees the status code and loo for that servlet which can now handle the reuest.
!gain the browser maes a new reuest, but with the name of that servlet which can
now handle the reuest and the result will be displayed to you by the browser. (he
U7 will have the address of the new servlet. #n all this process the client is
unaware of the processing.
Servlet 7edirect forces the browser to do wor.
Send 'ed rect n ServletWhen we want that someone else should handle the response of our servlet, then
there we should use sen'Re'irect(!method.
8/14/2019 servlet notes.doc
96/103
#n send 7edirect whenever the client maes any reuest it goes to the container,
there the container decides whether the concerned servlet can handle the reuest or
not. #f not then the servlet decides that the reuest can be handle by other servlet
or )sp. (hen the servlet calls the sen'Re'irect(!method of the response ob)ect and
sends bac the response to the browser along with the status code. (hen the browser
sees the status code and loo for that servlet which can now handle the reuest.
!gain the browser maes a new reuest, but with the name of that servlet which can
now handle the reuest and the result will be displayed to you by the browser. #n all
this process the client is unaware of the processing.
3he co'e of the progra" is given below:
-89!"#:)E H#>= )= N.30#ransitional&&EA%-ht'l-head-'eta http4equiv+%"ontent4#$pe% content+%text&ht'l;
charset+S!4556740%-titleRedirectin the pae-&title-&head-/od$
-For' action + %&Servlet)roject&SendRedirect%'ethod + %post%
-tr-tdEnter $our na'e B-&td-td-input t$pe + %text% na'e +
%userna'e%-&td-&tr-/r-tr
-tdEnter $our passord B-&td-td-input t$pe + %passord% na'e +
%passord%-&td-&tr-/r
8/14/2019 servlet notes.doc
97/103
-tr-td-input t$pe + %su/'it% na'e +
%su/'it%-&td-&tr
-&For'-&/od$-&ht'l
import )ava.io.T
import )ava.io.#C?*ceptionT
import )ava*.servlet.Servlet?*ceptionT
import )ava*.servlet.http.'ttpServlet7euestT
import )ava*.servlet.http.'ttpServlet7esponseT
public class Send7edirect e*tends )ava*.servlet.http.'ttpServlet implements
)ava*.servlet.Servlet Y
public Send7edirect45 Y
super45T
Z
protected void do"ost4'ttpServlet7euest reuest, 'ttpServlet7esponse response5
throws
Servlet?*ception, #C?*ception Y (C$C !uto-generated method stub
response.set&ontent(ype4Pte*thtmlP5T
"rintWriter pw Q response.getWriter45T
String name Q reuest.get"arameter4PusernameP5T
String password Q reuest.get"arameter4PpasswordP5T
if4name.euals4PJamesP5]] password.euals4PabcP55
Y
response.send7edirect4PServlet"ro)ectValidUserP5T
Z
else
Y
pw.println4Pu r not a valid userP5T
Z
Z
Z
8/14/2019 servlet notes.doc
98/103
import )ava.io.T
import )ava.io.#C?*ceptionT
import )ava*.servlet.Servlet?*ceptionTimport )ava*.servlet.http.'ttpServlet7euestT
import )ava*.servlet.http.'ttpServlet7esponseT
Servlet implementation class for Servlet+ ValidUser
public class ValidUser e*tends )ava*.servlet.http.'ttpServlet implements
)ava*.servlet.Servlet Y
4non-Java-doc5 Fsee )ava*.servlet.http.'ttpServletL'ttpServlet45
public ValidUser45 Y
super45T
Z
4non-Java-doc5
Fsee )ava*.servlet.http.'ttpServletLdo8et4'ttpServlet7euest reuest,
'ttpServlet7esponse response5
protected void do8et4'ttpServlet7euest reuest, 'ttpServlet7esponse response5
throws
Servlet?*ception, #C?*ception Y
(C$C !uto-generated method stub
Z
4non-Java-doc5
Fsee )ava*.servlet.http.'ttpServletLdo"ost4'ttpServlet7euest reuest,'ttpServlet7esponse response5
protected void do"ost4'ttpServlet7euest reuest, 'ttpServlet7esponse response5
throws
Servlet?*ception, #C?*ception Y
8/14/2019 servlet notes.doc
99/103
(C$C !uto-generated method stub
"rintWriter pw Q response.getWriter45T
pw.println4PWelcome to roseindia.net0br1P5T
pw.println4Phow are youP5T
ZZ
3he output of the progra" is given below:
Servlet Conte/t
8/14/2019 servlet notes.doc
100/103
ServletContext is a interface which helps us to communicate with the servlet
container. (here is only one Servlet&onte*t for the entire web application and the
components of the web application can share it. (he information in the
Servlet&onte*t will be common to all the components. 7emember that each servlet
will have its own Servlet%onfig. (he Servet&onte*t is created by the container
when the web application is deployed and after that only the conte*t is available to
each servlet in the web application.
Web application initialiGation:
/. @irst of all the web container reads the deployment descriptor file and thencreates a namevalue pair for each 0conte*t-param1 tag.
2. !fter creating the namevalue pair it creates a new instance of Servlet&onte*t.
6. #ts the responsibility of the &ontainer to give the reference of the
Servlet&onte*t to the conte*t init parameters.
9. (he servlet and )sp which are part of the same web application can have the
access of the Servlet&onte*t.
(he &onte*t init parameters are available to the entire web application not )ust to the
single servlet lie servlet init parameters.
'ow can we do the mapping of the &onte*t init parameters in web.*ml
Hservlet
Hservlet*na"e9appingH
8/14/2019 servlet notes.doc
101/103
Hpara"*na"eE"ailH
8/14/2019 servlet notes.doc
102/103
get%reation3i"e(!: get&reation(ime45 is a method. (his is the method that returns
the time when this session was created a long integer time.
get;astccesse'3i"e(!: getast!ccessed(ime45 is a method. (his is the method
that returns the last time the client sends reuest with this session.
getI'(!: (his is the method that returns a string containing the uniue identifier
assigned to this session.
8ere is the co'e of this progra":
import java.io.*;import java.util.*;import javax.servlet.*;import javax.servlet.http.*;
public class ccessed9ateServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response
throws ServletException, !Exception { )rintWriter p + response.etWriter(;
HttpSession session + request.etSession(true;9ate create + new 9ate(session.et"reation#i'e(;9ate accessed + new 9ate(session.et=astccessed#i'e(;p.println(%9 % D session.etd(;
p.println(%"reateB % D create;p.println(%=ast