6795986-Servelet-s-Faqs.pdf

Embed Size (px)

Citation preview

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    1/159

    Servlets

    A servlet is a JavaTMcomponent that can be plugged into a Java-enabled web server toprovide custom services. These services can include:

    New features

    Runtime changes to content

    Runtime changes to presentation New standard protocols (such as T!"

    New custom protocols

    #ervlets are designed to wor$ within a re%uest&response processing model. 'n are%uest&response model a client sends a re%uest message to a server and the serverresponds b) sending bac$ a repl) message. Re%uests can come in the form of an

    *TT! +R, T! +R, or a custom protocol.The re%uest and the corresponding response reflect the state of the client and the server atthe time of the re%uest. Normall) the state of the client&server connection cannot bemaintained across different re%uest&response pairs. *owever session information ismaintainable with servlets through means to be described later. The Java #ervlet A!'includes several Java interfaces and full) defines the lin$ between a hosting server andservlets. The #ervlet A!' is defined as an etension to the standard J/. J/ etensions arepac$aged under 0ava--the root of the Java etension librar) tree. The Java #ervlet A!'

    contains the following pac$ages:

    !ac$age0ava.servlet !ac$age0ava.servlet.http

    #ervlets are a powerful addition to the Java environment. The) are fast safe reliableand 1223 pure Java. 4ecause servlets plug into an eisting server the) leverage a lotof eisting code and technolog). The server handles the networ$ connections protocolnegotiation class loading and more5 all of this wor$ does not need to be replicated6And because servlets are located at the middle tier the) are positioned to add a lot ofvalue and fleibilit) to a s)stem. 'n this course )ou will learn about the #ervlet A!' and)ou will get a brief tour of the t)pes of features servlets can implement.

    Architectural Roles for Servlets

    4ecause of their power and fleibilit) servlets can pla) a significant role in a s)stemarchitecture. The) can perform the application processing assigned to the middle tier act asa pro) for a client and even augment the features of the middle tier b) adding support fornew protocols or other features. A middle tier acts as the application server in so called three-tier client&server s)stems positioning itself between a lightweight client li$e a web browserand a data source.

    Middle-Tier Process

    Page 1of 159

    http://developer.java.sun.com/developer/onlineTraining/Servlets/Fundamentals/servlets.html#ExampleHTTPSessionhttp://java.sun.com/products/servlet/2.1/api/Package-javax.servlet.htmlhttp://java.sun.com/products/servlet/2.1/api/Package-javax.servlet.http.htmlhttp://developer.java.sun.com/developer/onlineTraining/Servlets/Fundamentals/servlets.html#ExampleHTTPSessionhttp://java.sun.com/products/servlet/2.1/api/Package-javax.servlet.htmlhttp://java.sun.com/products/servlet/2.1/api/Package-javax.servlet.http.html
  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    2/159

    'n man) s)stems a middle tier serves as a lin$ between clients and bac$-end services. 4)using a middle tier a lot of processing can be off-loaded from both clients (ma$ing themlighter and faster" and servers (allowing them to focus on their mission". 7ne advantage ofmiddle tier processing is simpl) connection management. A set of servlets could handleconnections with hundreds of clients if not thousands while rec)cling a pool of epensive

    connections to database servers.

    7ther middle tier roles include:

    4usiness rule enforcement

    Transaction management Mapping clients to a redundant set of servers

    #upporting different t)pes of clients such as pure *TM, and Java capable clients

    Proxy Servers

    8hen used to support applets servlets can act as their proies. This can be importantbecause Java securit) allows applets onl) to ma$e connections bac$ to the server fromwhich the) were loaded.'f an applet needs to connect to a database server located on a different machine a servletcan ma$e this connection on behalf of the applet.

    Protocol Support

    The #ervlet A!' provides a tight lin$ between a server and servlets. This allows servlets toadd new protocol support to a server. (9ou will see how *TT! support is provided for )ou in

    the A!' pac$ages." ssentiall) an) protocol that follows a re%uest&response computingmodel can be implemented b) a servlet. This could include:

    #MT! !7!

    T!

    #ervlet support is currentl) available in several web servers and will probabl) startappearing in other t)pes of application servers in the near future. 9ou will use a web server tohost the servlets in this class and onl) deal with the *TT! protocol.4ecause *TT! is one of the most common protocols and because *TM, can provide such

    a rich presentation of information servlets probabl) contribute the most to building *TT!based s)stems.

    HTML Support

    *TM, can provide a rich presentation of information because of its fleibilit) and the range ofcontent that it can support. #ervlets can pla) a role in creating *TM, content. 'n fact servletsupport for *TM, is so common the0ava.servlet.httppac$age is dedicated to supporting*TT! protocol and *TM, generation.

    ;omple web sites often need to provide *TM, pages that are tailored for each visitor or

    even for each hit. #ervlets can be written to process *TM, pages and customi

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    3/159

    the) are sent to a client. This can be as simple as on the fl) substitutions or it can be ascomple as compiling a grammar-based description of a page and generating custom *TM,.

    Inline HTML Generation

    #ome web servers such as the Java 8eb #erverTM(J8#" allow servlet tags to beembedded directl) into *TM, files. 8hen the server encounters such a tag it calls theservlet while it is sending the *TM, file to the client. This allows a servlet to insert itscontribution directl) into the outgoing *TM, stream.

    Server-Side Includes

    Another eample is on the fl) tag processing $nown as server-side includes(##'". 8ith ##'an *TM, page can contain special commands that are processed each time a page isre%uested. +suall) a web server re%uires *TM, files that incorporate ##' to use a uni%ueetension such as .shtml. As an eample if an *TM, page (with an .shtml etension"

    includes the following: =6-->include virtual?@&includes&page.html@--

    it would be detected b) the web server as a re%uest to perform an inline file include. 8hileserver side includes are supported b) most web servers the ##' tags are not standardi

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    4/159

    Te!porary versus Per!anent Servlets

    #ervlets can be started and stopped for each client re%uest or the) can be started as theweb server is started and $ept alive until the server is shut down. Temporar) servlets areloaded on demand and offer a good wa) to conserve resources in the server for less-used

    functions.

    !ermanent servlets are loaded when the server is started and live until the server isshutdown. #ervlets are installed as permanent etensions to a server when their start-upcosts are ver) high (such as establishing a connection with a 4M#" when the) offerpermanent server-side functionalit) (such as an RM' service" or when the) must respond asfast as possible to client re%uests.

    There is no special code necessar) to ma$e a servlet temporar) or permanent5 this is afunction of the server configuration.

    4ecause servlets can be loaded when a web server starts the) can use this auto-loadingmechanism to provide easier loading of server-side Java programs. These programs canthen provide functionalit) that is totall) uni%ue and independent of the web server. oreample a servlet could provide R-based services (rlogin rsh ..." through T;!&'! portswhile using the servlet re%uest&response protocol to present and process *TM, pages usedto manage the servlet.

    "sing servletrunner

    or both J/ 1.1 and the Java C platform )ou need to install the Java #ervlet evelopment

    /it (J#/". To use servletrunner ma$e sure )our !AT* environment variable points to itsdirector). or the J#/ C.2 installed with all default options that location is: c:E0sd$C.2Ebin ona 8indows platform.

    To ma$e sure that servletrunner has access to the Java servlet pac$ages chec$ that )our;,A##!AT* environment variable is pointing to the correct JAR file c:E0sd$C.2ElibE0sd$.0ar ona 8indows platform. 8ith the Java C platform instead of modif)ing the ;,A##!AT* it iseasier to 0ust cop) the JAR file to the et director) under the Java runtine environment. Thistreats the servlet pac$ages as standard etensions.

    8ith the environment set up run the servletrunner program from the command line. The

    parameters are:

    +sage: servletrunner FoptionsG7ptions: -p port the port number to listen on -b bac$log the listen bac$log -m ma maimum number of connection handlers -t timeout connection timeout in milliseconds -d dir servlet director) -s filename servlet propert) file name

    Page 4of 159

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    5/159

    The most common wa) to run this utilit) is to move to the director) that contains )our servletsand run servletrunner from that location. *owever that doesnDt automaticall) configure thetool to load the servlets from the current director).

    Magercise

    1. *osting with servletrunner

    "sing #ava $e% Server

    #unDs Java 8eb #erver (J8#" is a full featured product. or servlet developers a nicefeature is its abilit) to detect when a servlet has been updated. 't detects when new classfiles have been copied to the appropriate servlet director) and if necessar) automaticall)reloads an) running servlets.

    The J8# can be installed as a service under 8indows NT. 8hile this ma$es it convenient for

    running a production server it is not recommended for servlet development wor$. +nder8indows HI there are no 7# services so the command line start-up is )our onl) option.

    To run J8# from the c:EJava8eb#erver1.1Ebin director) t)pe in the httpd command. Thisstarts the server in a console window. No further displa) is shown in the console unless aservlet eecutes a #)stem.out.println(" statement.

    #ervlets are installed b) moving them to the c:EJava8eb#erver1.1Eservlets director). Asmentioned J8# detects when servlets have been added to this director). Although )ou canuse the J8# management applet to tailor the servlet installation this is generall) not advised

    ecept for production server installations.

    To shut down the J8# press =;ontrol; in the command window. The server prints amessage to the console when it has finished shutting down.

    Magercise

    1. *osting with the Java 8eb #erver

    Servlet API

    The Java #ervlet A!' defines the interface between servlets and servers. This A!' ispac$aged as a standard etension to the J/ under 0ava:

    !ac$age0ava.servlet

    !ac$age0ava.servlet.http

    The A!' provides support in four categories:

    #ervlet life c)cle management

    Access to servlet contet

    +tilit) classes

    *TT!-specific support classes

    Page 5of 159

    http://developer.java.sun.com/developer/onlineTraining/Servlets/Fundamentals/magercises/ServletRunnerHosting/index.htmlhttp://developer.java.sun.com/developer/onlineTraining/Servlets/Fundamentals/magercises/JavaWebServerHosting/index.htmlhttp://java.sun.com/products/servlet/2.1/api/Package-javax.servlet.htmlhttp://java.sun.com/products/servlet/2.1/api/Package-javax.servlet.http.htmlhttp://developer.java.sun.com/developer/onlineTraining/Servlets/Fundamentals/servlets.html#lifeCyclehttp://developer.java.sun.com/developer/onlineTraining/Servlets/Fundamentals/servlets.html#ServletContexthttp://developer.java.sun.com/developer/onlineTraining/Servlets/Fundamentals/servlets.html#utilityClasseshttp://developer.java.sun.com/developer/onlineTraining/Servlets/Fundamentals/servlets.html#HTTPClasseshttp://developer.java.sun.com/developer/onlineTraining/Servlets/Fundamentals/magercises/ServletRunnerHosting/index.htmlhttp://developer.java.sun.com/developer/onlineTraining/Servlets/Fundamentals/magercises/JavaWebServerHosting/index.htmlhttp://java.sun.com/products/servlet/2.1/api/Package-javax.servlet.htmlhttp://java.sun.com/products/servlet/2.1/api/Package-javax.servlet.http.htmlhttp://developer.java.sun.com/developer/onlineTraining/Servlets/Fundamentals/servlets.html#lifeCyclehttp://developer.java.sun.com/developer/onlineTraining/Servlets/Fundamentals/servlets.html#ServletContexthttp://developer.java.sun.com/developer/onlineTraining/Servlets/Fundamentals/servlets.html#utilityClasseshttp://developer.java.sun.com/developer/onlineTraining/Servlets/Fundamentals/servlets.html#HTTPClasses
  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    6/159

    The Servlet Life ycle

    #ervlets run on the web server platform as part of the same process as the web server itself.The web server is responsible for initiali

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    7/159

    character-level data instead of b)te-level data )ou can get a 4ufferedReaderinsteadwith getReader(".

    A #ervletResponserepresents the servletDs repl) bac$ to the client. 8hen preparing aresponse the method set;ontentT)pe("is called first to set the M'M t)pe of therepl). Net the method get7utput#tream("or get8riter("can be used to obtain a

    #ervlet7utput#treamor !rint8riter respectivel) to send data bac$ to the client.

    As )ou can see there are two wa)s for a client to send information to a servlet. The first is tosend parameter values and the second is to send information via the 'nput#tream (orReader". !arameter values can be embedded into a +R,. *ow this is done is discussedbelow. *ow the parameter values are read b) the servlet is discussed later.

    The service(" methodDs 0ob is conceptuall) simple--it creates a response for each clientre%uest sent to it from the host server. *owever it is important to reali

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    8/159

    return @A #imple #ervlet@5

    public void service (#ervletRe%uest re% #ervletResponse res

    " throws #ervletception '7ception L res.set;ontentT)pe( @tet&html@ "5 !rint8riter out ? res.get8riter("5 out.println( @=html@ "5 out.println( @=head "5 out.println( @=titleA #ample #ervlet=&title@ "5 out.println( @=&head@ "5 out.println( @=bod)@ "5 out.println( @=h1A #ample #ervlet=&h1@ "5 out.println( @=&bod)@ "5 out.println( @=&html@ "5

    out.close("5

    Servlet ontext

    A servlet lives and dies within the bounds of the server process. To understand its operatingenvironment a servlet can get information about its environment at different times. #ervletinitiali

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    9/159

    #erver contet information is available at an) time through the #ervlet;ontetob0ect. Aservlet can obtain this ob0ect b) calling the get#ervlet;ontet("method on the #ervlet;onfigob0ect. Remember that this was passed to the servlet during the initiali

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    10/159

    param1 ? re%.get!arameter(@irst@"5 paramC ? re%.get!arameter(@#econd@"5

    There are additional pieces of information available to the servlet through #ervletRe%uest.

    These are shown in the following table.

    getAttribute(" Returns value of a named attribute for this re%uest.

    get;ontent,ength(" #i

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    11/159

    The eception0ava.servlet.+navailableceptionindicates that a servlet is unavailable.#ervlets can report this eception at an) time. There are two t)pes of unavailabilit):

    Per!anent. The servlet is unable to function until an administrator ta$es some action.

    'n this state a servlet should write a log entr) with a problem report and possible

    resolutions. Te!porary. The servlet encountered a (potentiall)" temporar) problem such as a full

    dis$ failed server etc. The problem can correct itself with time or ma) re%uireoperator intervention.

    HTTP Support

    #ervlets that use the *TT! protocol are ver) common. 't should not be a surprise that thereis specific help for servlet developers who write them. #upport for handling the *TT!protocol is provided in the pac$age0ava.servlet.http. 4efore loo$ing at this pac$age ta$e aloo$ at the *TT! protocol itself.

    *TT! stands for the *)perTet Transfer !rotocol. 't defines a protocol used b) web browsersand servers to communicate with each other. The protocol defines a set of tet-basedre%uest messages called HTTP methods. (Note: The *TT! specification calls these HTTPmethods5 do not confuse this term with Java methods. Thin$ of HTTP methodsas messagesre%uesting a certain t)pe of response". The *TT! methods include:

    BT

    *A !7#T

    !+T ,T TRA;

    ;7NN;T

    7!T'7N#

    or this course )ou will onl) need to loo$ at onl) three of these methods: BT *A and!7#T.

    The !TT" #$T Method

    The *TT! BT method re%uests information from a web server. This information could be afile output from a device on the server or output from a program (such as a servlet or ;B'script".

    An *TT! BT re%uest ta$es the form:

    BT +R, =http version *ost: =target host

    in addition to several other lines of information.

    or eample the following *TT! BT message is re%uesting the home page from theMage,ang web site:

    Page 11of 159

    http://java.sun.com/products/servlet/2.1/api/javax.servlet.UnavailableException.htmlhttp://java.sun.com/products/servlet/2.1/api/Package-javax.servlet.http.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.UnavailableException.htmlhttp://java.sun.com/products/servlet/2.1/api/Package-javax.servlet.http.html
  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    12/159

    BT & *TT!&1.1 ;onnection: /eep-Alive +ser-Agent: Mo

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    13/159

    ;ontent-length: PPUI

    =PPUI b)tes worth of data -- the document bod)

    The !$%D Method

    The *TT! *A method is ver) similar to the *TT! BT method. The re%uest loo$s eactl)the same as the BT re%uest (ecept the word *A is used instead of BT" but the serveronly returns the header information.

    *A is often used to chec$ the following:

    The last-modified date of a document on the server for caching purposes

    The si

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    14/159

    Note the blan$ line--this signals the end of the !7#T re%uest header and the beginning ofthe etended information.

    +nli$e the BT method !7#T is notepected to be safenor idempotent5 it can performmodifications to data and it is not re%uired to be repeatable.

    !TT" Support Classes

    Now that )ou have been introduced to the *TT! protocol consider how the0ava.servlet.httppac$age helps )ou write *TT! servlets. The abstract class0ava.servlet.http.*ttp#ervletprovides an implementation of the0ava.servlet.#ervletinterface and includes a lot of helpfuldefault functionalit). The easiest wa) to write an *TT! servlet is to etend *ttp#ervletandadd )our own custom processing.

    The class *ttp#ervletprovides an implementation of the service("method that dispatches the*TT! messages to one of several special methods. These methods are:

    doBet("

    do*ead("

    doelete(" do7ptions("

    do!ost("

    doTrace("

    and correspond directl) with the *TT! protocol methods.

    As shown in the following diagram the service(" method interprets each *TT! method anddetermines if it is an *TT! BT *TT! !7#T *TT! *A or other *TT! protocol method:

    igWWWW

    The class *ttp#ervletis actuall) rather intelligent. Not onl) does it dispatch *TT! re%uests itdetects which methods are overridden in a subclass and can report bac$ to a client on thecapabilities of the server. (#impl) b) overriding the doBet("method causes the class torespond to an *TT! 7!T'7N# method with information that BT *A TRA; and7!T'7N# are all supported. These capabilities are in fact all supported b) the classDs code".

    'n another eample of the support *ttp#ervletprovides if the doBet("method is overriddenthere is an automatic response generated for the *TT! *A method. (#ince the responseto an *TT! *A method is identical to an *TT! BT method--minus the bod) of themessage--the *ttp#ervletclass can generate an appropriate response to an *TT! *Are%uest from the repl) sent bac$ from the doBet("method". As )ou might epect if )ou needmore precise control )ou can alwa)s override the do*ead("method and provide a customresponse.

    'sing the !TT" Support Classes

    8hen using the *TT! support classes )ou generall) create a new servlet that etends

    *ttp#ervletand overrides either doBet("or do!ost(" or possibl) both. 7ther methods can beoverridden to get more fine-grained control.

    Page 14of 159

    http://java.sun.com/products/servlet/2.1/api/Package-javax.servlet.http.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#servicehttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doGethttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doHeadhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doDeletehttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doOptionshttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doPosthttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doTracehttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doGethttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doGethttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doGethttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doHeadhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doGethttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doPosthttp://java.sun.com/products/servlet/2.1/api/Package-javax.servlet.http.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#servicehttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doGethttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doHeadhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doDeletehttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doOptionshttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doPosthttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doTracehttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doGethttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doGethttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doGethttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doHeadhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doGethttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doPost
  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    15/159

    The *TT! processing methods are passed two parameters an *ttp#ervletRe%uestob0ectand an *ttp#ervletResponseob0ect. The *ttp#ervletRe%uestclass has several conveniencemethods to help parse the re%uest or )ou can parse it )ourself b) simpl) reading the tet ofthe re%uest.

    A servletDs doBet("method should

    Read re%uest data such as input parameters

    #et response headers (length t)pe and encoding"

    8rite the response data

    't is important to note that the handling of a BT method is epected to be safeandidempotent.

    *anding is considered safeif it does not have anyside effects for which users are

    held responsible such as charging them for the access or storing data. *andling is considered idempotentif it can safel) be repeated. This allows a client to

    repeat a BT re%uest without penalt).

    Thin$ of it this wa): BT should be @loo$ing without touching.@ 'f )ou re%uire processing thathas side effects )ou should use another *TT! method such as !7#T.

    A servletDs do!ost("method should be overridden when )ou need to process an *TM, formposting or to handle a large amount of data being sent b) a client. *TT! !7#T methodhandling is discussed in detail later.

    *A re%uests are processed b) using the doBet("method of an *ttp#ervlet. 9ou couldsimpl) implement doBet("and be done with it5 an) document data that )ou write to theresponse output stream will notbe returned to the client. A more efficient implementationhowever would chec$ to see if the re%uest was a BT or *A re%uest and if a *Are%uest not write the data to the response output stream.

    Su!!ary

    The Java #ervlet A!' is a standard extension. This means that there is an eplicit definition ofservlet interfaces but it is not part of the Java evelopment /it (J/" 1.1 or the Java Cplatform. 'nstead the servlet classes are delivered with the Java #ervlet evelopment /it

    (J#/" version C.2 from #un (http:&&0ava.sun.com&products&servlet&". This J#/ version isintended for use with both J/ 1.1 and the Java C platform. There are a few significantdifferences between J#/ C.2 and J#/ 1.2. #ee belowfor details. 'f )ou are using aversion of J#/ earlier than C.2 it is recommended that )ou upgrade to J#/ C.2.

    #ervlet support currentl) spans two pac$ages:

    0ava.servlet: Beneral #ervlet #upport

    ServletAn interface that defines communication between a web server and aservlet. This interface defines the init(" service(" and destro)("methods (and a few others".

    Servletonfig An interface that describes the configuration parameters for a servlet.

    Page 15of 159

    http://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServletRequest.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServletResponse.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServletRequest.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doGethttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doPosthttp://developer.java.sun.com/developer/onlineTraining/Servlets/Fundamentals/servlets.html#ExampleHTTPPostProcessinghttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doGethttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doGethttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doGethttp://java.sun.com/products/servlet/http://developer.java.sun.com/developer/onlineTraining/Servlets/Fundamentals/servlets.html#JSDK1_0vsJSDK2_0http://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#inithttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#servicehttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#destroyhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.ServletConfig.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServletRequest.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServletResponse.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServletRequest.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doGethttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doPosthttp://developer.java.sun.com/developer/onlineTraining/Servlets/Fundamentals/servlets.html#ExampleHTTPPostProcessinghttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doGethttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.html#doGethttp://java.sun.com/products/servlet/http://developer.java.sun.com/developer/onlineTraining/Servlets/Fundamentals/servlets.html#JSDK1_0vsJSDK2_0http://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#inithttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#servicehttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#destroyhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.ServletConfig.html
  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    16/159

    This is passed to the servlet when the web server calls its init("method. Note that the servlet should save the reference to the#ervlet;onfigob0ect and define a get#ervlet;onfig("method to returnit when as$ed. This interface defines how to get the initiali

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    17/159

    #ometimes a web page needs onl) a small piece of information that is customi

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    18/159

    Maintaining #ession 'nformationsection later in this course. 8ithout session managementtrac$ing one can resort to several different strategies. The) all involve writing data to theclient in hidden fields which is then sent bac$ to the server. The simplest wa) to handleupdates is to use an optimistic loc$ing scheme based on date&time stamps. 7ne can use asingle date&time stamp for a whole form of data or one could use separate date&time stamps

    for each @row@ of information.

    7nce the update strateg) has been selected capturing the data sent to the server via an*TT! !7#T method is straightforward. 'nformation from the *TM, form is sent as a seriesof parameters (name&value pairs" in the 'nput#tream ob0ect. The *ttp+tilsclass contains amethod parse!ostata("that accepts the raw 'nput#tream from the client and return a*ashtable with the parameter information alread) processed. A reall) nice feature is that if aparameter of a given name has multiple values (such is the case for a column name withmultiple rows" then this information can be retrieved from the *ashtable as an arra) of t)pe#tring.

    'n the following Magercise )ou will be given s$eleton code that implements a pair of servletsthat displa) data in a browser as an editable *TM, form. The structure of the data is $eptseparate from the actual data. This ma$es it eas) to modif) this code to run against arbitrar)tables from a J4;-connected database.

    Magercise

    1. !osting and !rocessing *TM, orms

    "sing oo)ies

    or those unfamiliar with coo$ies a coo$ie is a named piece of data maintained b) abrowser normall) for session management. #ince *TT! connections are stateless )ou canuse a coo$ie to store persistent information accross multiple *TT! connections. The ;oo$ieclass is where all the @magic@ is done. The *ttp#ession class described netis actuall)easier to use. *owever it doesnDt support retaining the information across multiple browsersessions.

    To save coo$ie information )ou need to create a ;oo$ie set the content t)pe of the*ttp#ervletResponse response add the coo$ie to the response and then send the output.9ou must add the coo$ie after setting the content t)pe but before sending the output as the

    coo$ie is sent bac$ as part of the *TT! response header.

    private static final #tring #+MX/9 ? @sum@5 ... int sum ? ...5 && get old value and add to it ;oo$ie the;oo$ie ?

    new ;oo$ie (#+MX/9 'nteger.to#tring(sum""5 response.set;ontentT)pe(@tet&html@"5 response.add;oo$ie(the;oo$ie"5

    't is necessar) to remember that all coo$ie data are strings. 9ou must convert information li$e

    int data to a #tring ob0ect. 4) default the coo$ie lives for the life of the browser session. Toenable a coo$ie to live longer )ou must call the setMaAge(interval"method. 8hen positive

    Page 18of 159

    http://developer.java.sun.com/developer/onlineTraining/Servlets/Fundamentals/servlets.html#ExampleHTTPSessionhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpUtils.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpUtils.html#parsePostDatahttp://developer.java.sun.com/developer/onlineTraining/Servlets/Fundamentals/magercises/FormPostingAndProcessing/index.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.Cookie.htmlhttp://developer.java.sun.com/developer/onlineTraining/Servlets/Fundamentals/servlets.html#ExampleHTTPSessionhttp://developer.java.sun.com/developer/onlineTraining/Servlets/Fundamentals/servlets.html#ExampleHTTPSessionhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.Cookie.html#setMaxAgehttp://developer.java.sun.com/developer/onlineTraining/Servlets/Fundamentals/servlets.html#ExampleHTTPSessionhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpUtils.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpUtils.html#parsePostDatahttp://developer.java.sun.com/developer/onlineTraining/Servlets/Fundamentals/magercises/FormPostingAndProcessing/index.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.Cookie.htmlhttp://developer.java.sun.com/developer/onlineTraining/Servlets/Fundamentals/servlets.html#ExampleHTTPSessionhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.Cookie.html#setMaxAge
  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    19/159

    this allows )ou to set the number of seconds a coo$ie eists. A negative setting is the defaultand destro)s the coo$ie when the browser eits. A

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    20/159

    To store session-specific information )ou use the putOalue($e) value"method. To retrievethe information )ou as$ the session with getOalue($e)". The following eample demonstratesthis b) continuall) summing up the integer value of theAddendparameter. 'n the event thevalue is not an integer the number of errors are also counted.

    private static final #tring #+MX/9 [email protected]@5

    private static final #tring RR7RX/9 [email protected]@5

    'nteger sum ? ('nteger" session.getOalue(#+MX/9"5 int ival ? 25 if (sum 6? null" L ival ? sum.intOalue("5 tr) L #tring addend#tring ?

    re%uest.get!arameter(@Addend@"5 int addend ? 'nteger.parse'nt (addend#tring"5 sum ? new 'nteger(ival addend"5 session.putOalue (#+MX/9 sum"5 catch (Numberormatception e" L 'nteger error;ount ?

    ('nteger"session.getOalue(RR7RX/9"5 if (error;ount ?? null" L error;ount ? new 'nteger(1"5 else L error;ount ? new 'nteger(error;ount.intOalue("1"5 session.putOalue (RR7RX/9 error;ount"5

    As with all servlets once )ouDve performed the necessar) operations )ou need to generatesome output. 'f )ou are using sessions it is necessar) to re%uest the session with*ttp#ervletRe%uest.get#ession(" before generating an) output.

    response.set;ontentT)pe(@tet&html@"5 !rint8riter out ? response.get8riter("5

    out.println(@=html@ @=head=title#ession 'nformation=&title=&head@ @=bod) bgcolor?E@>E@@ @=h1#ession 'nformation=&h1=table@"5 out.println (@=tr=td'dentifier=&td@"5 out.println (@=td@ session.get'd(" @=&td=&tr@"5 out.println (@=tr=td;reated=&td@"5 out.println (@=td@ new ate( session.get;reationTime("" @=&td=&tr@"5 out.println (@=tr=td,ast Accessed=&td@"5 out.println (@=td@ new ate(

    session.get,astAccessedTime("" @=&td=&tr@"5 out.println (@=tr=tdNew #essionQ=&td@"5

    Page 20of 159

    http://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpSession.html#putValuehttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpSession.html#getValuehttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpSession.html#putValuehttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpSession.html#getValue
  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    21/159

    out.println (@=td@ session.isNew(" @=&td=&tr@"5 #tring namesFG ? session.getOalueNames("5 for (int i?2 n?names.length5 i=n5 i" L out.println (@=tr=td@ namesFiG @=&td@"5 out.println (@=td@ session.getOalue (namesFiG"

    @=&td=&tr@"5 out.println(@=&table=&center=&bod)=&html@"5 out.close("5

    The complete code eample shown above is availablefor testing. 7ne thing notdemonstrated in the eample is the abilit) to enda session where the net call tore%uest.get#ession(true" returns a different session. This is done with a call to invalidate(".

    'n the event a user has browser coo$ies disabled )ou can encode the session ' within the*ttp#ervletResponseb) calling its encode+rl("method.

    onnecting to *ata%ases

    't is ver) common to have servlets connect to databases through J4;. This allows )ou tobetter control access to the database b) onl) permitting the middle-tier to communicate withthe database. 'f )our database server includes sufficient simultanious connection licenses)ou can even setup database connections once when the servlet is initiali

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    22/159

    @Mon 21 Jan 1HH2 22:22:22 BMT@"5

    #tatement stmt ? null5

    Result#et result ? null5

    tr) L && #ubmit %uer)

    stmt ? con.create#tatement("5

    result ? stmt.eecuteYuer) ( @#,;T programmer cups @

    @R7M Joltata 7RR 49 cups #;5@"5

    && ;reate output

    !rint8riter out ? response.get8riter("5

    while(result.net("" L

    && Benerate output from Result#et finall) L

    if (result 6? null" L

    result.close("5

    if (stmt 6? null" L

    stmt.close("5

    out.flush("5

    out.close("5 'n the destro)(" method disconnect from the database.

    public void destro)(" L

    super.destro)("5 con.close("5

    't is not good practice to leave a database connection permanentl) open so this servletshould not be installed as a permanent servlet. *aving it as a temporar) servlet that closes

    itself down after a predefined period of inactivit) allows the sharing of the databaseconnection with re%uests that coincide reducing the cost of each re%uest.

    9ou can also save some information in the *ttp#ession to possible page through the resultset.

    Security Issues

    As with Java applets Java servlets have securit) issues to worr) about too.

    The Servlet Sand%ox

    Page 22of 159

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    23/159

    A servlet can originate from several sources. A webmaster ma) have written it5 a user ma)have written it5 it ma) have been bought as part of a third-part) pac$age or downloaded fromanother web site.

    4ased on the source of the servlet a certain level of trust should be associated with that

    servlet. #ome web servers provide a means to associate different levels of trust with differentservlets. This concept is similar to how web browsers control applets and is $nown as@sandboing@.

    A servlet sandbo is an area where servlets are given restricted authorit) on the server. The)ma) not have access to the file s)stem or networ$ or the) ma) have been granteda moretrusted status. 't is up to the web server administrator to decide which servlets are grantedthis status. Note that a full) trusted servlet has full access to the serverDs file s)stem andnetwor$ing capabilities. 't could even perform a #)stem.eit(" stopping the web server...

    Access ontrol Lists +ALs,

    Man) web servers allow )ou to restrict access to certain web pages and servlets via accesscontrol lists (A;,s". An A;, is a list of users who are allowed to perform a specific function inthe server. The list specifies:

    8hat $ind of access is allowed 8hat ob0ect the access applies to

    8hich users are granted access

    ach web server has its own means of specif)ing an A;, but in general a list of users is

    registered on the server and those user names are used in an A;,. #ome servers also allow)ou to add users to logical groups so )ou can grant access to a group of users withoutspecif)ing all of them eplicitl) in the A;,.

    A;,s are etremel) important as some servlets can present or modif) sensitive data andshould be tightl) controlled while others onl) present public $nowledge and do not need tobe controlled.

    Threading Issues

    A web server can call a servletDs service("method for several re%uests at once. This brings

    up the issue of thread safet) in servlets.

    4ut first consider what )ou do notneed to worr) about: a servletDs init("method. The init("method will onlybe called oncefor the duration of the time that a servlet is loaded. The webserver calls init("when loading and will not call it again unless the servlet has been unloadedand reloaded. 'n addition the service("method or destro)("method will notbe called until theinit("method has completed its processing.

    Things get more interesting when )ou consider the service("method. The service("methodcan be called b) the web server for multiple clients at the same time. (8ith the J#/ C.2)ou can tag a servlet with the #ingleThreadModelinterface. This results in each call to

    service("being handled seriall). #hared resources such as files and databases can stillhave concurrenc) issues to handle."

    Page 23of 159

    http://java.sun.com/products/jdk/1.1/docs/api/java.lang.System.html#exithttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#servicehttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#inithttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#inithttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#inithttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#servicehttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#destroyhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#inithttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#servicehttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#servicehttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#servicehttp://java.sun.com/products/servlet/2.1/api/javax.servlet.SingleThreadModel.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#servicehttp://java.sun.com/products/jdk/1.1/docs/api/java.lang.System.html#exithttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#servicehttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#inithttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#inithttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#inithttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#servicehttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#destroyhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#inithttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#servicehttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#servicehttp://java.sun.com/products/servlet/2.1/api/javax.servlet.SingleThreadModel.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#service
  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    24/159

    'f )our service("method uses outside resources such as instance data from the servletob0ect files or databases )ou need to carefull) eamine what might happen if multiple callsare made to service("at the same time. or eample suppose )ou had defined a counter in)our servlet class that $eeps trac$ of how man) service(" method invocations are currentl)running:

    private int counter ? 25

    Net suppose that )our service("method contained the following code:

    int m)Number ? counter 15 && line 1 counter ? m)Number5 && line C

    && rest of the code in the service(" method

    counter ? counter - 15

    8hat would happen if two service("methods were running at the same time and botheecuted line 1 before either eecuted line CQ 4oth would have the same value form)Number and the counter would not be properl) updated.

    or this situation the answer might be to s)nchroni

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    25/159

    still provide servlet support that complies with the J#/ 1.2 A!' definitions )ou need to becareful about upgrading to the new J#/.

    2e3 Servlet 4eatures in #S* 1/0

    J#/ C.2 adds the following servlet support:

    The interface #ingleThreadModelindicates to the server that onl) one thread can call

    the service("method at a time. Reader and 8riteraccess from #ervletRe%uestand #ervletResponse #everal *TT! session classes that can be used to provide state information that

    persists over multiple connections and re%uests between an *TT! client and an *TT!server.

    ;oo$ie support is now part of the standard servlet etension.

    #everal new *TT! response constants have been added to *ttp#ervletResponse elegation of ,T 7!T'7N# !+T and TRA; to appropriate methods in

    *ttp#ervlet

    J#/ C.2 deprecated one method:

    get#ervlets(" --)ou should use get#ervletNames("instead

    Page 25of 159

    http://java.sun.com/products/servlet/2.1/api/javax.servlet.SingleThreadModel.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#servicehttp://java.sun.com/products/jdk/1.1/docs/api/java.io.Reader.htmlhttp://java.sun.com/products/jdk/1.1/docs/api/java.io.Writer.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.ServletRequest.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.ServletResponse.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServletResponse.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.ServletContext.html#getServletshttp://java.sun.com/products/servlet/2.1/api/javax.servlet.ServletContext.html#getServletNameshttp://java.sun.com/products/servlet/2.1/api/javax.servlet.SingleThreadModel.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.Servlet.html#servicehttp://java.sun.com/products/jdk/1.1/docs/api/java.io.Reader.htmlhttp://java.sun.com/products/jdk/1.1/docs/api/java.io.Writer.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.ServletRequest.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.ServletResponse.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServletResponse.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.http.HttpServlet.htmlhttp://java.sun.com/products/servlet/2.1/api/javax.servlet.ServletContext.html#getServletshttp://java.sun.com/products/servlet/2.1/api/javax.servlet.ServletContext.html#getServletNames
  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    26/159

    lass 5avax/servlet/ServletInputStrea!5avax/servlet/ServletInputStrea!

    public abstract class ServletInputStrea!An input stream for reading servlet re%uests it provides an efficient read,ine method. This is

    an abstract class to be implemented b) a networ$ services writer. or some applicationprotocols such as the *TT! !7#T and !+T methods servlet writers use the input stream toget data from clients. The) access the input stream via the #ervletRe%uestDs get'nput#treammethod available from within the servletDs service method. #ubclasses of #ervlet'nput#treammust provide an implementation of the read(" method.See Also6

    readServletInputStrea!("

    The default constructor does no wor$.readLine(b)teFG int int"

    #tarting at the specified offset reads into the given arra) of b)tes until all re%uested

    b)tes have been read or a DEnD is encountered in which case the DEnD is read into thearra) as well.

    ServletInputStrea!protected #ervlet'nput#tream("

    The default constructor does no wor$.

    Methods/

    readLinepublic int read,ine(b)te bFG

    int off int len" throws '7ception

    #tarting at the specified offset reads into the given arra) of b)tes until all re%uestedb)tes have been read or a DEnD is encountered in which case the DEnD is read into thearra) as well.Para!eters6b - the buffer into which the data is readoff - the start offset of the datalen - the maimum number of b)tes to readReturns6the actual number of b)tes read or -1 if the end of the stream is reached

    Thro3s6'7ceptionif an '&7 error has occurred

    #ava Servlets and Applets

    4) now ever)one has heard of Java applets. 4ut ever) once in a while someone mentionsJava servlets. This article answers the %uestion @8hat is a Java servletQ@. 't also comparesservlets to ;B' and Java applets. More detailed information can be found at the Java #ervlet

    *ome !age.

    Page 26of 159

    http://java.sun.com/products/servlet/2.1/api/#ServletInputStream()http://java.sun.com/products/servlet/2.1/api/#readLine(byte[],%20int,%20int)http://java.sun.com/products/java-server/servlets/index.htmlhttp://java.sun.com/products/java-server/servlets/index.htmlhttp://java.sun.com/products/servlet/2.1/api/#ServletInputStream()http://java.sun.com/products/servlet/2.1/api/#readLine(byte[],%20int,%20int)http://java.sun.com/products/java-server/servlets/index.htmlhttp://java.sun.com/products/java-server/servlets/index.html
  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    27/159

    #ava Servlets

    A Java servlet is a Java program that eecutes on the 8eb or *TT! server in response tore%uests from a 8eb browser. The 8eb server software uses Java Oirtual Machine to run theservlet and generate an *TM, page. The servlet ta$es input from a *TM, page containing

    *TM, input tags processes it and returns a *TM, page with the results.

    Java #ervlets can be thought of as ;B' programs in some respects. 4oth servlets and ;B'eecute on the server in response to *TM, input. Thus both are limited to *TM, andJava#criptDs capabilities. *owever Java servlets are much more powerful that ;B' programsfor these reasons.

    #ervlets eecute as a thread within the 8eb server. Threaded eecution avoids the

    overhead of creating separate processes for each ;B' call. #ervlets ma) retain data between eecutions. or eample a servlet could retain a

    networ$ connection or access counter between eecutions. *owever coo$ies or

    similar solutions are still needed to retain data about an individual browser thataccesses the servlet.

    A servlet ma) connect to an) computer on the networ$ or write files on the server.

    8hile ;B' programs ma) also do these things Java servlets allow a platformindependent implementation.

    A servlet can use business ob0ects that are part of a larger distributed s)stem. This is

    difficult or impossible to accomplish with ;B'.

    To a Java servlet version in action clic$ here. A new window will appear with the servlet.

    #ava Applets

    A Java Applet is a Java program that eecutes on the 8eb browser. Java Applets are limitedto certain operations on the browser. Java applets can also use J4; connection ordistributed ob0ects. The Java applet allows more comple user interface options than *TM,combined with either ;B' or Java servlets. *owever the Java applet re%uires a Java-enabled 8eb browser. Applets have several advantages over *TM,.

    Applets allow local validation of data entered b) the user. ,ocal validation of data ispossible using *TM, combined with Java#cript but variances in Java#criptimplementations ma$e Java#cript difficult to generall) use.

    An applet can use the database to perform list of values loo$ups and data validation.*TM, (even if combined with Java#cript" can not do that without invo$ing a ;B' orservlet program and drawing a new *TM, page.

    7nce an applet is downloaded the amount of data transferred between the 8eb

    browser and the server is reduced. *TM, re%uires that the server transfer thepresentation of the data (the *TM, tags" along with the data itself. The *TM, tagscan easil) be 1&P to 1&C of the data transferred from the server to the client.

    Applets allow the designer to use comple B+' widgets such as grids spin controls

    and scrollbars. These widgets are not available to *TM,.

    Modelling using Session and (ntity (#7s

    Gopalan Suresh Ra5

    Page 27of 159

    http://www.cariboulake.com/cgi-bin/redirect_DemoServlet?command=StartPage&return=HTMLhttp://www.execpc.com/~gopalan/personal/cv.htmlhttp://www.cariboulake.com/cgi-bin/redirect_DemoServlet?command=StartPage&return=HTMLhttp://www.execpc.com/~gopalan/personal/cv.html
  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    28/159

    +se #ession 4eans for Application logic

    +se #ession 4eans as the only interface to the client

    pect little reuse of session beans

    +se session beans to control the wor$flow of a group of entit) beans

    +se ntit) 4eans to develop a persistent ob0ect model (wrap all )r. J4; code"

    +se ntit) 4eans to enforce accurac)&integrit) of )our database

    'nsist on reuse of ntit) 4eans

    +se ntit) 4eans to model domain ob0ects with a uni%ue identit) shared b) multiple clients

    'n general #ession 4eans are about a conversation with a client and ntit) 4eans are aboutrecords in the domain model.

    +se entit) beans for a persistant ob0ect model: eg. wrap up all )our 0dbc code etc. giving therest of )our application an ob0ect-oriented interface to )our data model. #ession beans are forapplication logic. or eample use session beans to model the la)er that interfaces with )ourob0ect-model but normall) should not go direct to )our database. Thus a set of session beansprovide all the functionalit) for a particular application of which there could be severalcommunicating with the ntit) based 7b0ect-Model. 't will be session beanDs J4ob0ects thatcommunicate with the front-end B+' code (or servlets etc.". *owever also be aware that entit)beans can have an ob0ect model behavior too. As alwa)s there are no hard and fast rules.

    +se #ession 4eans as the onl) interface to the client providing a @coarse grained@ facade tothe underl)ing model. 9ou should use entit) beans to enforce the accurac)& integrit)&

    auditabilit) of databases not merel) as an 77 representation of data. Then use sessionbeans to run the processes that operate on the databases. This split reduces the pain ofintroducing new& changed processes because testing& approval does not need to be sostringent.

    'nsist on reuse of entit) beans. The)Dll be hard to develop but over time the)Dll @define )ourcompan)@.

    pect little reuse of session beans. !lan instead to discard them and create new ones %uic$l)b) building a RA capabilit) around them as a means to competitiveness.

    levate ntities to a much higher level. ntities are good candidates to model businessob0ects& domain ob0ects which have a uni%ue identit) and need to be shared b) varoius clients

    and be persisted over a longer time. The) can also incorporate the business logic that goes onwith their responsibilit). #ession 4eans can be used whenever a business method re%uiresservices from two or more entities. 't is a good idea to have all interfaces to the s)stemthrough #essions beans.

    Intervie3 8uestions

    Servlets61. Servlet Life ycleA. The #ervlet life c)cle is as follows

    Z pu%lic void init+, thro3s Servlet(xception9

    pu%lic void init+Servletonfig config, thro3s Servlet(xception

    Page 28of 159

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    29/159

    ecuted once when the servlet is first loaded. Not called for each re%uest. +seget'nit!arameter to read initiali

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    30/159

    etc. as appropriate. Now if )ou have a servlet that needs to handle both !7#T andBT re%uests identicall) )ou ma) be tempted to override service directl) as belowrather than implementing both doBet and do!ost.public void service(*ttp#ervletRe%uest re%uest *ttp#ervletResponse response"throws #ervletception '7ception L

    && #ervlet ;odeThis is not a good idea. 'nstead 0ust have do!ost call doBet (or viceversa" as below.public void doBet(*ttp#ervletRe%uest re%uest *ttp#ervletResponse response"throws #ervletception '7ception L&& #ervlet ;odepublic void do!ost(*ttp#ervletRe%uest re%uest *ttp#ervletResponse response"throws #ervletception '7ception LdoBet(re%uest response"5

    Although this approach ta$es a couple of etra lines of code it has fiveadvantages over directl) overriding service:

    1. 9ou can add support for other services later b) adding do!ut doTrace etc.perhaps in a subclass. 7verriding service directl) precludes this possibilit).C. 9ou can add support for modification dates b) adding a get,astModified method. 'f)ou use doBet the standard service method uses the get,astModified method to set,ast-Modified headers and to respond properl) to conditionalBT re%uests (those containing an 'f-Modified-#ince header". #ee #ection C.V (Anample +sing #ervlet 'nitiali

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    31/159

    initialirepeats ? Integer/parseInt+repeatString,> catch+2u!%er4or!at(xception nfe, IE@En@ @=*1 A,'BN?;NTR@ title @=&*1@"5

    for(int i?25 i=repeats5 i" Lout.println(message @=4R@"5

    Page 31of 159

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    32/159

    out.println(@=&479=&*TM,@"5

    U. Servlet ontextA. #ervlets can also store persistent data in the #ervlet-;ontet ob0ect that is

    available through the get#ervlet;ontet method. #ervlet;ontet has setAttribute andgetAttribute methods that let )ou store arbitrar) data associated with specified $e)s.The difference between storing data in instance variables and storing it in the #ervlet-;ontet is that the #ervlet;ontet is shared b) all servlets in the servlet engine (or inthe 8eb application if )our server supports such a capabilit)".

    P. Ho3 you 3ill create a session in a servlet; $hat are the various 3ays ofcreating a session;

    A. The 2eed for Session Trac)ing*TT! is a \stateless] protocol: each time a client retrieves a 8eb page it

    opens a separate connection to the 8eb server and the server does not automaticall)maintain contetual information about a client. ven with serversthat support persistent ($eep-alive" *TT! connections and $eep a soc$et open formultiple client re%uests that occur close together in time there is no built-in support formaintaining contetual information. This lac$ of contet causes a number ofdifficulties. or eample when clients at an on-line store add an item to their shoppingcarts how does the server $now what[s alread) in themQ #imilarl) when clientsdecide to proceed to chec$out how can the server determine which previousl)created shopping carts are theirsQThere are three t)pical solutions to this problem: coo$ies +R,-rewritingand hidden form fields.1. Typical "ses of oo)iesZ 'dentif)ing a user during an e-commerce sessionZ Avoiding username and passwordZ ;ustomi

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    33/159

    for(int i?25 i=coo$ies.length5 i" L;oo$ie c ? coo$iesFiG5if (c.getName(".e%uals(@someName@"" Ldo#omething8ith(c"5brea$5

    Z Reading coo)ies fro! %ro3ser +si!plified approach,6tract coo$ie or coo$ie value from coo$ie arra) b) using#ervlet+tilities.get;oo$ie or#ervlet+tilities.get;oo$ieOalue.oo)ie MethodsZ geto!!ent=seto!!ent: gets&sets comment. Not supported in version 2 coo$ies(which are what most browsers now support".Z get*o!ain=set*o!ain: lets )ou specif) domain to which coo$ie applies. ;urrenthost must be part of domain specified.

    Z getMaxAge=setMaxAge: gets&sets the coo$ie epiration time (in seconds". 'f )ou failto set this coo$ie applies to current browsing session onl). #ee ,ong,ived;oo$iehelper class (#ection V.I".Z get2a!e=set2a!e: gets&sets the coo$ie name. or new coo$ies )ou suppl) nameto constructor not to setName. or incoming coo$ie arra) )ou use getName to findthe coo$ie of interest.Z getPath=setPath: gets&sets the path to which coo$ie applies. 'f unspecified coo$ieapplies to +R,s that are within or below director) containing current page.Z getSecure=setSecure: gets&sets flag indicating whether coo$ie shouldappl) onl) to ##, connections or to all connections.Z getCalue=setCalue: gets&sets value associated with coo$ie. or new coo$ies )ousuppl) value to constructor not to setOalue. or incoming coo$ie arra) )ou usegetName to find the coo$ie of interest then call getOalue on the result.Z getCersion=setCersion: gets&sets the coo$ie protocol version. Oersion 2 is thedefault5 stic$ with that until browsers start supporting version 1.

    C. Session Trac)ingLoo)ing "p Session Infor!ation6 getCalue*ttp#ession session ? re%uest.get#ession(true"5#hopping;art cart ? (#hopping;art"session.getOalue(@shopping;art@"5if (cart ?? null" L && No cart alread) in session

    cart ? new #hopping;art("5session.putOalue(@shopping;art@ cart"5do#omething8ith(cart"5Associating Infor!ation 3ith a Session6 putCalue*ttp#ession session ? re%uest.get#ession(true"5session.putOalue(@referring!age@ re%uest.get*eader(@Referer@""5#hopping;art cart ? (#hopping;art"session.getOalue(@previous'tems@"5if (cart ?? null" L && No cart alread) in sessioncart ? new #hopping;art("5session.putOalue(@previous'tems@ cart"5

    #tring item' ? re%uest.get!arameter(@item'@"5

    Page 33of 159

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    34/159

    if (item' 6? null" Lcart.add'tem(;atalog.get'tem(item'""5HttpSession MethodsZ pu%lic '%5ect getCalue+String na!e, D1/.E

    pu%lic '%5ect getAttri%ute+String na!e, D1/1Etracts a previousl) stored value from a session ob0ect. Returns null if no value isassociated with given name.Z pu%lic void putCalue+String na!e9 '%5ect value, D1/.Epu%lic void setAttri%ute+String na!e9 '%5ect value, D1/1EAssociates a value with a name. 'f value implements *ttp#ession4inding,istener itsvalue4ound method is called. 'f previous value implements*ttp#ession4inding,istener its value+nbound method is called.Z pu%lic void re!oveCalue+String na!e, D1/.Epu%lic void re!oveAttri%ute+String na!e, D1/1ERemoves an) values associated with designated name. 'f value being removed

    implements *ttp#ession4inding,istener its value+nbound method is called.Z pu%lic StringDE getCalue2a!es+, D1/.Epu%lic (nu!eration getAttri%ute2a!es+, D1/1EReturns the names of all attributes in the session.Z pu%lic String getId+,Returns the uni%ue identifier generated for each session.Z pu%lic %oolean is2e3+,Returns true if the client (browser" has never seen the session5 false otherwise.Z pu%lic long getreationTi!e+,Returns time at which session was first created (in milliseconds since 1HS2". To get avalue useful for printing pass value to ate constructor or the setTime'nMillis methodof Bregorian;alendar.Z pu%lic long getLastAccessedTi!e+,Returns time at which the session was last sent from the client.Z pu%lic int getMaxInactiveInterval+,pu%lic void setMaxInactiveInterval+int seconds,Bets or sets the amount of time in seconds that a session should go without accessbefore being automaticall) invalidated. A negative value indicates that session shouldnever time out. Not the same as coo$ie epiration date.Z pu%lic void invalidate+,'nvalidates the session and unbinds all ob0ects associated with it.

    U. (ncoding "RLs'n case servlet is using +R, rewriting to implement session trac$ing )oushould give the s)stem a chance to encode the +R,s.Z Regular "RLs#tring original+R, ? someRelative7rAbsolute+R,5#tring encoded+R, ? response.encode+R,(original+R,"5out.println(@=A *R?E@@ encoded+R, @E@...=&A@"5Z Redirect "RLs#tring original+R, ? some+R,5 && Relative +R, 7/ in C.C#tring encoded+R, ? response.encodeRedirect+R,(original+R,"5

    response.sendRedirect(encoded+R,"5

    Page 34of 159

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    35/159

    F/ Ho3 3ill you get the Re&uest dispatcher;A. 9ou obtain a Re%uestispatcher b) calling the getRe%uestispatcher method of

    #ervlet;ontet suppl)ing a +R, relative to the server root. or eample toobtain a Re%uestispatcher associated withhttp:&&)ourhost&presentations&presentation1.0sp )ou would do the following:

    #tring url ? @&presentations&presentation1.0sp@5Re%uestispatcher dispatcher ? get#ervlet;ontet(".getRe%uestispatcher(url"5

    / $hat are the various 3ays of for3arding a re&uest to #SP;A. 7nce )ou have a Re%uestispatcher )ou use forward to completel) transfer

    control to the associated +R, and use include to output the associated +R,[scontent. 'n both cases )ou suppl) the *ttp#ervletRe%uest and*ttp#ervletResponse as arguments. 4oth methods throw #ervletception and'7ception.Re&uest 4or3arding Syntax#tring url ? @&path&presentation1.0sp@5

    Re%uestispatcher dispatcher ? get#ervlet;ontet(".getRe%uestispatcher(url"5dispatcher.forward(re%uest response"5

    Getting a Re&uest*ispatcher %y Alternative Means +1/1 'nly,Z 7y na!e6 use getNamedispatcher method of #ervlet;ontet.Z 7y path relative to initial servlets location6 use the getRe%uestispatchermethod of *ttp#ervletRe%uest rather than the one from #ervlet;ontet.Including Static or *yna!ic ontentZ 7asic usage6response.set;ontentT)pe(@tet&html@"5!rint8riter out ? response.get8riter("5out.println(@...@"5Re%uestispatcher dispatcher ?get#ervlet;ontet(".getRe%uestispatcher(@&path&resource@"5dispatcher.include(re%uest response"5out.println(@...@"5Z J#! e%uivalent is 0sp:include(action" not the J#! include directive.4or3arding Re&uests fro! #SP PagesZ =0sp:forward page?@Relative +R,@ &

    Including Static or *yna!ic ontent

    'f a servlet uses the forward method of Re%uestispatcher it cannot actuall)send an) output to the client^it must leave that entirel) to the destination page. 'f theservlet wants to generate some of the content itself but use a J#! page or static*TM, document for other parts of the result the servletcan use the include method of Re%uestispatcher instead. The process is ver) similarto that for forwarding re%uests: call the getRe%uestispatcher method of#ervlet;ontet with an address relative to the server root then call include with the*ttp#ervletRe%uest and *ttp#ervletResponse.

    The two differences when include is used are that )ou can send content tothe browser before ma$ing the call and that control is returned to the #ervlet after theinclude call finishes. Although the included pages (servlets J#! pages or even static

    *TM," can send output to the client the) should not tr) to set *TT! responseheaders. *ere is an eample:

    Page 35of 159

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    36/159

    response.set;ontentT)pe(@tet&html@"5!rint8riter out ? response.get8riter("5out.println(@...@"5Re%uestispatcher dispatcher ?get#ervlet;ontet(".getRe%uestispatcher(@&path&resource@"5

    dispatcher.include(re%uest response"5out.println(@...@"5

    *owever include does one thing that forward does not: it automaticall) sets upattributes in the *ttp-#ervletRe%uest ob0ect that describe the original re%uest path incase the included servlet or J#! page needs that information. These attributesavailable to the included resource b) calling getAttribute on the *ttp-#ervletRe%uestare listed below:Z 0ava.servlet.include.re%uestXuriZ 0ava.servlet.include.contetXpathZ 0ava.servlet.include.servletXpath

    Z 0ava.servlet.include.pathXinfoZ 0ava.servlet.include.%uer)Xstring

    / Ho3 context can %e transferred fro! servlet to #SP;A. response.sendredirect and re%uestdispatcher.forward(" mechanisms are used.

    J/ Ho3 can you 3rite a 4TP Servlet;A. 4) etending Beneric #ervlet.

    K/ *ifference %et3een Re&uest*ispatcher9 for3ard and response/sendredirect;A. 'f )ou redirect users to a page within )our site plan ahead for session trac$ing b)

    using response.sendRedirect(response.encode+R,(url"" rather than 0ustresponse.sendRedirect(url". 8ith sendRedirect the servlet automaticall) builds apage containing the lin$ to show to older browsers that don[t automaticall) followredirects. inall) with version C.C of servlets (the version in JC" sendRedirect canhandle relative +R,s automaticall) translating them into absolute ones. 9ou must usean absolute +R, in version C.1 however.

    #SP./ *ifference %et3een Servlets and #SPA. J#! doesn[t provide an) capabilities that couldn[t in principle be accomplished with a

    servlet. 'n fact J#! documents are automaticall) translated into servlets behind thescenes. 4ut it is more convenient to write (and to modif)6" regular *TM, than to havea

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    37/159

    To simplif) these epressions )ou can use a number of predefined variables.The most important ones are:Z re&uest the *ttp#ervletRe%uestZ response the *ttp#ervletResponseZ session the *ttp#ession associated with the re%uest (unless

    disabled with the session attribute of the page directive ^ see#ection 11.P"Z out the !rint8riter (a buffered version called Jsp8riter"used to send output to the client

    *ere is an eample:9our hostname: =3? re%uest.getRemote*ost(" 3

    _M, #)nta for pressions : =0sp:epression

    Java Expression=&0sp:epression

    (x6

    =479=*CJ#! pressions=&*C=+,=,';urrent time: ? ne3 5ava/util/*ate+, N=,'9our hostname: ? re&uest/getRe!oteHost+, N=,'9our session ': ? session/getId+, N=,'The =;7test!aram=&;7 form parameter:? re&uest/getPara!eter+@testPara!@, N=&+,=&479

    C. Scriptletsof the form =3 code 3 which are inserted into the servlet[sX0sp#ervice method (called b) service". 'f )ou want to do something more complethan insert a simple epression J#! scriptlets let )ou insert arbitrar) code into theservlet[s X0sp#ervice method (which is called b) service". #criptlets have the followingform:=3 Java Code 3#criptlets have access to the same automaticall) defined variables asepressions (re%uest response session out etc.5 see #ection 12.I". #ofor eample if )ou want output to appear in the resultant page )ou woulduse the out variable as in the following eample.Attached BT data: =3? re%uest.getYuer)#tring(" 3

    'n general however scriptlets can perform a number of tas$s that cannotbe accomplished with epressions alone. These tas$s include setting responseheaders and status codes invo$ing side effects such as writing to the serverlog or updating a database or eecuting code that contains loops conditionalsor other comple constructs.(x6 =bod)=3#tring bg;olor ? re%uest.get!arameter(@bg;olor@"5boolean hasplicit;olor5

    if (bg;olor 6? null" Lhasplicit;olor ? true5

    Page 37of 159

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    38/159

    else Lhasplicit;olor ? false5bg;olor ? @8*'T@53

    =479 4B;7,7R?@=3? bg;olor 3@=*C A,'BN?@;NTR@;olor Testing=&*C=3if (hasplicit;olor" Lout.println(@9ou supplied an eplicit bac$ground color of @ bg;olor @.@"5 else Lout.println(@+sing default bac$ground color of 8*'T. @ @#uppl) the bg;olor re%uest attribute to tr) @ @a standard color an RRBB44 value or to see @ @if )our browser supports _11 color names.@"5

    3=&479

    U. *eclarationsof the form =36 code 3 which are inserted into the bod) of theservlet class outside of an) eisting methods. A J#! declaration lets )ou definemethods or fields that get inserted into the main bod) of the servlet class (outside ofthe X0sp#ervice method that is called b) service to process the re%uest". A declarationhas the following form: O ava Code N #ince declarations do not generate an)output the) are normall) used in con0unction with J#! epressions or scriptlets.(x6=479=*1J#! eclarations=&*1=36 private int access;ount ? 25 3=*CAccesses to page since server reboot:=3? access;ount 3=&*C=&479

    2ote6;hec$ the page ;omp[s-of-0spin the same folder

    U. $hat are the scopes in 5sp;A. page session application re%uest.

    P.$hat is the difference %et3een the session and application scope;A. application

    Means that in addition to being bound to a local variable bean will be stored inshared #ervlet;ontet available through predefined application variable or b) a call toget#ervlet;ontet(".This means a variable is created per application to all users.

    sessionMeans that in addition to being bound to a local variable bean will be stored in*ttp#ession ob0ect associated with current re%uest where it can be retrieved withgetOalue. This means a variable is created per session per user.

    I. an a 5sp extend any class;A. The etends attribute indicates the superclass of the servlet that will be generated

    Page 38of 159

    http://var/www/apps/scribd/scribd/tmp/scratch7/Comp's-of-JSP.dochttp://var/www/apps/scribd/scribd/tmp/scratch7/Comp's-of-JSP.doc
  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    39/159

    for the J#! page and ta$es the following form:=3` page etends?@pacage!class@ 3

    +se this attribute with etreme caution since the server ma) be using a customsuperclass alread).

    . #SP- A sa!ple #sp fileA.

    =67;T9! *TM, !+4,'; @-&&8U;&&T *TM, P.2 Transitional&&N@=*TM,=*A=T'T,J#! pressions=&T'T,=MTA NAM?@author@ ;7NTNT?@Mart) *all@=MTA NAM?@$e)words@;7NTNT?@J#!epressionsJava#erver!agesservlets@=MTA NAM?@description@ ;7NTNT?@A %uic$ eample of J#! epressions.@=,'N/ R,?#T9,#*T *R?@J#!-#t)les.css@ T9!?@tet&css@=&*A

    =479=*CJ#! pressions=&*C=+,=,';urrent time: ? ne3 5ava/util/*ate+, N=,'9our hostname: ? re&uest/getRe!oteHost+, N=,'9our session ': ? session/getId+, N=,'The =;7test!aram=&;7 form parameter:? re&uest/getPara!eter+@testPara!@, N=&+,=&479=&*TM,

    S. #sp I!plicit '%5ectsA. As a J#! author )ou have access to certain ob0ects that are available for use in J#!

    documents without being declared first. These ob0ects are parsed b) the J#! engine andinserted into the generated #ervlet as if )ou defined them )ourself. 'n realit) the J#!engine recogni

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    40/159

    note that out is used almost eclusivel) in scriptlets since J#! epressions areautomaticall) placed in the output stream and thus rarel) need to refer to out eplicitl).session 6 This variable is the *ttp#ession ob0ect associated with the re%uest. Recallthat sessions are created automaticall) so this variable is bound even if there is noincoming session reference. The one eception is if )ou use the session attribute of

    the page directive to turn sessions off. 'n that case attempts to reference the sessionvariable cause errors at the time the J#! page is translated into a servlet.application 6 This variable is the #ervlet;ontet as obtained viaget#ervlet;onfig(".get;ontet(". #ervlets and J#! pages can store persistent datain the #ervlet;ontet ob0ect rather than in instance variables. #ervlet;ontet hassetAttribute and getAttribute methods that let )ou store arbitrar) data associated withspecified $e)s. The difference between storing data in instance variables and storing itin the #ervlet- ;ontet is that the #ervlet;ontet is shared b) all servlets in the servletengine (or in the 8eb application if )our server supports such acapabilit)".config 6 This variable is the #ervlet;onfig ob0ect for this page.

    pageontext 6 J#! introduced a new class called !age;ontet to give a single pointof access to man) of the page attributes and to provide a convenient placeto store shared data. The page;ontet variable stores the value of the !age;ontetob0ect associated with the current page.page 6 This variable is simpl) a s)non)m for this and is not ver) useful in theJava programming language. 't was created as a place holder for the time when thescripting language could be something other than Java.

    V. *ifference %et3een page and pageontext;A. pageontext

    J#! introduced a new class called !age;ontet to give a single point ofaccess to man) of the page attributes and to provide a convenient placeto store shared data. The page;ontet variable stores the value of the!age;ontet ob0ect associated with the current page. #ee #ection 1U.P(#haring 4eans" for a discussion of its use.

    page

    This variable is simpl) a s)non)m for this and is not ver) useful in theJava programming language. 't was created as a place holder for thetime when the scripting language could be something other than Java.

    H. HTTP HeadersA. #ee the document *ttp *eaders.

    12. $hat is the difference %et3een 5sp static and dyna!ic include;A. The J#! include directive is used to insert tet and code into a J#! at translation

    time. After the initial re%uest is processed the data included does not change until theincluded file is changed and the server is restarted.The s)nta of the include directiveis =3` include file?@relative+R,spec@ 3

    The file that the file attribute points to can reference a normal tet *TM, file or aJ#! file which will be evaluated at translation time.

    5sp6includeN

    Page 40of 159

    http://var/www/apps/scribd/scribd/tmp/scratch7/HTTP%20headers.dochttp://var/www/apps/scribd/scribd/tmp/scratch7/HTTP%20headers.doc
  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    41/159

    The =0sp:include action provides a mechanism for including additional static andd)namic resources in the current J#! page. The s)nta for this action is as follows:=0sp:include page?@url#pec@ flush?@true@ &and=0sp:include page?@url#pec@ flush?@true@

    =0sp:param ... & =&0sp:include

    The first s)nta description does a re%uest-time inclusion whereas the secondcontains a list of param subelements that are used to argue the re%uest for thepurpose of inclusion. ollowingcontains the attributes and their descriptions for the=0sp:include action.Attri%ute *efinitionpage This attribute represents the relative +R, of the resource to be

    included.flush This attribute represents a mandator) 4oolean value stating

    whether or not the buffer should be flushed. ;urrentl) true is

    the onl) valid value for this attribute.

    #*7

    1.$rite a classA.import 0ava.s%l.K5class Jdbc1 L tr) L class.forName(\sun.0dbc.odbc.Jdbc7dbcriver]"5 ;onnection con ?riverManger.get;onnection(\0dbc:odbc:anil]] \] \"5 #tatement stmt ? con.create#tatement(": Result#et rs ? stmt.eecuteYuer)(\#elect K from mp]"5 8hile(rs.net("" L #tring s ? rs.get#tring(\Name]"5 #tring c ? rs.get#tring(\mpcode]": #)stem.out.println(s] \] \c"5catch(ception c"L #)stem.out.println(e"5

    C.$hen do you use execute8uery+,;A. The method used most often for eecuting #Y, statements is eecuteYuer) .

    This method is used to eecute #,;T statements which comprise the vast ma0orit)of #Y, statements.

    U. $hen do you use execute"pdate+,;A. 8e use the method eecute+pdate because the #Y, statement contained in

    createTable;offees is a , (data definition language" statement. #tatements thatcreate a table alter a table or drop a table are all eamples of , statements and

    are eecuted with the method eecute+pdate . As )ou might epect from its namethe method eecute+pdate is also used to eecute #Y, statements that update a

    Page 41of 159

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    42/159

    table. 'n practice eecute+pdate is used far more often to update tables than it is tocreate them because a table is created once but ma) be updated man) times.

    P. Ho3 3ill you do exception Handling;A. J4; lets )ou see the warnings and eceptions generated b) )our 4M# and b) the Java

    compiler. To see eceptions )ou can have a catch bloc$ print them out. or eample thefollowing two catch bloc$s from the sample code print out a message eplaining theeception:tr) L&& ;ode that could generate an eception goes here. 'f an eception is generated the catch&&bloc$ below will print out information about it. catch(#Y,ception e" L

    #)stem.err.println(@#Y,ception: @ e.getMessage(""5

    tr) L

    ;lass.forName(@m)river;lassName@"5 catch(0ava.lang.;lassNotoundception e" L

    #)stem.err.print(@;lassNotoundception: @"5#)stem.err.println(e.getMessage(""5

    There are actuall) three components however and to be complete )ou can printthem all out. The following code fragment shows a catch bloc$ that is complete in two wa)s.irst it prints out all three parts of an #Y,ception ob0ect: the message (a string thatdescribes the error" the #Y, state (a string identif)ing the error according to the _&7pen#Y,#tate conventions" and the vendor error code (a number that is the driver vendorDs errorcode number". The #Y,ception ob0ect e is caught and its three components areaccessed with the methods getMessage get#Y,#tate and getrror;ode

    I. +sage of finall)L statementA. "sing finally

    The generali

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    43/159

    P. Native-protocol pure Java driverach of these t)pes meets a different application need as weDll discuss in the followingsections.Type .6 #*7-'*7 7ridge9 Plus '*7 *riverThe first t)pe of J4; driver is the J4;-74; 4ridge. This driver t)pe is provided b) #un

    with the J/1.1 and later. 't provides J4; access to databases through 74; drivers. The74; driver must be configured on the client for the bridge to wor$. This driver t)pe iscommonl) used for protot)ping or when there is no J4; driver available for a particularatabase Management #)stem (4M#".Type 16 2ative-API *riverThe native-A!' driver converts J4; commands into 4M#-specific native calls. This ismuch li$e the restriction of T)pe 1 drivers. The client must have some binar) code loaded onits machine. These drivers do have an advantage over T)pe 1 drivers because the) interfacedirectl) with the database.Type Q6 #*7-2et9 Pure #ava *riverThe J4;-Net drivers are a three-tier solution. This t)pe of driver translates J4; calls into

    a database independent networ$ protocol that is sent to a middleware server. This serverthen translates this 4M# independent protocol into a 4M#-specific protocol which is sentto a particular database. The results are routed bac$ through the middleware server and sentbac$ to the client. This t)pe of solution ma$es it possible to implement a pure Java client. 'talso ma$es it possible to swap databases without affecting the client. This is b) far the mostfleible J4; solution.Type 6 2ative-Protocol9 Pure #ava *riverThe T)pe P drivers are pure Java drivers that communicate directl) with the vendorDsdatabase. The) do this b) converting J4; commands directl) into the database engineDsnative protocol. The T)pe P driver has a ver) distinct advantage over all the other drivert)pes. 't has no additional translation or middleware la)ers which improves performancetremendousl).

    S. $hat is prepared state!ent; +Pre-co!piled,A. 'f )ou want to eecute a #tatement ob0ect man) times it will normall) reduce eecutiontime to use a !repared#tatement ob0ect instead.

    The main feature of a !repared#tatement ob0ect is that unli$e a #tatement ob0ect it isgiven an #Y, statement when it is created. The advantage to this is that in most cases this#Y, statement will be sent to the 4M# right awa) where it will be compiled. As a result the!repared#tatement ob0ect contains not 0ust an #Y, statement but an #Y, statement thathas been precompiled. This means that when the !repared#tatement is eecuted the 4M#

    can 0ust run the !repared#tatement Ds #Y, statement without having to compile it first.

    V. Ho3 3ill you use prepared State!ent;A. As with #tatement ob0ects )ou create !repared#tatement ob0ects with a ;onnectionmethod. +sing our open connection con from previous eamples )ou might write code suchas the following to create a !repared#tatement ob0ect that ta$es two input parameters:

    PreparedState!ent updateSales ? con/prepareState!ent+ @"P*AT( '44((S S(T SAL(S ? ; $H(R( '42AM( LI( ;@,>

    9ou will need to suppl) values to be used in place of the %uestion mar$ placeholdersif there are an) before )ou can eecute a !repared#tatement ob0ect. 9ou do this b) callingone of the set___ methods defined in the class !repared#tatement . 'f the value )ou want to

    substitute for a %uestion mar$ is a Java int )ou call the method set'nt. 'f the value )ou want

    Page 43of 159

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    44/159

    to substitute for a %uestion mar$ is a Java #tring )ou call the method set#tring and so on.'n general there is a set___ method for each t)pe in the Java programming language.ode 4rag!ent .6 #tring update#tring ? @+!AT ;7# #T #A,# ? SI @

    @8*R ;7XNAM ,'/ D;olombianD@5

    stmt.eecute+pdate(update#tring"5ode 4rag!ent 16

    !repared#tatement update#ales ? con.prepare#tatement(@+!AT ;7# #T #A,# ? Q 8*R ;7XNAM ,'/ Q @"5update#ales.set'nt(1 SI"5update#ales.set#tring(C @;olombian@"5update#ales.eecute+pdate(":

    H. $hat is a calla%le state!ent;A. A ;allable#tatement ob0ect contains a call to a stored procedure5 it does not contain the

    stored procedure itself.

    12. Ho3 3ill you use calla%le state!ent;A. The first line of code below creates a call to the stored procedure #*78X#+!!,'R#using the connection con . The part that is enclosed in curl) braces is the escape s)nta forstored procedures. 8hen the driver encounters @Lcall #*78X#+!!,'R#@ it will translatethis escape s)nta into the native #Y, used b) the database to call the stored procedurenamed #*78X#+!!,'R#.(x6

    ;allable#tatement cs ? con.prepare;all(@Lcall #*78X#+!!,'R#@"5Result#et rs ? cs.eecuteYuer)("5

    11. Ho3 do you release connections;A. This final section is used to put our connection bac$ into the ;onnection!ool for furtheruse. The connection is released b) calling the pool.release;onnection(" method with the;onnection ob0ect. This method call is placed in the finall) bloc$ to guarantee its eecution.(x6

    finall) Ltr) Lif ( con 6? null " L&& release the connection no matter what

    pool.release;onnection(con"5catch (ception e" Lout.println(e.getMessage(""5

    1C. Ho3 do you parse result set;A.

    1U.$hat is rs/next+,; $hat happens 3ith this;A. The variable rs which is an instance of Result#et contains the rows of coffees

    Page 44of 159

  • 7/23/2019 6795986-Servelet-s-Faqs.pdf

    45/159

    and prices shown in the result set eample above. 'n order to access the names andprices we will go to each row and retrieve the values according to their t)pes. Themethod net moves what is called a cursor to the net row and ma$es that row (calledthe current row" the one upon which we can operate. #ince the cursor is initiall)positioned 0ust above the first row of a Result#et ob0ect the first call to the method

    net moves the cursor to the first row and ma$es it the current row. #uccessiveinvocations of the method net move the cursor down one row at a time from top tobottom.

    1P. Autoco!!it+,9 co!!it+,9 roll%ac)+,A. 8hen a connection is created it is in auto-commit mode. This means that each individual#Y, statement is treated as a transaction and will be automaticall) committed right after it iseecuted. (To be more precise the default is for an #Y, statement to be committed when itis completed not when it is eecuted. A statement is completed when all of its result sets andupdate counts have been retrieved. 'n almost all cases however a statement is completedand therefore committed right after it is eecuted."

    The wa) to allow two or more statements to be grouped into a transaction is todisable auto-commit mode. This is demonstrated in the fol