You are on page 1of 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 developers can 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 chec s 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 pac ages )ava*.servlet and )ava*.servlet.http. Servlets provides a way of creating the sophisticated server

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 li e getting the results of a database ,uery and returning to the client. "rocess and-or store the data submitted by the '(M.. Manage information about the state of a stateless '((". e.g. an online shopping car manages re,uest for multiple concurrent customers.

Life cycle of Servlet /. .oading and #nstantiation: (he servlet container loads the servlet during startup or when the first re,uest is made. (he loading of the servlet depends on the attribute 0load-on-startup1 of web.*ml file. #f the attribute 0load-onstartup1 has a positive value then the servlet is load with loading of the container otherwise it load when the first re,uest 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

any re,uest. (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 7e,uest: !fter successfully completing the initiali3ation process, the servlet will be available for service. Servlet creates separate threads for each re,uest. (he servlet container calls the service45 method for servicing any re,uest. (he service45 method determines the ind of re,uest and calls the appropriate method 4do8et45 or do"ost455 for handling the re,uest 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 re,uest, the servlet container calls the destroy45 method . .i e 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 re,uest 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.

.ife &ycle of a Servlet

Advantages of Java Servlets /. Portability 2. Powerful 6. Efficiency

9. Safety :. Integration ;. Extensibility <. Inexpensive "ortability !s we now that the servlets are written in )ava and follow well nown standardi3ed !"#s so they are highly portable across operating systems and server implementations. We can develop a servlet on Windows machine running the tomcat server or any other server and later we can deploy that servlet effortlessly on any other operating system li e Uni* server running on the i"lanet-=etscape !pplication server. So servlets are write once, run anywhere (WOR ! program. "owerful We can do several things with the servlets which were difficult or even impossible to do with &8#, for e*ample the servlets can tal directly to the web server while the &8# programs can>t do. Servlets can share data among each other, they even ma e the database connection pools easy to implement. (hey can maintain the session by using the session trac ing mechanism which helps them to maintain information from re,uest to the re,uest. #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 get loaded 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 re,uests are handled by separate threads so we can say that the servlets are highly scalable.

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 ma e it less than optimal solutions. Java Servlets changes all that.

%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 ta es significant amount of time. %ut in case of servlets initiali3ation ta es place first time it receives a re,uest and remains in memory till times out or server shut downs. !fter servlet is loaded, to handle a new re,uest 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 re,uest.

?*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 ta e all these advantages and can be e*tended from e*isting class to provide the ideal solutions. Safety Java provides very good safety features li e 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 re,uire 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

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 pac ages 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 s eleton of a servlet is given in "rogramm.

Servlets Life Cycle (he first time a servlet is invo ed, 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 e,uivalent 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

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

Cutput Screens (o appreciate the e*ecution of the servlet life cycle methods, eep refreshing the browser 4@: in Windows5. #n the bac ground, what actually happens is D with

each refresh, the do8et method is called which increments iAs value and displays the current value.

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

(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 software available for download F www.apache.org. (he current version of (omcat Server is ;.G 4as of =ovember 2GG<5. (his Server supports Java Servlets 2.: and Java Server "ages 4JS"s5 2./ specifications. #mportant software re,uired for running this server is SunAs J$E 4Java $evelopment Eit5 and J7? 4Java 7untime ?nvironment5. (he current version of J$E is ;.G. .i e (omcat, J$E is also free and is available for download at www.)ava.sun.com. &onfiguring (omcat Server Set J!V!H'CM? variable - Bou have to set this variable which points to the base installation directory of J$E installation. 4e.g. c+Iprogram fileI)avaI)d /.;.G5. Bou can either set this from the command prompt or from My &omputer -1 "roperties -1 !dvanced -1 ?nvironment Variables. Specify the Server "ort D Bou can change the server port from JGJG to JG 4if you wish to5 by editing the server.*ml file in the conf folder. (he path would be something li e this D c+Iprogram filesIapache software foundationItomcat;IconfIserver.*ml 7un (omcat Server Cnce the above pre-re,uisites are ta en care, you can test as whether the server is

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 JG5 C7 K Cpen your %rowser 4e.g. MS #nternet ?*plorer5 and type the following U7. + http+--localhost+JGJG- 4#f you have =C( changed the default port L5 #n either case, you should get a page similar to the one in @igure-J 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

(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.M nor the )ava*.servlet.http.M is part of the standard J$E. #t has to be e*clusively added in the &.!SS"!('. (he set of classes re,uired 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 application folder. (he name of the folder can be any valid and logical name that represents your application 4e.g. ban Happs, airlineHtic etsHboo ing, 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.

@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

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.

@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.

@igureD #nclude servletAs name using the 0servlet1 0-servlet1 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 0-servlet-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.

@igure D #nclude url-pattern using the 0servlet-mapping1 0-servlet-mapping1 tag +ote D "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+--localhost-demoe*amples-servletHlifecycle

@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-invo e 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 5 6 78O9E 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 %; SSP 38 inside the environment variable by using the following @or Windows O", steps.

8o to Start-1&ontrol "anel-1System-1!dvanced-1?nvironment Variables1=ew button and Set the values as 6ariable +a"e: %; SSP 38 6ariable 6alue: &+I"rogram @ilesIJavaI(omcat ;.GIlibIservlet-api.)ar @or Windows 2GGG and =( 8o to Start-1Settings-1&ontrol "anel-1System-1?nvironment Variables1=ew button and Set the values as 6ariable +a"e: %; SSP 38 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 application and 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:<<localhost:=>=><'irectory (fol'er na"e of your application! na"e<servlet na"e and press enter. #f everything is correct your servlet will run.

Writing Servlet Hello World Start by ma ing one program which will )ust print the P'ello WorldP on the browser. ?ach time the user visits this page it will display P'ello WorldP to the user. !s we now that the our servlet e*tends the 8ttpServlet and overrides the do8et45 method which it inherits from the 'ttpServlet class. (he server invo es do8et45

method whenever web server receives the 8?( re,uest from the servlet. (he do8et45 method ta es two arguments first is 'ttpServlet7e,uest ob)ect and the second one is 'ttpServlet7esponse ob)ect and this method throws the Servlet?*ception. Whenever the user sends the re,uest to the server then server generates two ob)ects, first is 'ttpServlet7e,uest ob)ect and the second one is 'ttpServlet7esponse ob)ect. 'ttpServlet7e,uest ob)ect represents the client>s re,uest and the 'ttpServlet7esponse represents the servlet>s response. #nside the do8et445 method our servlet has first used the set&ontent(ype45 method of the 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 PrintWriter class. 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, HttpServletResp throws ServletException, !Ex response.set"ontent#$pe(%text&ht'l%(; )rintWriter p* + response.,etWriter((; p*.println(%-ht'l.%(; p*.println(%-head.-title.Hello World-&title.-&title.%(; p*.println(%-/od$.%(; p*.println(%-h0.Hello World-&h0.%(; p*.println(%-&/od$.-&ht'l.%(; 1

web.x"l file for this progra": -2x'l version+%0.3% encodin,+% S!4556740%2. -844-89!"#:)E *e/4app );<= " %4&&Sun >icros$ste's, nc.&&9#9 We/ !pplication ?.@&&EA% %httpB&&java.sun.co'&dtd&*e/4appC?C@.dtd%. 44. -*e/4app. -servlet. -servlet4na'e.Hello-&servlet4na'e. -servlet4class.HelloWorld-&servlet4class. -&servlet. -servlet4'appin,. -servlet4na'e.Hello-&servlet4na'e. -url4pattern.&HelloWorld-&url4pattern. -&servlet4'appin,. -&*e/4app.

3he output of the progra" is given below:

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 4ate class of the :ava.util pac age. 3he co'e the progra" is given below: import )ava.io.*;
import java.util.*; import javax.servlet.*; import javax.servlet.http.*;

public class 9ispla$in,9ate extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response(

throws ServletException, )rintWriter p* + response.,etWriter((; 9ate toda$ + new 9ate((;

!Exception

p*.println(%-ht'l.%D%-/od$.-h0.#oda$ 9ate is-&h0.%(; p*.println(%-/.%D toda$D%-&/.-&/od$.%D %-&ht'l.%(; 1 1

web.x"l file for this progra" -2x'l version+%0.3% encodin,+% S!4556740%2. -844-89!"#:)E *e/4app );<= " %4&&Sun >icros$ste's, nc.&&9#9 We/ !pplication ?.@&&EA% %httpB&&java.sun.co'&dtd&*e/4appC?C@.dtd%. 44. -*e/4app. -servlet. -servlet4na'e.Hello-&servlet4na'e. -servlet4class.9ate9ispla$-&servlet4class. -&servlet. -servlet4'appin,. -servlet4na'e.Hello-&servlet4na'e. -url4pattern.&9ate9ispla$-&url4pattern. -&servlet4'appin,. -&*e/4app. 3he output of the progra" is given below:

Simple Counter in Servlet #n this e*ample we are going to now how we can ma e a program on counter which will eep trac how many times the servlet has been accessed. (o ma e this program firstly we have to ma e 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 ma ing 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:

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; 1 1

p*.println(%Et present the value oF the counter is % D coun

3he output of the progra" is given below:

Holistic Counter #n this program we are going to ma e a such a servlet which will count the number it has been accessed and the number of threads created by the server.

#n this e*ample firstly we are going to create one class named as 'olistic&ounter#nServlet. =ow declare a variable counter of 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 Gor Each Servlet

static Hashta/le hash#a/le + new Hashta/le((; &&Shared /$ all t

public void doGet(HttpServletRequest request, HttpServletRespon throws ServletException, { response.set"ontent#$pe(%text&ht'l%(; )rintWriter p* + response.,etWriter((; counterDD; hash#a/le.put(this,this(;

!Excep

p*.println(%#his servlet has /een accessed% D counter D %ti'e

p*.println(%#here are currentl$% D hash#a/le.siHe(( D %thread

1 1

3he output of the progra" is given below:

Counter in init( !et"od #n this program we are going to ma e 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 ma e use of the init method of the Servlet interface which ta es 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

of the Servlet&onfig interface to the value of the init parameter initial which we have defined in the deployment descriptor file. Bou need to parse the 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 "ounter n nit extends HttpServlet { int counter; super.init(conFi,(; Strin, initIalue + conFi,.,et nit)ara'eter(%initial%(; try{ counter + 1 catch(Au'/erGor'atException e( { counter + 3; 1 1 throws ServletException, counterDD; nte,er.parse nt(initIalue(;

public void init(Servlet"onFi, conFi,( throws ServletExceptio

protected void doGet(HttpServletRequest request, HttpServletR )rintWriter p* + response.,etWriter((;

!Exception {response.set"onte

p*.println(%Since loadin, this servlet has /een accessed% D c

1 1

web.x"l file for this progra": -2x'l version+%0.3%


-844-89!"#:)E *e/4app );<= " %4&&Sun >icros$ste's, nc.&&9#9 We/ !pplication ?.@&&EA% %httpB&&java.sun.co'&dtd&*e/4appC?C@.dtd%. 44. encodin,+% S!4556740%2.

-*e/4app. -servlet. -servlet4na'e.Hello-&servlet4na'e. -servlet4class."ounter n nit-&servlet4class. -&servlet. -servlet4'appin,. -servlet4na'e.Hello-&servlet4na'e. -url4pattern.&"ounter n nit-&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"l file. Whenever the container ma es a servlet it always reads it deployment descriptor file i.e. web.*ml. &ontainer creates name-value pairs for the Servlet%onfig ob)ect. Cnce the parameters are in Servlet%onfig they 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 re,uest, the service method calls either the do8et45 or

the do"ost45. %y default it will be do8et45 method. =ow inside the 'o?et(! method use getWriter(! method of the response ob)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,((.,et nit)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,((.,et nit)ara'eter(%Ed'inE'ail%((; p*.println(%#he address is % D ,etServlet"onFi,((.,et nit)ara'eter(%Eddress%((; p*.println(%#he phone no is % D ,etServlet"onFi,((.,et nit)ara'eter(%)honeAo%((; 1 1

web.x"l file of this progra":

-2x'l version+%0.3%
-89!"#:)E *e/4app

encodin,+% S!4556740%2.

);<= " %4&&Sun >icros$ste's, nc.&&9#9 We/ %httpB&&java.sun.co'&dtd&*e/4appC?C@.dtd%.

!pplication

?.@&&EA%

-*e/4app.

-servlet. -init4para'. -para'4na'e.Ed'inE'ail-&para'4na'e. -para'4value.hihelloK$ahoo.co.in-&para'4value. -&init4para'. -init4para'. -para'4na'e.Eddress-&para'4na'e. -para'4value.!Lhla-&para'4value. -&init4para'. -init4para'. -para'4na'e.)honeAo-&para'4na'e. -para'4value.73737373-&para'4value. -&init4para'. -servlet4na'e.hihello-&servlet4na'e. -servlet4class. nitServlet-&servlet4class. -&servlet. -servlet4'appin,. -servlet4na'e.hihello-&servlet4na'e. -url4pattern.& nitServlet-&url4pattern. -&servlet4'appin,. -&*e/4app.

3he output of the progra" is given below:

#assing #arameter %sing Html &orm

(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 ma e 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 re,uest will go to the server and the result will be displayed to us. #n the servlet which will wor as a controller here pic s 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 PrintWriter class. 3he co'e of the progra" is given below: -ht'l.
-head. -title.Ae* )a,e 0-&title. -&head. -/od$. -h?.=o,in-&h?. -p.)lease enter $our userna'e and pass*ord-&p. -For' 'ethod+%GE#% action+%&ht'lFor'&=o,inServlet%. -p. ;serna'e -input t$pe+%text% na'e+%userna'e% siHe+%?3%.-&p. -p. )ass*ord -input t$pe+%text% na'e+%pass*ord% siHe+%?3%.-&p. -p.-input t$pe+%su/'it% value+%Su/'it% na'e+%<0%.-&p. -&For'. -p.Mn/sp;-&p. -&/od$. -&ht'l.

;oginServlet.:ava import
java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class =o,inServlet extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response( throws ServletException, !Exception { response.set"ontent#$pe(%text&ht'l%(; )rintWriter out + response.,etWriter((; Strin, na'e + request.,et)ara'eter(%userna'e%(;

1 1

Strin, pass + request.,et)ara'eter(%pass*ord%(; 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 pass*ord B % D % % D pass D %-/r.%(; out.println(%-&/od$.-&ht'l.%(;

web.x"l file for this progra": -2x'l version+%0.3%


encodin,+% S!4556740%2. -844-89!"#:)E *e/4app );<= " %4&&Sun >icros$ste's, nc.&&9#9 We/ Epplication ?.@&&EA% %httpB&&java.sun.co'&dtd&*e/4appC?C@.dtd%. 44. -*e/4app. -servlet. -servlet4na'e.Hello-&servlet4na'e. -servlet4class.=o,inServlet-&servlet4class. -&servlet. -servlet4'appin,. -servlet4na'e.Hello-&servlet4na'e. -url4pattern.&=o,inServlet-&url4pattern. -&servlet4'appin,. -&*e/4app.

3he output of the progra" is given below:

!ultiple values for a single parameter #n our program it may be that we may have multiples values for a single parameter li e in chec bo*es. We are going to ma e one program over it. (o ma e 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 chec bo* which will have the same name but with different values. We have one more submit button, on pressing this button the re,uest will be forwarded.

=ow in the servlet that is wor ing li e a controller will retrieve the values we have entered in the html form by the method getPara"eter6alues(! which returns the array of String. !t last to retrieve all the values from the array use for loop. (he output will be displayed to you by the PrintWriter ob)ect.

3he co'e of the progra" is given below: In'ex.ht"l -89!"#:)E H#>= );<= "
%4&&W@"&&9#9 H#>= N.30 #ransitional&&EA%.

-ht'l. -head. -title. nsert title here-&title. -&head. -/od$. -For' 'ethod + %post% action + %&Get)ara'eterServlet&Get)ara'eterIalues%. -p.Which oF the *hisL$ $ou liLe 'ost-&p. -input t$pe + %checL/ox% na'e +%*hisL$% value + %Ro$al"hallen,e%.Ro$al"hallen,e.-/r. -input t$pe + %checL/ox% na'e +%*hisL$% value + %Ro$alSta,%.Ro$alSta,.-/r. -input t$pe + %checL/ox% na'e +%*hisL$% value + %<a,piper%.<a,piper.-/r. -input t$pe +%su/'it% na'e+ %su/'it%. -&For'. -&/od$. -&ht'l.

?etPara"eter6alues.:ava

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((; Strin,OP *hisL$ + request.,et)ara'eterIalues(%*hisL$%(; for(int i+3; i-*hisL$.len,th; iDD({ p*.println(%-/r.*hisL$ B % D *hisL$OiP(; 1 1 1

web.x"l file for this progra": -2x'l version+%0.3%


-844-89!"#:)E *e/4app encodin,+% S!4556740%2.

);<= " %4&&Sun >icros$ste's, nc.&&9#9 We/ !pplication ?.@&&EA% %httpB&&java.sun.co'&dtd&*e/4appC?C@.dtd%. 44. -*e/4app. -servlet. -servlet4na'e.Hello-&servlet4na'e. -servlet4class.Get)ara'eterIalues-&servlet4class. -&servlet. -servlet4'appin,. -servlet4na'e.Hello-&servlet4na'e. -url4pattern.&Get)ara'eterIalues-&url4pattern. -&servlet4'appin,. -&*e/4app.

3he output of the progra" is given below:

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.

#n send 7edirect whenever the client ma es any re,uest it goes to the container, there the container decides whether the concerned servlet can handle the re,uest or not. #f not then the servlet decides that the re,uest 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 re,uest. !gain the browser ma es a new re,uest, but with the name of that servlet which can now handle the re,uest 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 ma e 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 re,uest to the other servlet which will handle the re,uest. #f the password entered by the user is wrong then the re,uest 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. -title.Ae* )a,e 0-&title. -&head. -/od$. -For' 'ethod+%)!S#% action+%&SendRedirect&SendRedirectServlet%. -p.Enter $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% siHe+%?3%.-&p. -p.Enter $our pass*ordMn/sp; -input t$pe+%text% na'e+%pass*ord% siHe+%?3%.-&p.

-p.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;Mn/sp; -input t$pe+%su/'it% value+%Su/'it% na'e+%<0%.-&p. -&For'. -&/od$. -&ht'l.

import

java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SendRedirectServlet extends HttpServlet{ protected void do)ost(HttpServletRequest request, HttpServletResponse response( throws ServletException, !Exception { response.set"ontent#$pe(%text&ht'l%(; )rintWriter p* + response.,etWriter((; Strin, na'e + request.,et)ara'eter(%userna'e%(; Strin, pass*ord + request.,et)ara'eter(%pass*ord%(; if(na'e.equals(%Qa'es%(MM pass*ord.equals(%a/c%(({ response.sendRedirect(%&SendRedirect&Ialid;serServlet%(; 1 else{ p*.println(%u r not a valid user%(; 1 1 1

import

java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Ialid;serServlet extends HttpServlet{ protected void doGet(HttpServletRequest request, HttpServletResponse response( throws ServletException, !Exception { )rintWriter p* + response.,etWriter((; p*.println(%Welco'e to roseindia.net % D % %(; p*.println(%ho* are $ou%(; 1 1

web.x"l file for this progra":

-2x'l version+%0.3%

encodin,+% S!4556740%2. -89!"#:)E *e/4app );<= " %4&&Sun >icros$ste's, nc.&&9#9 We/ Epplication ?.@&&EA% %httpB&&java.sun.co'&dtd&*e/4appC?C@.dtd%. -*e/4app. -servlet. -servlet4na'e.RulFiqar-&servlet4na'e. -servlet4class.SendRedirectServlet-&servlet4class. -&servlet. -servlet4'appin,. -servlet4na'e.RulFiqar-&servlet4na'e. -url4pattern.&SendRedirectServlet-&url4pattern. -&servlet4'appin,. -servlet. -servlet4na'e.Hello-&servlet4na'e. -servlet4class.Ialid;serServlet-&servlet4class. -&servlet. -servlet4'appin,. -servlet4na'e.Hello-&servlet4na'e. -url4pattern.&Ialid;serServlet-&url4pattern. -&servlet4'appin,. -&*e/4app.

3he output of the progra" is given below:

Session (rac)ing !s we now that the 'ttp is a stateless protocol, means that it can>t persist the information. #t always treats each re,uest as a new re,uest. #n 'ttp client ma es a connection to the server, sends the re,uest., gets the response, and closes the connection. #n session management client first ma e a re,uest for any servlet or any page, the container receives the re,uest and generates a uni,ue session #$ and gives it bac to the client along with the response. (his #$ gets stores on the client machine. (hereafter when the client re,uest again sends a re,uest to the server then it also sends the session #d with the re,uest. (here the container sees the #d and sends bac the re,uest. Session (rac ing can be done in three ways+ /. 8i''en ,or" ,iel's: (his is one of the ways to support the session trac ing. !s we now by the name, that in this fields are added to an '(M. form which are not displayed in the client>s re,uest . (he hidden form fields are sent bac to the server when the form is submitted. #n hidden form fields the html entry will be li e 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 trac ing. @R;Rewriting can be used in place where we don>t want to use coo ies. #t is used to maintain the session. Whenever the browser sends a re,uest then it is

always interpreted as a new re,uest because http protocol is a stateless protocol as it is not persistent. Whenever we want that out re,uest ob)ect to stay alive till we decide to end the re,uest ob)ect then, there we use the concept of session trac ing. #n session trac ing firstly a session ob)ect is created when the first re,uest goes to the server. (hen server creates a to en which will be used to maintain the session. (he to en is transmitted to the client by the response ob)ect and gets stored on the client machine. %y default the server creates a coo ie and the coo ie get stored on the client machine. 6. %ooAies: When coo ie based session management is used, a to en is generated which contains user>s information, is sent to the browser by the server. (he coo ie is sent bac to the server when the user sends a new re,uest. %y this coo ie, the server is able to identify the user. #n this way the session is maintained. &oo ie is nothing but a name- value pair, which is stored on the client machine. %y default the coo ie is implemented in most of the browsers. #f we want then we can also disable the coo ie. @or security reasons, coo ie based session management uses two types of coo ies. (o *etermine +"et"er t"e Session is $e+ or ,ld #n this program we are going to ma e one servlet on session in which we will chec whether the session is new or old. (o ma e this program firstly we need to ma e one class named

%hecAing3heSession. #nside the 'o?et(! method, which ta es two ob)ects one of re,uest and second of response. #nside this method call the method getWriter(! of the response ob)ect. Use getSession(! of the re,uest ob)ect, which returns the 8ttpSession ob)ect. =ow by using the 8ttpSession we can find out whether the session is new or old.

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 1 1

web.x"l file for this progra": -2x'l version+%0.3%


encodin,+% S!4556740%2. -844-89!"#:)E *e/4app );<= " %4&&Sun >icros$ste's, nc.&&9#9 We/ Epplication ?.@&&EA% %httpB&&java.sun.co'&dtd&*e/4appC?C@.dtd%. 44. -*e/4app. -servlet. -servlet4na'e.Hello-&servlet4na'e. -servlet4class."hecLin,#heSession-&servlet4class. -&servlet. -servlet4'appin,. -servlet4na'e.Hello-&servlet4na'e. -url4pattern.&"hecLin,#heSession-&url4pattern. -&servlet4'appin,. -&*e/4app.

3he output of the progra" is given below:

#re- ./isting Session #n this e*ample we are going to find out whether the session is pre-existing or 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 re,uest 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.*;

import javax.servlet.*; import javax.servlet.http.*; public class )reExistin,SessionServlet 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 1 1

web.x"l file for this progra": -2x'l version+%0.3%


encodin,+% S!4556740%2. -89!"#:)E *e/4app );<= " %4&&Sun >icros$ste's, nc.&&9#9 We/ Epplication ?.@&&EA% %httpB&&java.sun.co'&dtd&*e/4appC?C@.dtd%. -*e/4app. -servlet. -servlet4na'e.RulFiqar-&servlet4na'e. -servlet4class.)reExistin,SessionServlet-&servlet4class. -&servlet. -servlet4'appin,. -servlet4na'e.RulFiqar-&servlet4na'e. -url4pattern.&)reExistin,SessionServlet-&url4pattern. -&servlet4'appin,. -&*e/4app.

3he output of the progra" is given below:

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 re,uests. !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 ;ast ccess3i"e.:ava import


import import import import import import import import import import java.io.*; javax.servlet.*; javax.servlet.http.*; java.net.*; java.util.*; javax.servlet.Servlet"onFi,; javax.servlet.ServletException; javax.servlet.Servlet!utputStrea'; javax.servlet.http.HttpSession; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse;

public class =astEccess#i'e extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response( throws ServletException, !Exception {

1 public void do)ost(HttpServletRequest request,HttpServletResponse response( throws ServletException, !Exception { doGet(request, response(; 1 1

HttpSession session + request.,etSession(true(; response.set"ontent#$pe(%text&ht'l%(; )rintWriter out + response.,etWriter((; Strin, head; nte,er count + new nte,er(3(; if (session.isAe*((( { head + %Ae* Session Ialue %; 1 else { head + %!ld Session value%; nte,er oldcount +( nte,er(session.,etIalue(%count%(; if (oldcount 8+ null( { count + new nte,er(oldcount.intIalue(( D 0(; 1 1 session.putIalue(%count%, count(; out.println(%-H#>=.-<!9: <G"!=!R+J%SG9G6ETJ%.Jn% D %-H? E= GA+J%"EA#ERJ%.% D head D %-&H?.Jn% D %-HN E= GA+J%"EA#ERJ%.Session Eccess #i'eB-&HN.Jn% D %-#E<=E <!R9ER+0 E= GA+"EA#ER.Jn% D %-#R <G"!=!R+J%pinLJ%.Jn% D % -#9.Session "reation #i'eJn% D% -#9.% D new 9ate(session.,et"reation#i'e((( D %Jn% D %-#R <G"!=!R+J%pinLJ%.Jn% D% -#9.=ast Session Eccess #i'eJn% D % -#9.% D new 9ate(session.,et=astEccessed#i'e((( D %-&#E<=E.Jn% D%-&<!9:.-&H#>=.%(;

4escription of co'e: #n the above servlet, is+ew(! method is used to find whether session is new or old. (he get%reation3i"e(! method is used to find the time when session was created. (he get;ast ccesse'3i"e(! method is used to find when last time session was accessed by the user. 8ere is the "apping of servlet (B;ast ccess3i"e.:avaB! in the web.x"l file: 0servlet1 0servlet-name1.ast!ccess(ime0-servletname1 0servlet-class1.ast!ccess(ime0-servletclass1 0-servlet1 0servlet-mapping1 0servlet-name1.ast!ccess(ime0-servlet-

name1 0url-pattern1-.ast!ccess(ime0-url-pattern1 0-servlet-mapping1

Running the servlet by this url: http:<<localhost:=>=><%o'ing4iaryExa"ple<;ast ccess3i"e 'isplays the output liAe below:

When user re*calls the servlet the creation ti"e will be sa"e but last accesse' ti"e will be change' as shown in the following figure:

Get Session Id #n this e*ample we are going to ma e a program in which we will find the session id which was generated by the container. 8ttpSession session C reDuest.getSession(!E #nside the service method we as for the session and every thing gets automatically, li e the creation of the 'ttpSession ob)ect. (here is no need to generate the uni,ue session id. (here is no need to ma e a new &oo ie ob)ect. ?verything happens automatically behind the scenes. !s soon as call the method getSession(! of the re,uest ob)ect a new ob)ect of the session gets created by the container and a uni,ue session id generated to maintain the session. (his session id is transmitted bac to the response ob)ect so that whenever the client ma es any re,uest then it should also attach the session id with the re,uest 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 Session dServlet 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.,et d((; p*.println(%Session d is B % D id(; 1 1

web.x"l file for this progra": -2x'l version+%0.3%


encodin,+% S!4556740%2. -89!"#:)E *e/4app );<= " %4&&Sun >icros$ste's, nc.&&9#9 We/ Epplication ?.@&&EA%

%httpB&&java.sun.co'&dtd&*e/4appC?C@.dtd%. -*e/4app. -servlet. -servlet4na'e.RulFiqar-&servlet4na'e. -servlet4class.Session dServlet-&servlet4class. -&servlet. -servlet4'appin,. -servlet4na'e.RulFiqar-&servlet4na'e. -url4pattern.&Session dServlet-&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 li e+

getI'. (his method is used to find the identifier of the session which is uni,ue.

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;ast ccesse'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
import import import import public

java.io.*; javax.servlet.*; javax.servlet.http.*; java.net.*; java.util.*; 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((; nte,er count + new nte,er(3(;

if (session.isAe*((( { head + %Ae* Session Ialue%; 1 else { head + %!ld Session value%; nte,er oldcount +( nte,er(session.,etIalue(%count%(; if (oldcount 8+ null( { count + new nte,er(oldcount.intIalue(( D 0(; 1 1 session.putIalue(%count%, count(; out.println(%-H#>=.-<!9: <G"!=!R+J%pinLJ%.Jn% D %-H? E= GA+J%"EA#ERJ%.% D head D %-&H?.Jn% D %-H@ E= GA+J%"EA#ERJ%.9escription a/out SessionB-&H@.Jn% D %-#E<=E <!R9ER+0 E= GA+"EA#ER.Jn% D %-#R <G"!=!R+J%voiletJ%.Jn% D % -#H. nFor'ation #$pe-#H.Session IalueJn% D%-#R.Jn% D% -#9. 9Jn% D %-#9.% D session.,et d(( D %Jn% D %-#R.Jn% D % -#9.Session "reation #i'eJn% D % -#9.% D new 9ate(session.,et"reation#i'e((( D %Jn% D %-#R.Jn% D% -#9.=ast Session Eccess #i'eJn% D% -#9.% D new 9ate(session.,et=astEccessed#i'e((( D %Jn% D %-#R.Jn% D% -#9.Au'/er oF )revious Session EccessesJn% D %-#9.% D count D %Jn% D %-&#E<=E.Jn% D%-&<!9:.-&H#>=.%(; 1 public void do)ost(HttpServletRequest request,
HttpServletResponse response( throws ServletException, !Exception

{
1 1

doGet(request, response(;

'ere is the mapping of class file in web.*ml. 0servlet1 0servlet-name1'ttpSession$isplay0-servlet-name1 0servlet-class1'ttpSession$isplay0-servlet-class1 0-servlet1 0servlet-mapping1 0servlet-name1'ttpSession$isplay0-servlet-name1

0url-pattern1-'ttpSession$isplay0-url-pattern1 0-servlet-mapping1 Run this exa"ple by this url: http:<<localhost:=>=><%o'ing4iaryExa"ple<8ttpSession4isplay Output: In case of first ti"e accessing of servlet the following session value will be 'isplaye'

In case of preexist session if user accesse' the servlet then the following session value will be 'isplaye'.

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((; nte,er count + new nte,er(3(; Strin, head; if (session.isAe*((( { head + %#his is the Ae* Session%; 1 else {

head + %#his is the old Session%; nte,er oldcount +( nte,er(session.,etIalue(%count%(; if (oldcount 8+ null( { count + new nte,er(oldcount.intIalue(( D 0(; 1 1 session.putIalue(%count%, count(; out.println(%-H#>=.-<!9: <G"!=!R+J%SG9G6ETJ%.Jn% D %-H? E= GA+J%"EA#ERJ%.% D head D %-&H?.Jn% D %-#E<=E <!R9ER+0 E= GA+"EA#ER.Jn% D %-#R <G"!=!R+J%SGGE933J%.Jn% D% -#H. nFor'ation #$pe-#H.Session "ountJn% D%-#R.Jn% D% -#9.#otal Session EccessesJn% D %-#9.% D count D %Jn% D %-&#E<=E.Jn% D%-&<!9:.-&H#>=.% (; 1 1

9apping of Servlet (B%ounterServlet.:avaB! in web.x"l file 0servlet1 0servlet-name1&ounterServlet0-servlet-name1 0servlet-class1&ounterServlet0-servlet-class1 0-servlet1 0servlet-mapping1 0servlet-name1&ounterServlet0-servlet-name1 0url-pattern1-&ounterServlet0-url-pattern1 0-servlet-mapping1 Running the servlet by this url: http:<<localhost:=>=><%o'ing4iaryExa"ple<%ounterServlet 'isplays the figure below:

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 ma e a class named as ServletInserting4ata, which must e*tends the abstract 8ttpServlet class, 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 ta es 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 PrintWriter class. 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 ta es 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 ta es three arguments and returns the Connection ob)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 Connection ob)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 insertedS 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 9ata nsertion extends HttpServlet

public void doGet(HttpServletRequest request, {


HttpServletResponse response( throws ServletException, !Exception

int i + state'ent.execute;pdate(quer$(; if(i8+3({ out.println(%#he record has /een inserted%(;

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>ana,er.,et"onnection(Ujd/cBod/cBdsn6V(; State'ent state'ent + conn.createState'ent((; Strin, quer$ + % nsert into ;ser values(Wsanja$X,XLrutiLX(%;

1 1

1 catch (Exception e({ S$ste'.out.println(e(; 1

-&ta/le.%(; 1 rs.close((; state'ent.close((;

1 else{ out.println(%Sorr$8 Gailure%(; 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.

web.x"l file for this progra" -2x'l version+%0.3%


encodin,+% S!4556740%2.

-844-89!"#:)E *e/4app );<= " %4&&Sun >icros$ste's, nc.&&9#9 We/ Epplication ?.@&&EA% %httpB&&java.sun.co'&dtd&*e/4appC?C@.dtd%. 44. -*e/4app. -servlet. -servlet4na'e.Hello-&servlet4na'e. -servlet4class.9ata nsertion-&servlet4class. -&servlet. -servlet4'appin,. -servlet4na'e.Hello-&servlet4na'e. -url4pattern.&9ata nsertion-&url4pattern. -&servlet4'appin,. -&*e/4app.

3able in the 'atabase before Insertion: mys,l1 select M from empHsalT ?mpty set 4G.G2 sec5 3he output of the progra" is given below:

3able in the 'atabase after Insertion: mys,l1 select M from empHsalT U----------U--------U V ?mp=ame V salary V U----------U--------U V 3ulfi,ar V /:GGG V U----------U--------U / 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 ma e a class named as Servlet,etching4ata which 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 'o?et(! method which ta es 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 PrintWriter class. 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 ta es 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 ta es three arguments and returns the Connection ob)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 Connection ob)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:

import

java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class ServletGetchin,9ataGro'9ata/ase0 extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response( throws ServletException, !Exception{ response.set"ontent#$pe(%text&ht'l%(; )rintWriter p* + response.,etWriter((; Strin, connection;R= + %jd/cB'$sqlB&&localhost&HulFiqar%; "onnection connection+null; try{ "lass.ForAa'e(%co'..'$sql.9river%(; connection + 9river>ana,er.,et"onnection(connection;R=, %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 1 1

web.x"l file for this progra": -2x'l version+%0.3%


encodin,+% S!4556740%2. -844-89!"#:)E *e/4app );<= " %4&&Sun >icros$ste's, nc.&&9#9 We/ Epplication ?.@&&EA% %httpB&&java.sun.co'&dtd&*e/4appC?C@.dtd%. 44. -*e/4app. -servlet. -servlet4na'e.Hello-&servlet4na'e. -servlet4class.ServletGetchin,9ataGro'9ata/ase-&servlet4class. -&servlet. -servlet4'appin,. -servlet4na'e.Hello-&servlet4na'e. -url4pattern.&ServletGetchin,9ataGro'9ata/ase-&url4pattern. -&servlet4'appin,. -&*e/4app.

3he output of the progra" is given below:

mys,l1 select M from empHsalT U----------U--------U V ?mp=ame V salary V U----------U--------U V 3ulfi,ar V /:GGG V V vinod V /2GGG V U----------U--------U 2 rows in set 4G.GG sec5

Inserting data from t"e H(!L page to t"e data0ase #n this program we are going to ma e program in which we are going to insert the values in the database table from the html form. (o ma e our program wor ing we need to ma e 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, clic ing 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

ma e a class named as ServletInserting4ata@sing8t"l which 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 'o?et(! method which ta es 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 PrintWriter class. 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 ta es 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 ta es three arguments and returns the Connection ob)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 PreparedStatement ob)ect and ta es 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 the PreparedStatement ob)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. -title.Ae* )a,e 0-&title.

-&head. -/od$.

-For' 'ethod+%)!S#% action+%& n9ata<$Ht'l&Servlet nsertin,9ata;sin,Ht'l%. -844*e//ot /ot+%SaveResults% ;4Gile+%Fp*e/B&&&Cprivate&For'Cresults.txt% S4Gor'at+%#EZ#&"SI% S4=a/el4Gields+%#R;E% 44. -p.Enter Aa'eBMn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp;Mn/sp; -input t$pe+%text% na'e+%userna'e% siHe+%?3%.-&p. -p.Enter )ass*ordB -input t$pe+%text% na'e+%pass*ord% siHe+%?3%.-&p. -p.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/ -input t$pe+%su/'it% value+%Su/'it% na'e+%<0%.-&p. -&For'. -&/od$. -&ht'l.

ServletInserting4ata@sing8t"l.:ava

import
import import import import

java.io.*; java.lan,.*; java.sql.*; javax.servlet.*; javax.servlet.http.*;

public class Servlet nsertin,9ata;sin,Ht'l extends HttpServlet

public void do)ost(HttpServletRequest request, throws ServletException, !Exception

HttpServletResponse response( {

response.set"ontent#$pe(%text&ht'l%(; )rintWriter p* + response.,etWriter((; "onnection connection; try{ Strin, s0 + request.,et)ara'eter(%Fna'e%(; Strin, s? + request.,et)ara'eter(%lna'e%(; p*.println(s0(;

p*.println(s?(; "lass.ForAa'e(%444%(; connection + 9river>ana,er.,et"onnection(4444 (; )reparedState'ent pst +

connection.prepareState'ent(%insert

into ;ser values(2,2(%(;

1 1

1 catch (Exception e({ p*.println(e(; 1

pst.setStrin,(0,s0(; pst.setStrin,(?,s?(; int i + pst.execute;pdate((; if(i8+3({ p*.println(%-/r.Record has /een inserted%(; 1 else{ p*.println(%Failed to insert the data%(; 1

web.x"l file for this progra": -2x'l version+%0.3%


encodin,+% S!4556740%2. -89!"#:)E *e/4app );<= " %4&&Sun >icros$ste's, nc.&&9#9 We/ Epplication ?.@&&EA% %httpB&&java.sun.co'&dtd&*e/4appC?C@.dtd%. -*e/4app. -servlet. -servlet4na'e.RulFiqar-&servlet4na'e. -servlet4class.Servlet nsertin,9ata;sin,Ht'l-&servlet4class. -&servlet. -servlet4'appin,. -servlet4na'e.RulFiqar-&servlet4na'e. -url4pattern.&Servlet nsertin,9ata;sin,Ht'l-&url4pattern. -&servlet4'appin,. -&*e/4app.

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 ma e a class named as Servlet,etching4ata,ro"4atabase which 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

'o?et(! method which ta es 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 PrintWriter class. 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 ta es 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 ta es three arguments and returns the Connection ob)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 PreparedStatement ob)ect and ta es a ,uery as its parameter. #n this ,uery we will write the tas we want to perform. (he Resultset ob)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 the ResultSet ob)ect.

3he co'e of the progra" is given below:

import import import import

java.io.*; java.sql.*; javax.servlet.*; javax.servlet.http.*;

public class ServletGetchin,9ataGro'9ata/ase extends HttpServle public void doGet(HttpServletRequest request, HttpServletResp throws ServletException, !Exception
{ response.set"ontent#$pe(%text&ht'l%(; )rintWriter p* + response.,etWriter((; Strin, connection;R= + %jd/cB'$sqlB&&localhost&HulFiqar%; "onnection connection+null; try{ "lass.ForAa'e(%or,.,jt.''.'$sql.9river%(; connection + 9river>ana,er.,et"onnection(connection;R=, %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%(;

1 1

3he output of the progra" is given below:

3able in the 'atabase: mys,l1 select M from empHsalT U----------U--------U V ?mp=ame V salary V U----------U--------U V 3ulfi,ar V /:GGG V V vinod V /2GGG V U----------U--------U 2 rows in set 4G.GG sec5

Getting Columns $ames using Servlets 3he co'e of the progra" is given below:

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, connection;R= + %jd/cB'$sqlB&&localhost&HulFiqar%; "onnection connection+null; try{ "lass.ForAa'e(%or,.,jt.''.'$sql.9river%(; connection + 9river>ana,er.,et"onnection(connection;R=, %root%, %ad'in%(; )reparedState'ent pst + connection.prepareState'ent(%select * Fro' e'pCdetails%(; ResultSet rs + pst.executeYuer$((; ResultSet>eta9ata rs'd + rs.,et>eta9ata((; int no!F"olu'ns + rs'd.,et"olu'n"ount((; && t sho*s the nu'/er oF colu'ns p*.println(%#he nu'/er oF colu'ns are % D no!F"olu'ns D %-/r.%(; && t sho*s 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 1 1

web.x"l ,ile for this progra": -2x'l version+%0.3%


encodin,+% S!4556740%2. -89!"#:)E *e/4app );<= " %4&&Sun >icros$ste's, nc.&&9#9 We/ Epplication ?.@&&EA% %httpB&&java.sun.co'&dtd&*e/4appC?C@.dtd%. -*e/4app. -servlet. -servlet4na'e.RulFiqar-&servlet4na'e. -servlet4class.ServletGettin,"olu'nsAa'es-&servlet4class. -&servlet. -servlet4'appin,. -servlet4na'e.RulFiqar-&servlet4na'e. -url4pattern.&ServletGettin,"olu'nsAa'es-&url4pattern. -&servlet4'appin,. -&*e/4app.

3he output of the progra" is given below:

3able in the 'atabase: mys,l1 select M from empHdetailsT U--------U----------U---------U----------U----------U-------U---------U--------U V user#d V =ame V surname V address/ V address2 V town V country V 3ipcode V U--------U----------U---------U----------U----------U-------U---------U--------U V <6W<W V 3ulfi,ar V !hmed V Moradabad V $elhi V C hla V #ndia V //GG2: V U--------U----------U---------U----------U----------U-------U---------U--------U / row in set 4G.GG sec5

Getting $um0er of Columns 3he co'e of the progra" is given below:

import import import import

java.io.*; java.sql.*; javax.servlet.*; javax.servlet.http.*;

public class ServletGettin,Ao!F"olu'ns extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResp

throws ServletException, !Exception{ response.set"ontent#$pe(%text&ht'l%(; )rintWriter p* + response.,etWriter((; Strin, connection;R= + %jd/cB'$sqlB&&localhost&HulFiqar%; "onnection connection+null; try{ "lass.ForAa'e(%co'.'$sql.jd/c.9river%(.ne* nstance((; connection + 9river>ana,er.,et"onnection(connection;R=, %root%, %ad'in%(; )reparedState'ent pst + connection.prepareState'ent(%select * Fro' e'pCdetails%(; ResultSet rs + pst.executeYuer$((; ResultSet>eta9ata rs'd + rs.,et>eta9ata((; int no!F"olu'ns + rs'd.,et"olu'n"ount((; && t sho*s 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 1 1

web.x"l file for this progra": -2x'l version+%0.3%


encodin,+% S!4556740%2. -89!"#:)E *e/4app );<= " %4&&Sun >icros$ste's, nc.&&9#9 We/ Epplication ?.@&&EA% %httpB&&java.sun.co'&dtd&*e/4appC?C@.dtd%. -*e/4app. -servlet. -servlet4na'e.RulFiqar-&servlet4na'e. -servlet4class.ServletGettin,Ao!F"olu'ns-&servlet4class. -&servlet. -servlet4'appin,. -servlet4na'e.RulFiqar-&servlet4na'e. -url4pattern.&ServletGettin,Ao!F"olu'ns-&url4pattern. -&servlet4'appin,. -&*e/4app.

3able e"p7'etails in the 'atabase: mys,l1 select M from empHdetailsT

U--------U----------U---------U-----------U---------U--------U---------U--------U V user#d V =ame V surname V address/ V address2 V town V country V 3ipcod eV U--------U----------U---------U-----------U---------U--------U---------U--------U V J;6<2 V Xulfi,ar V !hmed V Moradabad V 7ohini V 7ohini V $elhi V //GG2: V U--------U----------U---------U-----------U---------U--------U---------U------3he output of the progra" is given below:

Getting $um0er of 'o+s 3he co'e of the progra" is given below:

import import import import

java.io.*; java.sql.*; javax.servlet.*; javax.servlet.http.*;

public class ServletGettin,Ao!FRo*s extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResp
throws ServletException, !Exception{ int ro*s+3; response.set"ontent#$pe(%text&ht'l%(; )rintWriter p* + response.,etWriter((; Strin, connection;R= + %jd/cB'$sqlB&&localhost&HulFiqar%; "onnection connection; try{ "lass.ForAa'e(%or,.,jt.''.'$sql.9river%(; connection + 9river>ana,er.,et"onnection(connection;R=, %root%, %ad'in%(; )reparedState'ent pst + connection.prepareState'ent(%%(; ResultSet rs + pst.executeYuer$(%select count(*( Fro' e'pCsal%(; while (rs.next((({ ro*s + rs.,et nt(0(; 1 p*.println(%#he nu'/er oF ro*s are % D ro*s(; 1 catch(Exception e({ p*.println(%#he exception is % D e(; 1

1 1

web.x"l ,ile for this progra": -2x'l version+%0.3%


encodin,+% S!4556740%2.

-89!"#:)E *e/4app );<= " %4&&Sun >icros$ste's, nc.&&9#9 We/ Epplication ?.@&&EA% %httpB&&java.sun.co'&dtd&*e/4appC?C@.dtd%. -*e/4app. -servlet. -servlet4na'e.RulFiqar-&servlet4na'e. -servlet4class.ServletGettin,Ao!FRo*s-&servlet4class. -&servlet. -servlet4'appin,. -servlet4na'e.RulFiqar-&servlet4na'e. -url4pattern.&ServletGettin,Ao!FRo*s-&url4pattern. -&servlet4'appin,. -&*e/4app.

3able e"p7sal in the 'atabase:

mys,l1 select M from empHsalT U----------U--------U V ?mp=ame V salary V U----------U--------U V 3ulfi,ar V /:GGG V V vinod V /2GGG V U----------U--------U 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 Servlet9eletin,Ro*sGro'#a/le extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response( throws ServletException, !Exception{ int ro*s; response.set"ontent#$pe(%text&ht'l%(; )rintWriter p* + response.,etWriter((; Strin, connection;R= + %jd/cB'$sqlB&&localhost&HulFiqar%; "onnection connection; try{ "lass.ForAa'e(%or,.,jt.''.'$sql.9river%(; connection + 9river>ana,er.,et"onnection(connection;R=, %root%, %ad'in%(; )reparedState'ent pst + connection.prepareState'ent (%delete Fro' e'pCsal *here E'pAa'e + [vinod[%(; int i + pst.execute;pdate((;

1 1

1 catch(Exception e({ p*.println(%#he exception is % D e(; 1

if (i++3({ p*.println(%Ro* has /een deleted%(; 1 else{ p*.println(%Ao ro*s has /een deleted%(; 1

web.x"l file for this progra": -2x'l version+%0.3%


encodin,+% S!4556740%2. -89!"#:)E *e/4app );<= " %4&&Sun >icros$ste's, nc.&&9#9 We/ Epplication ?.@&&EA% %httpB&&java.sun.co'&dtd&*e/4appC?C@.dtd%. -*e/4app. -servlet. -servlet4na'e.RulFiqar-&servlet4na'e. -servlet4class.Servlet9eletin,Ro*sGro'#a/le-&servlet4class. -&servlet. -servlet4'appin,. -servlet4na'e.RulFiqar-&servlet4na'e. -url4pattern.&Servlet9eletin,Ro*sGro'#a/le-&url4pattern. -&servlet4'appin,. -&*e/4app.

3able in the 'atabase before 'eletion: mys,l1 select M from empHsalT U----------U--------U V ?mp=ame V salary V U----------U--------U V 3ulfi,ar V /:GGG V V vinod V /2GGG V U----------U--------U 2 rows in set 4G.GG sec5 3he output of the progra" is given below:

3able in the 'atabase after 'eletion: mys,l1 select M from empHsalT U----------U--------U V ?mp=ame V salary V U----------U--------U V 3ulfi,ar V /:GGG V U----------U--------U / row in set 4G.G: sec5

*eleting All 'o+s &rom t"e data0ase (a0le 3he co'e of the progra" is given below:

import

java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class Servlet9eletin,EllRo*sGro'#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, connection;R= + %jd/cB'$sqlB&&localhost&HulFiqar%; "onnection connection; try{ "lass.ForAa'e(%or,.,jt.''.'$sql.9river%(; connection + 9river>ana,er.,et"onnection(connection;R=, %root%, %ad'in%(; )reparedState'ent pst + connection.prepareState'ent(%delete Fro' e'pCsal%(; int i + pst.execute;pdate((; if (i++3({ p*.println(%Ell ro*s are deleted%(; 1 else{ p*.println(%no ro*s has /een deleted%(; 1 1 catch(Exception e({ p*.println(%#he exception is % D e(; 1 1 1

web.x"l file for this progra": -2x'l version+%0.3%


encodin,+% S!4556740%2. -89!"#:)E *e/4app );<= " %4&&Sun >icros$ste's, nc.&&9#9 We/ Epplication ?.@&&EA% %httpB&&java.sun.co'&dtd&*e/4appC?C@.dtd%. -*e/4app. -servlet. -servlet4na'e.RulFiqar-&servlet4na'e. -servlet4class.Servlet9eletin,EllRo*sGro'#a/le-&servlet4class. -&servlet. -servlet4'appin,. -servlet4na'e.RulFiqar-&servlet4na'e. -url4pattern.&Servlet9eletin,EllRo*sGro'#a/le-&url4pattern. -&servlet4'appin,. -&*e/4app.

3able in the 'atabase before 'eletion:

mys,l1 select M from empHsalT U----------U--------U V ?mp=ame V salary V U----------U--------U V 3ulfi,ar V /:GGG V V vinod V /2GGG V U----------U--------U 2 rows in set 4G.GG sec5 3he output of the progra" is given below:

3able in the 'atabase after 'eletion: mys,l1 select M from empHsalT ?mpty set 4G.G2 sec5

Ho+ to add a column in a ta0le &onsider a situation where the re,uirement of the client gets changed and you have as ed 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 the structure 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 Duery for adding a new column in the database table.

(o get the desired result firstly we need to ma e 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 ServletEddin,Ae*"olu'n extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response( throws ServletException, !Exception{ response.set"ontent#$pe(%text&ht'l%(; )rintWriter p* + response.,etWriter((; Strin, connection;R= + %jd/cB'$sqlB&&localhost&HulFiqar%; "onnection connection; try{ "lass.ForAa'e(%or,.,jt.''.'$sql.9river%(; connection + 9river>ana,er.,et"onnection(connection;R=, %root%, %ad'in%(; )reparedState'ent pst + connection.prepareState'ent (%alter ta/le e'pCdetails add colu'n sal int(6(%(; int i + pst.execute;pdate((; 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 1 1

web.x"l file for this progra":

-2x'l version+%0.3%

encodin,+% S!4556740%2. -89!"#:)E *e/4app );<= " %4&&Sun >icros$ste's, nc.&&9#9 We/ Epplication ?.@&&EA% %httpB&&java.sun.co'&dtd&*e/4appC?C@.dtd%. -*e/4app. -servlet. -servlet4na'e.RulFiqar-&servlet4na'e. -servlet4class.ServletEddin,Ae*"olu'n-&servlet4class. -&servlet. -servlet4'appin,. -servlet4na'e.RulFiqar-&servlet4na'e. -url4pattern.&ServletEddin,Ae*"olu'n-&url4pattern. -&servlet4'appin,. -&*e/4app.

3he output of the progra" is given below:

G.( and #,S( !et"od of H((# ?E3 (he 8et is one the simplest 'ttp method. #ts main )ob is to as the server for the resource. #f the resource is available then then it will given bac to the user on your browser. (hat resource may be a '(M. page, a sound file, a picture file 4J"?85 etc. We can say that get method is for getting something from the server. #t doesn>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.

POS3 (he "ost method is more powerful re,uest. %y using "ost we can re,uest 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, li e when we have to send a long en,uiry 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 ma e this program firstly we need to ma e 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, clic ing 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 reDuest ob)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 set ttribute(! method of the 8ttpSession ob)ect. (he attribute we have set will be retrieved by the get!ttribute method of the 8ttpSession ob)ect in the ne*t page and the value will be displayed on the browser by the PrintWriter ob)ect. 3he co'e of the progra" is given below:

-89!"#:)E H#>= );<= " %4&&W@"&&9#9 H#>= N.30 #ransitional&&EA%. -ht'l. -head. -'eta http4equiv+%"ontent4#$pe% content+%text&ht'l; charset+ S!4556740%. -title.Select the list oF colors-&title. -&head. -/od$. -For' action + %&Servlet)roject&"olor)a,e%. -select na'e + %colors% siHe + 6 'ultiple. -option selected.Green-&option. -option.Red-&option. -option.:ello*-&option. -option.<lue-&option. -option.<lacL-&option. -&select. -input t$pe + %su/'it% na'e + %su/'it%. -&For'. -&/od$. -&ht'l.

i'port java.io.*; i'port javax.servlet.*; i'port javax.servlet.http.*; &** * Servlet i'ple'entation class For ServletB "olor)a,e * *& pu/lic class "olor)a,e extends javax.servlet.http.HttpServlet i'ple'ents javax.servlet.Servlet { &* (non4Qava4doc( * Ksee javax.servlet.http.HttpServletSHttpServlet(( *& pu/lic "olor)a,e(( { super((;

1 &* (non4Qava4doc( * Ksee javax.servlet.http.HttpServletSdoGet (HttpServletRequest request, HttpServletResponse response( *& protected void doGet(HttpServletRequest request, HttpServletResponse response( thro*s ServletException, !Exception { && #!9! Euto4,enerated '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.setEttri/ute(%color%,colors(; session.set>ax nactive nterval(T3(; 1 p*.println(%-ht'l.-/od$ /,color +c$an.%(; For(int i + 3; i-colors.len,th; iDD( { p*.println(%#he selected colors are% D colorsOiPD %-/r.%(; 1 p*.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.HttpServletSdo)ost(HttpServletRequest request, HttpServletResponse response( *& protected void do)ost(HttpServletRequest request, HttpServletResponse response( thro*s ServletException, !Exception {

&& #!9! Euto4,enerated 'ethod stu/ 1 1

import )ava.io.MT import )ava*.servlet.MT import )ava*.servlet.http.MT -MM M Servlet implementation class for Servlet+ 8et&olors M Mpublic class 8et&olors e*tends 'ttpServlet Y -M 4non-Java-doc5 M Fsee )ava*.servlet.http.'ttpServletL'ttpServlet45 Mpublic 8et&olors45 Y super45T Z -M 4non-Java-doc5 M Fsee )ava*.servlet.http.'ttpServletLdo8et4 'ttpServlet7e,uest re,uest, 'ttpServlet7esponse response5 Mprotected void do8et4'ttpServlet7e,uest re,uest, 'ttpServlet7esponse response5 throws Servlet?*ception, #C?*ception Y -- (C$C !uto-generated method stub response.set&ontent(ype4Pte*t-htmlP5T "rintWriter pw Q response.getWriter45T 'ttpSession session Q re,uest.getSession4false5T if4session QQ null5 Y pw.println4P=o session is availableP5T pw.println4PWe are creating a session for you. &reating.....P5T session Q re,uest.getSession45T Z else

Y String get&olors[\ Q 4String[\5session.get!ttribute4PcolorP5T pw.println4P0html10body bgcolor Q cyan1P5T for4int iQ GT i0get&olors.lengthTiUU5 Y pw.println4P(he selected colors are P U get&olors[i\ U P0br1P5T Z pw.println4P0html10body1P5T Z Z -M 4non-Java-doc5 M Fsee )ava*.servlet.http.'ttpServletLdo"ost4 'ttpServlet7e,uest re,uest, 'ttpServlet7esponse response5 Mprotected void do"ost4'ttpServlet7e,uest re,uest, 'ttpServlet7esponse response5 throws Servlet?*ception, #C?*ception Y -- (C$C !uto-generated method stub Z Z 3he output of the progra" is given below:

send'edirect #n send 7edirect whenever the client ma es any re,uest it goes to the container, there the container decides whether the concerned servlet can handle the re,uest or not. #f not then the servlet decides that the re,uest 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 re,uest. !gain the browser ma es a new re,uest, but with the name of that servlet which can now handle the re,uest 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 '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.

#n send 7edirect whenever the client ma es any re,uest it goes to the container, there the container decides whether the concerned servlet can handle the re,uest or not. #f not then the servlet decides that the re,uest 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 re,uest. !gain the browser ma es a new re,uest, but with the name of that servlet which can now handle the re,uest 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#>= );<= " %4&&W@"&&9#9 H#>= N.30 #ransitional&&EA%. -ht'l. -head. -'eta http4equiv+%"ontent4#$pe% content+%text&ht'l; charset+ S!4556740%. -title.Redirectin, the pa,e-&title. -&head. -/od$. -For' action + %&Servlet)roject&SendRedirect% 'ethod + %post%. -tr. -td.Enter $our na'e B-&td. -td.-input t$pe + %text% na'e + %userna'e%.-&td. -&tr.-/r. -tr. -td.Enter $our pass*ord B-&td. -td.-input t$pe + %pass*ord% na'e + %pass*ord%.-&td. -&tr.-/r.

-td.-input t$pe + %su/'it% na'e + %su/'it%.-&td. -&tr. -&For'. -&/od$. -&ht'l.

-tr.

import )ava.io.MT import )ava.io.#C?*ceptionT import )ava*.servlet.Servlet?*ceptionT import )ava*.servlet.http.'ttpServlet7e,uestT 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'ttpServlet7e,uest re,uest, 'ttpServlet7esponse response5 throws Servlet?*ception, #C?*ception Y -- (C$C !uto-generated method stub response.set&ontent(ype4Pte*t-htmlP5T "rintWriter pw Q response.getWriter45T String name Q re,uest.get"arameter4PusernameP5T String password Q re,uest.get"arameter4PpasswordP5T if4name.e,uals4PJamesP5]] password.e,uals4PabcP55 Y response.send7edirect4P-Servlet"ro)ect-ValidUserP5T Z else Y pw.println4Pu r not a valid userP5T Z Z Z

import )ava.io.MT import )ava.io.#C?*ceptionT import )ava*.servlet.Servlet?*ceptionT import )ava*.servlet.http.'ttpServlet7e,uestT import )ava*.servlet.http.'ttpServlet7esponseT -MM M Servlet implementation class for Servlet+ ValidUser M Mpublic class ValidUser e*tends )ava*.servlet.http.'ttpServlet implements )ava*.servlet.Servlet Y -M 4non-Java-doc5 M Fsee )ava*.servlet.http.'ttpServletL'ttpServlet45 Mpublic ValidUser45 Y super45T Z -M 4non-Java-doc5 M Fsee )ava*.servlet.http.'ttpServletLdo8et4'ttpServlet7e,uest re,uest, 'ttpServlet7esponse response5 Mprotected void do8et4'ttpServlet7e,uest re,uest, 'ttpServlet7esponse response5 throws Servlet?*ception, #C?*ception Y -- (C$C !uto-generated method stub Z -M 4non-Java-doc5 M Fsee )ava*.servlet.http.'ttpServletLdo"ost4'ttpServlet7e,uest re,uest, 'ttpServlet7esponse response5 Mprotected void do"ost4'ttpServlet7e,uest re,uest, 'ttpServlet7esponse response5 throws Servlet?*ception, #C?*ception Y

-- (C$C !uto-generated method stub "rintWriter pw Q response.getWriter45T pw.println4PWelcome to roseindia.net0br1P5T pw.println4Phow are youP5T Z Z 3he output of the progra" is given below:

Servlet Conte/t

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 then creates a name-value pair for each 0conte*t-param1 tag. 2. !fter creating the name-value 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 li e servlet init parameters. 'ow can we do the mapping of the &onte*t init parameters in web.*ml HservletI Hservlet*na"eI9appingH<servlet*na"eI Hservlet*classI%ontext9appingH<servlet*classI H<servletI Hcontext*para"I

Hpara"*na"eIE"ailH<para"*na"eI Hpara"*valueIa'"inJrosein'ia.netH<para"*valueI H<context*para"I #n the servlet code we will write this as Servlet%ontext context C getServlet%ontext(!E pw.println(context.getInitPara"eter(BE"ailB!T

Accessing *ate in Servlet #n this e*ample, we are going to show how we can display a creation date of the session and last accessed date or time and id on our browser. #t is very easy to display it on our browser by using the 4ate class of the :ava.util pac age. !s we now that the our servlet e*tends the 8ttpServlet and overrides the doGet() method which it inherits from the 'ttpServlet class. (he server invo es 'o?et(! method whenever web server receives the 8?( re,uest from the servlet. (he 'o?et(! method ta es two arguments first is 'ttpServlet7e,uest ob)ect and the second one is 'ttpServlet7esponse ob)ect and this method throws the Servlet?*ception. getSession(!: getSession45 is a method. (his is the method that uses 'ttpServlet7e,uest ob)ect. When you call the method with its argument as true, the servlet reference implementation creates a session if necessary. (o properly maintain the session, you must call getSession45 before any output to response.

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;ast ccesse'3i"e(!: get.ast!ccessed(ime45 is a method. (his is the method that returns the last time the client sends re,uest with this session. getI'(!: (his is the method that returns a string containing the uni,ue 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 Eccessed9ateServlet 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=astEccessed#i'e(((; p*.println(% 9 % D session.,et d(((; p*.println(%"reateB % D create(; p*.println(%=ast EccessedB % D accessed(; Strin, dataAa'e + request.,et)ara'eter(%dataAa'e%(; if (dataAa'e 8+ null MM dataAa'e.len,th(( . 3( { Strin, dataIalue + request.,et)ara'eter(%dataIalue%(; session.putIalue(dataAa'e, dataIalue(; 1 Strin,OP valueAa'es + session.,etIalueAa'es((; if (valueAa'es 8+ null MM valueAa'es.len,th . 3( { for (int i + 3; i - valueAa'es.len,th; iDD( { Strin, str + valueAa'esOiP; Strin, str0 + session.,etIalue(str(.toStrin,((; p*.println(str D % + % D str0(; 1 1 1 1

Web.xml file for this program: 0^*ml versionQP/.GP encodingQP#SC-JJ:W-/P^1

0N--0N$C&(B"? web-app "U%.#& P---Sun Microsystems, #nc.--$($ Web !pplication 2.6--?=P Phttp+--)ava.sun.com-dtd-web-appH2H6.dtdP1 --1 0web-app1 0servlet1 0servlet-name1amar0-servlet-name1 0servlet-class1!ccessed$ateServlet0-servlet-class1 0-servlet1 0servlet-mapping1 0servlet-name1amar0-servlet-name1 0url-pattern1-!ccessed$ateServlet0-url-pattern1 0-servlet-mapping1 0-web-app1 Output of this progra" is given below.

You might also like