+ All Categories
Home > Documents > Servlets,Struts FAQs(P)

Servlets,Struts FAQs(P)

Date post: 04-Jun-2018
Category:
Upload: vijaykumar015
View: 223 times
Download: 0 times
Share this document with a friend

of 35

Transcript
  • 8/13/2019 Servlets,Struts FAQs(P)

    1/35

    1

    Servlets & Struts :

    1) How do I support both GET and POST protocol from the same Servlet

    The easy way is, just support POST, then have your doGet method call your doPostmethod:

    public void doGet(HttpServletReuest re, HttpServletResponse res!

    throws Servlet"#ception, $O"#ception

    % doPost(re, res!&

    '

    !) How do I ensure that m" servlet #s thread$safe

    This is actually a very comple# issue) * +ew uidelines:

    -) The init (! method is uaranteed to be called once per servlet instance,when the servlet is loaded) .ou don/t have to worry about thread sa+ety inside

    this method, since it is only called by a sinle thread, and the web server willwait until that thread e#its be+ore sendin any more threads into your

    service(! method)

    0) "very new client reuest enerates (or allocates! a new thread& that thread

    calls the service (! method o+ your servlet (which may in turn call doPost(!,doGet(! and so +orth!)

    1) 2nder most circumstances, there is only one instance o+ your servlet, nomatter how many client reuests are in process) That means that at any

    iven moment, there may be many threads runnin inside the service(!method o+ your solo instance, all sharin the same instance data and

    potentially steppin on each other/s toes) This means that you should becare+ul to s"nchron#%eaccess to shared data (instance variables! usin the

    synchroni3ed 4eyword)

    (5ote that the server will also allocate a new instance i+ you reister theservlet with a new name and, e)), new init parameters)!

    6) 5ote that you need not (and should not! synchroni3e on local data or

    parameters) *nd especially you shouldn/t synchroni3e the service (! method7

    (Or doPost(!, doGet(! et al)!

    8) * simple solution to synchroni3in is to always synchroni3e on the servlet

    instance itsel+ usin 9amp&uot&synchroni3ed (this! % ))) '9amp&uot&)However, this can lead to per+ormance bottlenec4s& you/re usually better o++

    synchroni3in on the data objects themselves)

  • 8/13/2019 Servlets,Struts FAQs(P)

    2/35

    2

    ) $+ you absolutely can/t deal with synchroni3in, you can declare that yourservlet 9amp&uot&implements SinleThread;odel9amp&uot&) This empty

    inter+ace tells the web server to only send one client reuest at a time intoyour servlet) oc: "If the target servlet is flagged

    with this interface, the servlet programmer is guaranteed that no two threadswill execute concurrently the service method of that servlet. This guarantee is

    ensured by maintaining a pool of servlet instances for each such servlet, anddispatching each service call to a free servlet. In essence, if the servletimplements this interface, the servlet will be thread safe."5otethat this is not an ideal solution, since per+ormance may su++er (dependin on

    the si3e o+ the instance pool!, plus it/s more di++icult to share data acrossinstances than within a sinle instance)

    See also ?hat/s a better approach +or enablin thread@sa+e servlets and =SPsA

    SinleThread;odel $nter+ace or Synchroni3ationA

    B) To share data across successive or concurrent reuests, you can use either

    instance variables or class@static variables, or use Session Trac4in)

    C) The destroy(! method is not necessarily as clean as the init(! method) The

    server calls destroy e#thera+ter all service calls have been completed, ora+ter a certain number o+ seconds have passed, whichever comes +irst) This

    means that other threads miht be runnin service reuests at the same timeas your destroy(! method is called7 So be sure to synchroni3e, andDor wait +or

    the other reuests to uit) Sun/s Servlet Tutorial has an e#ample o+ how to dothis with re+erence countin)

    E) destroy(! cannot throw an e#ception, so i+ somethin bad happens, calllo(! with a help+ul messae (li4e the e#ception!) See the 9amp&uot&closin

    a =>F connection9amp&uot& e#ample in Sun/s Tutorial)

    ) 'hat #s the d#fference between (* encod#n+, (* rewr#t#n+, HT-* escap#n+, and

    ent#t" encod#n+

    (* Encod#n+is a process o+ trans+ormin user input to a G$ +orm so it is +it +ortravel across the networ4 @@ basically, strippin spaces and punctuation and replacin

    with escape characters) 2R >ecodin is the reverse process) To per+orm theseoperations, call java)net)2R"ncoder)encode(! and java)net)2R>ecoder)decode(!

    (the latter was (+inally7! added to =>I -)0, a4a =ava 0!)

    E.ample:chanin J?e/re K-7J into J?eL0BreML01-L0-J

    (* ewr#t#n+is a techniue +or savin state in+ormation on the user/s browser

    between pae hits) $t/s sort o+ li4e coo4ies, only the in+ormation ets stored insidethe 2R, as an additional parameter) The HttpSession *P$, which is part o+ theServlet *P$, sometimes uses 2R Rewritin when coo4ies are unavailable)

    E.ample:chanin N* HR"

  • 8/13/2019 Servlets,Struts FAQs(P)

    3/35

    3

    There/s also a +eature o+ the *pache web servercalled 2R Rewritin& it is enabledby the modrewrite module) $t rewrites 2Rs on their way #nto the server, allowin

    you to do thins li4e automatically add a trailin slash to a directory name, or to mapold +ile names to new +ile names) This has nothin to do with servlets)

  • 8/13/2019 Servlets,Struts FAQs(P)

    4/35

    4

    U =un $namori has written a class calledor)apache)tomcat)reuest)Parse;ime which is available in the TomcatS

    tree)

    U =SPSmarthas a +ree set o+ =SP +or doin +ile upload and download)

    U 2ploadFeanby =avaWoom claims to handle most o+ the hassle o+ uploadin+or you, includin writin to dis4 or memory)

    U There/s an 2pload Ta in dot=

    Once you process the +orm@data stream into the uploaded +ile, you can then either

    write it to dis4, write it to a database, or process it as an $nputStream, dependin onyour needs) See How can $ access or create a +ile or +older in the current directory

    +rom inside a servletA and other uestions in the Servlets:

  • 8/13/2019 Servlets,Struts FAQs(P)

    5/35

    5

    Njsp:useFean idJ+FeanJ classJovi)

  • 8/13/2019 Servlets,Struts FAQs(P)

    6/35

    6

    handled by the servlet/s service(! method in a concurrent +ashion (i)e) the service(!method handles each client reuest within a seperate thread concurrently)!

    There have been some recent studies contrastin the per+ormance o+ servlets with Perl scriptsrunnin in a Jreal@li+eJ environment) The results are +avorable to servlets, especially when they are

    runnin in a clustered environment)

    19) How do I call one servlet from another servlet

    X Short answer: there are several ways to do this, includin

    U use a Reuest>ispatcher

    U use a 2Ronnectionor HTTPlient

    U send a redirect

    U call etServletonte#t(!)etServlet(name! (deprecated, doesn/t wor4 in0)-M!

    @ *le#

    $t depends on what you mean by JcallJ and what it is you see4 to do and why you

    see4 to do it)

    $+ the end result needed is to invo4e the methods then the simplest mechanism

    would be to treat the servlet li4e any java object , create an instance and call the

    mehods)$+ the idea is to call the service method +rom the service method o+ another servlet,*I* +orwardin the reuest, you could use the Reuest>ispatcher object)

    $+, however, you want to ain access to the instance o+ the servlet that has beenloaded into memory by the servlet enine, you have to 4now the alias o+ the servlet)

    (How it is de+ined depends on the enine)! Ia servlet can be named by the property

    myname)codecom)sameer)servlets);yServlet

    The code below shows how this named servlet can be accessed in the service method

    o+ another servlet

    public void service (HttpServletReuest reuest, HttpServletResponse response!

    throws Servlet"#ception, $O"#ception %

    ))) ;yServlet ms(;yServlet!

    etServleton+i(!)etServletonte#t(!)etServlet(JmynameJ!& )))

    '

    http://www.jguru.com/jguru/faq/view.jsp?EID=206736http://www.jguru.com/jguru/faq/view.jsp?EID=31753http://www.innovation.ch/java/HTTPClient/http://www.jguru.com/jguru/faq/view.jsp?EID=126245http://www.jguru.com/jguru/faq/view.jsp?EID=206736http://www.jguru.com/jguru/faq/view.jsp?EID=31753http://www.innovation.ch/java/HTTPClient/http://www.jguru.com/jguru/faq/view.jsp?EID=126245
  • 8/13/2019 Servlets,Struts FAQs(P)

    7/35

    7

    That said, This whole apporach o+ accessin servlets in another servlets has beendeprecated in the 0)- version o+ the servlet *P$ due to the security issues) The

    cleaner and better apporach is to just avoid accessin other servlets directly and usethe Reuest>ispatcher instead)

    11) 'hat are all the d#fferent #nds of servers ;Such as 'eb Servers, 6ppl#cat#on

    Servers, etc)

    The servers involved in handlin and processin a user/s reuest brea4 down into a+ew basic types, each o+ which may have one or more tas4s it solves) This +le#ibility

    ives developers a reat deal o+ power over how applications will be created and

    deployed, but also leads to con+usion over what server is able to, or should, per+orma speci+ic tas4)

    Startin at the basic level, a user is typically submittin a reuest to a system

    throuh a web browser) (?e are conveniently inorin all other types o+ clients (R;$,

    ORF*, O;D>O;, ustom, etc))! +or the time bein +or purposes o+ clarity)! Theweb reuest must be received by a 'eb Server(otherwise 4nown as an HTTP

    Server! o+ some sort) This web server must handle standard HTTP reuests andresponses, typically returnin HT; to the callin user) ode that e#ecutes within the

    server environment may be G$ driven, Servlets, *SP, or some other server@sideprorammin lanuae, but the end result is that the web server will pass bac4

    HT; to the user)

    The web server may need to e#ecute an application in response to the users reuest)

    $t may be eneratin a list o+ news items, or handlin a +orm submission to a uestboo4) $+ the server application is written as a =ava Servlet, it will need a place to

    e#ecute, and this place is typically called a Servlet En+#ne) >ependin on the webserver, this enine may be internal, e#ternal, or a completely di++erent product) This

    enine is continually runnin, unli4e a traditional G$ environment where a G$script is started upon each reuest to the server) This persistance ives a servlet

    connection and thread poolin, as well as an easy way to maintain state betweeneach HTTP reuest) =SP paes are usually tied in with the servlet enine, and would

    e#ecute within the same spaceDapplication as the servlets)

    There are many products that handle the web servin and the servlet enine in

    di++erent manners) 5etscapeDiPlanet "nterprise Server builds the servlet eninedirectly into the web server and runs within the same process space) *pache reuires

    that a servlet enine run in an e#ternal process, and will communicate to the eninevia TPD$P soc4ets) Other servers, such as ;S $$S don/t o++icially support servlets,

    and reuire add@on products to add that capability)

    ?hen you move on to "nterprise =avaFeans (and other =0""components li4e =;S

    and ORF*! you move into the application server space) *n 6ppl#cat#on Serverisany server that supplies additional +unctionality related to enterprise computin @@ +or

    instance, load balancin, database access classes, transaction processin,messain, and so on)

    E0ependin on the application server, prorammers

    http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/
  • 8/13/2019 Servlets,Struts FAQs(P)

    8/35

    8

    may use ORF* or R;$ to tal4 to their beans, but the baseline standard is to use=5>$ to locate and create "=F re+erences as necessary)

    5ow, one thin that con+uses the issue is that many application server providersinclude some or all o+ these components in their product) $+ you loo4 at ?eboic

    (http:DDwww)beasys)comD! you will +ind that ?eboic contains a web server, servletenine, =SP processor, =;S +acility, as well as an "=F container) Theoretically a

    product li4e this could be used to handle all aspects o+ site development) $n practice,you would most li4ely use this type o+ product to manaeDserve "=F instances, while

    dedicated web servers handle the speci+ic HTTP reuests)

    1=) Should I overr#de the serv#ce;) method 5o) $t provides a +air bit o+ house4eepin that you/d just have to do yoursel+) $+ you need to dosomethin reardless o+ whether the reuest is e)), a POST or a G"T, create a helper method and

    call that at the beinnin o+ e)), doPost(! and doGet(!)

    1!) How can m" appl#cat#on +et to now when a HttpSess#on #s removed ;when #t t#me$

    outs) >e+ine a class, say SessionTimeout5oti+ier, that implements

    java#)servlet)http)HttpSessionFindinistener) reate a SessionTimeout5oti+ier object and add it tothe user session) ?hen the session is removed, SessionTimeout5oti+ier)value2nbound(! will be

    called by the servlet enine) .ou can implement value2nbound(! to do whatever you want)

    1) 'h" use 0SP when we can do the same th#n+ w#th servlets

    XOriinal uestion: ?hy should $ use =SP when there is already servlet technoloy

    available +or servin dynamic contentA

    ?hile =SP may be reat +or servin up dynamic ?eb content and separatin content

    +rom presentation, some may still wonder why servlets should be cast aside +or =SP)

    The utility o+ servlets is not in uestion) They are e#cellent +or server@sideprocessin, and, with their sini+icant installed base, are here to stay) $n +act,

    architecturally spea4in, you can view =SP as a hih@level abstraction o+ servlets that

    is implemented as an e#tension o+ the Servlet 0)- *P$) Still, you shouldn/t useservlets indiscriminately& they may not be appropriate +or everyone) " @@ a process that enerally reuires a hiher level o+prorammin e#pertise)

    ?hen deployin servlets, even developers have to be care+ul and ensure that there isno tiht couplin between presentation and content) .ou can usually do this by

    addin a third@party HT; wrapper pac4ae li4e htmlIona to the mi#) Fut even this

    approach, thouh providin some +le#ibility with simple screen chanes, still does notshield you +rom a chane in the presentation +ormat itsel+) HT;, you would still need to ensure that

    wrapper pac4aes were compliant with the new +ormat) $n a worst@case scenario, i+ awrapper pac4ae is not available, you may end up hardcodin the presentation

    within the dynamic content) So, what is the solutionA One approach would be to useboth =SP and servlet technoloies +or buildin application systems)

  • 8/13/2019 Servlets,Struts FAQs(P)

    9/35

    9

    1/) How do I send #nformat#on and data bac and forth between applet and servlet us#n+the HTTP protocol

    2se the standard java)net)2R class, or Jroll your ownJ usin java)net)Soc4et) See

    the HTTP specat ?1 +or more detail)

    5ote: The servlet cannot initiate this connection7 $+ the servlet needs to

    asynchronously send a messae to the applet, then you must open up a persistent

    soc4et usin java)net)Soc4et (on the applet side!, and java)net)ServerSoc4et andThreads (on the server side!)

    1) 5an I +et the path of the current servlet where #t l#ves on the f#le s"stem ;not #ts

    (*)

    Try usin:

    reuest)etRealPath(reuest)etServletPath(!!

    *n e#ample may be:

    out)println(reuest)etRealPath(reuest)etServletPath(!!!&

    12) How can I da#s" cha#n servlets to+ether such that the output of one servlet serves asthe #nput to the ne.t

    There are two common methods +or chainin the output o+ one servlet to another

    servlet :

    Z[U the +irst method is the aliasin which describes a series o+ servlets to be e#ecuted

    Z[U the second one is to de+ine a new ;$;"@Type and associate a servlet as handlers

    *s $ don/t really use the second one, $/ll +ocus on the aliasin)

    To chain servlets toether, you have to speci+y a seuential list o+ servlets andassociate it to an alias) ?hen a reuest is made to this alias, the +irst servlet in the

    list is invo4ed, processed its tas4 and sent the ouptut to the ne#t servlet in the list asthe reuest object) The output can be sent aain to another servlets)

    To accomplish this method, you need to con+iure your servlet enine (=Run,=ava?eb server, =Serv )))!)

  • 8/13/2019 Servlets,Struts FAQs(P)

    10/35

    10

    public class srv* e#tends HttpServlet % )))

    public void doGet ()))! % Print?riter out res)et?riter(!&

    rest)setontentType(Jte#tDhtmlJ!& )))

    out)println(JHello hainin servletJ!& '

    '

    *ll the servlet srvF has to do is to open an input stream to the reuest object and

    read the data into a Fu++eredReader object as +or e#ample :

    Fu++eredReader b new Fu++eredReader( new

    $nputStreamReader(re)et$nputStream(! ! !&Strin data b)readine(!&

    b)close(!&

    *+ter that you can +ormat your output with the data)

    $t should wor4 straith+orward with =ava ?eb Server or =serv too) =ust loo4 at intheir documentation to de+ine an alias name) Hope that it/ll help)

    14) 'h" there are no constructors #n servlets

    * servlet is just li4e an applet in the respect that it has an init(! method that acts asa constrcutor) Since the servlet environment ta4es care o+ instantiatin the servlet,

    an e#plicit constructor is not needed) *ny initiali3ation code you need to run shouldbe placed in the init(! method since it ets called when the servlet is +irst loaded by

    the servlet container)

    18) How to handle mult#ple concurrent database re>uests?updates when us#n+ 0@F;S provide the +acility o+ loc4s whenever the data is bein modi+ied) Therecan be two scenarios:

    -) ;ultiple database updates on di++erent rows, i+ you are usin servlets the servlets will

    open multiple connections +or di++erent users) $n this case there is no need to do

    additional prorammin)0) $+ database updates are on the same row then the rows are loc4ed automatically by

    the >F;S, hence we have to send reuests to the >F;S repetitively until the loc4 isreleased by >F;S)

    This issue is dealt with in the =>F documentation& loo4 up JTransactionsJ andJauto@commitJ) $t can et pretty con+usin)

    =9) 'hat #s the d#fference between Gener#cServlet and HttpServlet

  • 8/13/2019 Servlets,Struts FAQs(P)

    11/35

    11

    GenericServlet is +or servlets that miht not use HTTP, li4e +or instance

  • 8/13/2019 Servlets,Struts FAQs(P)

    12/35

    12

    stored in the coo4ieor encoded in 2R (usin A(* rewr#t#n+A! and the coo4iespeci+ication says the si3e o+ coo4ie as well as HTTP reuest (e)) G"T

    Ddocument)html^n! cannot be loner then 64b)

    =) 'hat #s the d#fference between the doGet and doPost methodsdoGet is called in response to an HTTP G"T reuest) This happens when users clic4 on a lin4, or

    enter a 2R into the browser/s address bar) $t also happens with some HT; F drivers were not re@

    entrant) The modern versions o+ =>F drivers should wor4 OI, but there are neverany uarantees)

    2sin connection poolin will avoid the whole issue, plus will lead to improvedper+ormance) See this

  • 8/13/2019 Servlets,Struts FAQs(P)

    13/35

    13

    Strin thisServer etServleton+i(!)etServletonte#t(!)etServer$n+o(!&

    $+ you are usin =SP, you can use this e#pression:

    NL application)etServer$n+o(! L

    !1) How can I +et the absolute (* of a servlet?0SP pa+e at runt#me

    .ou can et all the necessary in+ormation to determine the 2R +rom the reuest object) Toreconstruct the absolute 2R +rom the scheme, server name, port, 2R$ and uery strin you can

    use the 2R class +rom java)net) The +ollowin code +rament will determine your pae/s absolute2R:

    Strin +ile reuest)etReuest2R$(!&i+ (reuest)etueryStrin(! 7 null! %

    +ile M /A/ M reuest)etueryStrin(!&'

    2R reconstructed2R new 2R(reuest)etScheme(!, reuest)etServer5ame(!,

    reuest)etServerPort(!,

    +ile!&out)println(2R)toStrin(!!&

    !=) 'h" do Gener#cServlet and HttpServlet #mplement the Ser#al#%able #nterface

    GenericServlet and HttpServlet implement the Seriali3able inter+ace so that servlet eninescanJhibernateJ the servlet state when the servlet is not in use and re@instance it when needed or to

    duplicate servlet instances +or better load balancin) $ don/t 4now i+ or how current servlet eninesdo this, and it could have serious implications, li4e brea4in re+erences to objects otten in the

    init(! method without the prorammer 4nowin it) Prorammers should be aware o+ this pit+all andimplement servlets which are stateless as possible, deleatin data store to Session objects or to

    the Servletonte#t) $n eneral stateless servlets are better because they scale much better and arecleaner code)

    !!) How does one choose between overr#d#n+ the doGet;), doPost;), and serv#ce;)methodsThe di++erences between the doGet(! and doPost(! methods are that they are called in the

    HttpServlet that your servlet e#tends by its service(! method when it recieves a G"T or a POST

    reuest +rom a HTTP protocol reuest)

    * G"T reuest is a reuest to geta resource +rom the server) This is the case o+ a browser

    reuestin a web pae) $t is also possible to speci+y parameters in the reuest, but thelength of the parameters on the whole is limited) This is the case o+ a +orm in a web pae

    declared this way in html: N+orm methodJG"TJ or N+orm)

    * POST reuest is a reuest topost(to send! +orm data to a resource on the server) This is

    the case o+ o+ a +orm in a web pae declared this way in html: N+orm methodJPOSTJ) $n

    this case the si3e o+ the parameters can be much reater)

    The GenericServlet has a service(! method that ets called when a client reuest is made)

    This means that it ets called by both incomin reuests and the HTTP reuests are iven to

    the servlet as they are (you must do the parsin yoursel+!)

    The HttpServlet instead has doGet(! and doPost(! methods that et called when a clientreuest is G"T or POST) This means that the parsin o+ the reuest is done by the servlet:

    you have the appropriate method called and have convenience methods to read the reuest

    parameters)

    http://void%280%29/http://void%280%29/
  • 8/13/2019 Servlets,Struts FAQs(P)

    14/35

    14

    NT!"the doGet(! and doPost(! methods (as well as other HttpServlet methods! are calledby the service(! method)

    oncludin, i+ you must respond to G"T or POST reuests made by a HTTP protocol client(usually a browser! don/t hesitate to e#tend HttpServlet and use its convenience methods)

    $+ you must respond to reuests made by a client that is not usin the HTTP protocol, youmust use service(!)

    !) How do servlets d#ffer from -I 'hat are the advanta+es and d#sadvanta+es of

    each technolo+"

    Servlets e#tend the server@side +unctionality o+ a website) Servlets communicate with other

    application(s! on that server (or any other server! and per+orm tas4s above and beyond the

    JnormalJ static HT; document) * servlet can receive a reuest to et some in+ormationthrouh "=F +rom one or more databases, then convert this data into a static HT;D?;

    pae +or the client to see, +or e#ample) "ven i+ the servlet tal4s to many other applications

    all over the world to et this in+ormation, it still loo4s li4e it happened at that website)

    R;$ (Remote ;ethod $nvocation! is just that @ a way to invo4e methods on remotemachines) $t is way +or an application to tal4to another remote machine and e#ecutedi++erent methods, all the while appearin as i+ the action was bein per+ormed on the local

    machine)

    Servlets (or =SP! are mainly used +or any web@related activity such as online ban4in, online

    rocery stores, stoc4 tradin, etc) ?ith servlets, you need only to 4now the web addressand the paes displayed to you ta4e care o+ callin the di++erent servlets (or actions within a

    servlet! +or you) 2sin R;$, you must bind the R;$ server to an $P and port, and the clientwho wishes to tal4 to the remote server must 4now this $P and port, unless o+ course you

    used some 4ind o+ in@between loo4up utility, which you could do with (o+ all thins! servlets)

    !/) How can we use a servlet as a pro." for commun#cat#ons between two applets

    One way to accomplish this is to have the applets communicate via TPD$P soc4ets tothe servlet) The servlet would then use a custom protocol to receive and push

    in+ormation between applets) However, this solution does have +irewall problems i+

    the system is to be used over and $nternet verses an $ntranet)

    !) How can I des#+n m" servlet?0SP so that >uer" results +et d#spla"ed on severalpa+es, l#e the results of a search en+#ne Each pa+e should d#spla", sa", 19 records

    each and when the ne.t l#n #s cl#ced, I should see the ne.t?prev#ous 19 records and soonB

    2se a =ava Fean to store the entire result o+ the search that you have +ound) The servlet willthen set a pointer to the +irst line to be displayed in the pae and the number o+ lines todisplay, and +orce a display o+ the pae) The *ction in the +orm would point bac4 to the

    servlet in the =SP pae which would determine whether a ne#t or previous button has beenpressed and reset the pointer to previous pointer M number o+ lines and redisplay the pae)

    The =SP pae would have a scriplet to display data +rom the =ava Fean +rom the startpointer set to the ma#imum number o+ lines with buttons to allow previous or ne#t paes to

    be selected) These buttons would be displayed based on the pae number (i)e) i+ +irst thendon/t display previous button!)

    http://void%280%29/http://void%280%29/
  • 8/13/2019 Servlets,Struts FAQs(P)

    15/35

    15

    !2) How do I deal w#th mult#$valued parameters #n a servlet

    $nstead o+ usin etParameter(! with the ServletReuest, as you would with sinle@valued parameters, use the etParameteralues(! method) This returns a Strin

    array (or null! containin all the values o+ the parameter reuested)

    !4) How can I pass data retr#eved from a database b" a servlet to a 0SP pa+e

    One o+ the better approaches +or passin data retrieved +rom a servlet to a =SP is to

    use the ;odel 0 architecture as shown below:

    Fasically, you need to +irst desin a bean which can act as a wrapper +or storin theresultset returned by the database uery within the servlet) Once the bean has been

    instantiated and initiali3ed by invo4in its setter methods by the servlet, it can be

    placed within the reuest object and +orwarded to a display =SP pae as +ollows:

    com)+oo)dbFean bean new com)+oo)dbFean(!& DDcall setters to initiali3e bean

    re)set*ttribute(JdbFeanJ, bean!& urlJ)))J& DDrelative url +or display jsp pae

    Servletonte#t sc etServletonte#t(!& Reuest>ispatcher rd sc)etReuest>ispatcher(url!&

    rd)+orward(re, res!&

    The bean can then be accessed within the =SP pae via the useFean ta as:

    Njsp:useFean idJdbFeanJ classJcom)+oo)dbFeanJscopeJreuestJD

    )))NL

    DDiterate throuh the rows within dbFean and DDaccess the values usin a scriptlet

    L

    *lso, it is best to desin your application such that you avoid placin beans into the

    session unless absolutely necessary) Placin lare objects within the session imposesa heavy burden on the per+ormance o+ the servlet enine) O+ course, there may be

    additional desin considerations to ta4e care o+ @ especially i+ your servlets arerunnin under a clustered or +ault@tolerant architecture)

    !8) How can I use a servlet to +enerate a s#te us#n+ frames

    $n eneral, loo4 at each +rame as a uniue document capable o+ sendin its own reuests and

    receivin its own responses) .ou can create a top servlet (say,

  • 8/13/2019 Servlets,Struts FAQs(P)

    16/35

    16

    public void doGet(HttpServletReuest reuest, HttpServletResponse response! throws Servlet"#ception,

    $O"#ception %response)setontentType(Jte#tDhtmlJ!&

    Print?riter out new Print?riter (response)et?riter(!!&

    out)println(JNhtmlJ!& out)println(JNhead.our TitleNDheadJ!&

    DD de+ininthe three rows o+ ummyServletAmode+ullname+rm0J!&

    out)println(JN+rame srcDservletsD>ummyServletAmodesmallname+rm1J!& out)println(JND+ramesetJ!&

    out)println(JNbodyJ!&

    out)println(JNDbodyNDhtmlJ!& out)close(!&

    @@@@@@@@@@@@@@@@@@@@@@@@@@ "5> @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

    ?here ;enuServlet and >ummyServlet provide content and behavior +or the +rames

    enerated by uest

    5o) That doesn/t even ma4e sense :@!

    .ou can, however, send a JredirectJ, which tells the user/s browser to send anotherreuest, possibly to the same servlet with di++erent parameters) Search this

  • 8/13/2019 Servlets,Struts FAQs(P)

    17/35

    17

    and sends passwords with base6 encodin, there+ore it is not very secure)(See R

  • 8/13/2019 Servlets,Struts FAQs(P)

    18/35

    18

    $+ the ne#t servlet url is in the same host, then you can use the +orward method)

    Here is an e#ample code about usin +orward:

    U Reuest>ispatcher rd null&U Strin taret2R JtaretservletnameJ&

    U Servletonte#t ct# this)etServletonte#t(!&

    U rd ct#)etReuest>ispatcher(taret2R!&U rd)+orward(reuest, response!&

    /) How can the data w#th#n an HT-* form be refreshed automat#call" whenever there #sa chan+e #n the database

    =SP is intended +or dynamically eneratin paes) The enerated paes can include

    wml, html, dhtml or whatever you want)))

    ?hen you have a enerated pae, =SP has already made its wor4) F) This way you can load new in+ormation insidethe applet or try to +orce a pae reload)

    XThat/s a nice idea @@ it could use the show>ocument(! call to reload the current

    pae) $t could also use HTTP pollin instead o+ maintainin an e#pensive soc4etconnection) @*le#

    Perhaps (i+ possible!, could be simpler usin an automatic =avaScript re+reshin

    +unction that +orce pae reload a+ter a speci+ied time interval)

    //) 'hat #s a web appl#cat#on ;or AwebappA)

    * web application is a collection o+ servlets, html paes, classes, and other resources that

    can be bundled and run on multiple containers +rom multiple vendors) * web application isrooted at a speci+ic path within a web server)

  • 8/13/2019 Servlets,Struts FAQs(P)

    19/35

    19

    .ou can use Njsp:+orward paeJDrelativepathD.ourServletJ D orresponse)sendRedirect(Jhttp:DDpathD.ourServletJ!)

    ariables can be sent as:

    Njsp:+orward paeDrelativepathD.ourServlet

    Njsp:param nameJname-J valueJvalue-J DNjsp:param nameJname0J valueJvalue0J D

    NDjsp:+orward

    .ou may also pass parameters to your servlet by speci+yin

    response)sendRedirect(Jhttp:DDpathD.ourServletAparam-val-J!)

    /2) 5an there be more than one #nstance of a servlet at one t#me

    It is important to note that there can be more than one instance of a given (ervletclass in the servlet container. 1or example, this can occur where there was more

    than one servlet definition that utili2ed a specific servlet class with differentinitiali2ation parameters. This can also occur when a servlet implements the

    (ingleThread3odel interface and the container creates a pool of servlet instances touse.

    /8) 'hat #s #nter$servlet commun#cat#on

    *s the name says it, it is communication between servlets) Servlets tal4in to each

    other) XThere are many ways to communicate between servlets, includin

    U Reuest >ispatchin

    U HTTP Redirect

    U Servlet hainin

    U HTTP reuest (usin soc4ets or the 2Ronnection class!

    U Shared session, reuest, or application objects (beans!

    U >irect method invocation (deprecated!

    U Shared static or instance variables (deprecated!

    Search the ispatchin!+orin+ormation on each o+ these techniues) @*le#

    Fasically interServlet communication is acheived throuh servlet chainin) ?hich is aprocess in which you pass the output o+ one servlet as the input to other) These

    servlets should be runnin in the same server)

    http://www.jguru.com/jguru/faq/faqindex.jsp?title=FAQ+Entries+in+Topic+Java%3AAPI%3AServlets%3AMessage+Passing+(including+Request+Dispatching)&topic=52022http://www.jguru.com/jguru/faq/faqindex.jsp?title=FAQ+Entries+in+Topic+Java%3AAPI%3AServlets%3AMessage+Passing+(including+Request+Dispatching)&topic=52022
  • 8/13/2019 Servlets,Struts FAQs(P)

    20/35

  • 8/13/2019 Servlets,Struts FAQs(P)

    21/35

  • 8/13/2019 Servlets,Struts FAQs(P)

    22/35

    22

    .ou don/t have to do anythin special to include =avaScript in servlets or =SP paes) =ust have theservletD=SP pae enerate the necessary =avaScript code, just li4e you would include it in a raw

    HT; pae)

    The 4ey thin to remember is it won/t run in the server) $t will run bac4 on the client when

    the browser loads the enerate HT;, with the included =avaScript)

    4) How can I mae a POST re>uest throu+h responseBsended#rect;) or

    responseBsetStatus;) and responseBsetHeader;) methods

    .ou can/t) $t/s a +undamental limitation o+ the HTTP protocol) .ou/ll have to +iure out some other

    way to pass the data, such as

    U 2se G"T instead

    U ;a4e the POST +rom your servlet, not +rom the client

    U Store data in coo4ies instead o+ passin it via G"TDPOST

    42) How do I pass a re>uest ob7ect of one servlet as a re>uest ob7ect to another servlet

    2se a Reuest >ispatcher)

    44) I call a servlet as the act#on #n a form, from a 7spB How can I red#rectthe responsefrom the servlet, bac to the 0SP ;e>uest@#spatcherBforward w#ll not help #n th#s case,

    as I do not now wh#ch resource has made the re>uestB re>uestB+ete>uest(I w#ll

    return the ur# as conta#ned #n the act#on ta+ of the form, wh#ch #s not what #s neededB)

    .ou/ll have to pass the =SP/s 2R$ in to the servlet, and have the servlet callsendRedirect to o bac4 to the =SP)

  • 8/13/2019 Servlets,Struts FAQs(P)

    23/35

    23

    et$nitParameteret$nitParameter5ames

    etServletonte#tetServlet5ame

    .ou can use the methods to determine the Servlet/s initiali3ation parameters, the

    name o+ the servlets instance, and a re+erence to the Servlet onte#t the servlet isrunnin in)

    etServletonte#t is the most valuable method, as it allows you to share in+ormationaccross an application (conte#t!)

    Struts :

    D1: 'hat #s 6ct#onServlet*: The class or)apache)struts)action)*ctionServlet is the called the *ctionServlet) $n the =a4arta

    Struts e+initions +ile are simple )properties +iles and these +iles contains the

    messaes that can be used in the struts project) ;essae Resources >e+initions +iles can be addedto the struts@con+i)#ml +ile throuh messa+e$resources ?Fta)

    E.ample:Nmessae@resources parameterJ;essaeResourcesJ D

    D!: 'hat #s 6ct#on 5lass

    6: The *ction is part o+ the controller) The purpose o+ *ction lass is to translate the

    HttpServletReuest to the business loic) To use the *ction, we need to Subclass and overwrite thee#ecute(! method) The *ctionServlet (commad! passes the parameteri3ed class to *ction

  • 8/13/2019 Servlets,Struts FAQs(P)

    24/35

    24

    % publ#c *ctionavid ?inter+eldt as third@party add@on to Struts) 5ow

    the alidator +ramewor4 is a part o+ =a4arta ommons project and it can be used with or without

    Struts) The alidator +ramewor4 comes interated with the Struts

  • 8/13/2019 Servlets,Struts FAQs(P)

    25/35

    25

    The controller is implemented by a java servlet& this servlet is centrali3ed point o+ control +or the

    web application) $n struts +ramewor4 the controller responsibilities are implemented by several

    di++erent components li4e

    The 6ct#onServlet 5lass

    The e>uestProcessor 5lassThe 6ct#on 5lass

    The *ctionServlet e#tends the7ava.BservletBhttpBhttpServletclass) The *ctionServlet class is

    not abstract and there+ore can be used as a concrete controller by your application)

    The controller is implemented by the *ctionServlet class) *ll incomin reuests are mapped to the

    central controller in the deployment descriptor as +ollows)

    Nservlet

    Nservlet@nameactionNDservlet@name

    Nservlet@classor)apache)struts)action)*ctionServletNDservlet@class

    NDservlet

    *ll reuest 2R$s with the pattern _)do are mapped to this servlet in the deployment descriptor as

    +ollows)

    Nservlet@mappin

    Nservlet@nameactionNDservlet@name

    Nurl@pattern_)doNDurl@pattern

    Nurl@pattern_)doNDurl@pattern

    * reuest 2R$ that matches this pattern will have the +ollowin +orm)

    http:DDwww)mysitename)comDmyconte#tDaction5ame)do

    The precedin mappin is called e#tension mappin, however, you can also speci+y path mappinwhere a pattern ends with D_ as shown below)

    Nservlet@mappin

    Nservlet@nameactionNDservlet@name

    Nurl@patternDdoD_NDurl@pattern

    Nurl@pattern_)doNDurl@pattern

    * reuest 2R$ that matches this pattern will have the +ollowin +orm)

    http:DDwww)mysitename)comDmyconte#tDdoDaction5ame

    The class or+BapacheBstrutsBact#onBre>uestProcessorprocess the reuest +rom the controller)

    .ou can sublass the ReuestProcessor with your own version and modi+y how the reuest is

    processed)

    Once the controller receives a client reuest, it deleates the handlin o+ the reuest to a helper

    class) This helper 4nows how to e#ecute the business operation associated with the reuested

    action) $n the Struts +ramewor4 this helper class is descended o+ or)apache)struts)action)*ction

    class) $t acts as a bride between a client@side user action and business operation) The *ction class

    decouples the client reuest +rom the business model) This decouplin allows +or more than one@to@

    http://www.my_site_name.com/mycontext/do/action_Namehttp://www.my_site_name.com/mycontext/do/action_Name
  • 8/13/2019 Servlets,Struts FAQs(P)

    26/35

    26

    one mappin between the user reuest and an action) The *ction class also can per+orm other

    +unctions such as author#%at#on, lo++#n+be+ore invo4in business operation) The Struts *ction

    class contains several methods, but most important method is the e#ecute(! method)

    public *ction

  • 8/13/2019 Servlets,Struts FAQs(P)

    27/35

    27

    N+orward nameJSuccessJ pathJDactionDsomejsp)jspJ D

    N+orward nameJuest@#spatcher

    >e+ines an object that receives reuests +rom the client and sends them to any resource (such as a

    servlet, HT; +ile, or =SP +ile! on the server) The servlet container creates the Reuest>ispatcher

    object, which is used as a wrapper around a server resource located at a particular path or iven

    by a particular name)

    This inter+ace is intended to wrap servlets, but a servlet container can create Reuest>ispatcher

    objects to wrap any type o+ resource)

    +ete>uest@#spatcher

    public Reuest>ispatcher etReuest>ispatcher(java)lan)Strin path!

    Returns a Reuest>ispatcher object that acts as a wrapper +or the resource located at the iven

    path) * Reuest>ispatcher object can be used to +orward a reuest to the resource or to include

    the resource in a response) The resource can be dynamic or static)

    The pathname must bein with a JDJ and is interpreted as relative to the current conte#t root) 2se

    etonte#t to obtain a Reuest>ispatcher +or resources in +orein conte#ts) This method returns

    null i+ the Servletonte#t cannot return a Reuest>ispatcher)

    Parameters:

    path $ a Str#n+ spec#f"#n+ the pathname to the resource

    eturns:

    a e>uest@#spatcher ob7ect that acts as a wrapper for the resource at the spec#f#edpath

    See 6lso:

    e>uest@#spatcher, +et5onte.t;7avaBlan+BStr#n+)

    et5amed>ispatcher

    public Reuest>ispatcher et5amed>ispatcher(java)lan)Strin name!

    Returns a Reuest>ispatcher object that acts as a wrapper +or the named servlet)

    Servlets (and =SP paes also! may be iven names via server administration or via a web

    application deployment descriptor) * servlet instance can determine its name usinServleton+i)etServlet5ame(!)

    This method returns null i+ the Servletonte#t cannot return a Reuest>ispatcher +or any reason)

    Parameters:

    name @ a Strin speci+yin the name o+ a servlet to wrap

    Returns:

    a Reuest>ispatcher object that acts as a wrapper +or the named servlet

  • 8/13/2019 Servlets,Struts FAQs(P)

    28/35

    28

    See *lso:

    Reuest>ispatcher, etonte#t(java)lan)Strin!, Servleton+i)etServlet5ame(!

    Duest#on11: 'h" cant we overr#de create method #n StatelessSess#on

  • 8/13/2019 Servlets,Struts FAQs(P)

    29/35

    29

    the struts applications)

    The +ile validation)#ml is used to declare sets o+ validations that should be applied to

  • 8/13/2019 Servlets,Struts FAQs(P)

    30/35

    30

    Strin dispatch myispatch(!&i+ (JcreateJ)euals(dispatch!! % )))

    i+ (JsaveJ)euals(dispatch!! % )))

    The Struts >ispatch *ction Xor)apache)struts)actions is desined to do e#actly the same thin,

    but without messy branchin loic) The base per+orm method will chec4 a dispatch +ield +or you,

    and invo4e the indicated method) The only catch is that the dispatch methods must use the samesinature as per+orm) This is a very modest reuirement, since in practice you usually end up dointhat anyway)

    To convert an *ction that was switchin on a dispatch +ield to a >ispatch*ction, you simply need to

    create methods li4e this

    public *ction

  • 8/13/2019 Servlets,Struts FAQs(P)

    31/35

    31

    .ou can, but the value o+ the button is also its label) This means i+ the pae desiners want to labelthe button somethin di++erent, they have to coordinate the *ction prorammer) ocali3ation

    becomes virtually impossible) (Source: http:DDhusted)comDstrutsDtipsD]]0)html!)

    Duest#on14: How Struts relates to 0=EE

    6nswer: Struts +ramewor4 is built on =0"" technoloies (=SP, Servlet, Talibs!, but it is itsel+ notpart o+ the =0"" standard)

    Duest#on 18: 'hat #s struts act#ons and act#on mapp#n+s

    6nswer: * Struts action is an instance o+ a subclass o+ an *ction class, which implements a portion

    o+ a ?eb application and whose per+orm or e#ecute method returns a +orward)

    *n action can per+orm tas4s such as validatin a user name and password)

    *n action mappin is a con+iuration +ile entry that, in eneral, associates an action name with an

    action) *n action mappin can contain a re+erence to a +orm bean that the action can use, and canadditionally de+ine a list o+ local +orwards that is visible only to this action)

    *n action servlet is a servlet that is started by the servlet container o+ a ?eb server to process a

    reuest that invo4es an action) The servlet receives a +orward +rom the action and as4s the servlet

    container to pass the reuest to the +orward/s 2R) *n action servlet must be an instance o+ an

    or)apache)struts)action)*ctionServlet class or o+ a subclass o+ that class) *n action servlet is the

    primary component o+ the controller)

    Duest#on =9: 5an I setup 6pache Struts to use mult#ple conf#+urat#on f#les

    6nswer:.es Struts can use multiple con+iuration +iles) Here is the con+iuration e#ample:

    Nservlet Nservlet@nameban4inNDservlet@name

    Nservlet@classor)apache)struts)action)*ctionServlet

    NDservlet@class

    Ninit@param

    Nparam@namecon+iNDparam@name

    param$valueF?'E

  • 8/13/2019 Servlets,Struts FAQs(P)

    32/35

    32

    b) Harder to learnStruts are harder to learn, benchmar4 and optimi3e)

    Duest#on==: 'hat #s Struts Clow

    6nswer:Struts ispatch*ction)html!)

    Duest#on=/: 'hat are the components of Struts6nswer:Struts is based on the ; desin pattern) Struts components can be cateories into

    -odel, #ewand 5ontroller)

    -odel: omponents li4e business loic D business processes and data are the part o+ ;odel)

    #ew:=SP, HT; etc) are part o+ iew

    5ontroller:*ction Servlet o+ Struts is part o+ ontroller components which wor4s as +rontcontroller to handle all the reuests)

    Duest#on=: 'hat are Ta+ *#brar#es prov#ded w#th Struts

    6nswer:Struts provides a number o+ ta libraries that helps to create view components easily)These ta libraries are:

    a)

  • 8/13/2019 Servlets,Struts FAQs(P)

    33/35

    33

    6ct#onErrors:* class that encapsulates the error messaes bein reported by the validate(!method o+ an *ctionuplicate2ser"#ceptionJD

    b) Pro+rammat#c E.cept#on Handl#n+:Here you can use try%'catch%' bloc4 to handle thee#ception)

    Duest#on!9: 'hat do "ou understand b" 0SP 6ct#ons6nswer:=SP actions are Y; tas that direct the server to use e#istin components or control the

    behavior o+ the =SP enine) =SP *ctions consist o+ a typical (Y;@based! pre+i# o+ JjspJ +ollowed bya colon, +ollowed by the action name +ollowed by one or more attribute parameters)

    There are si# =SP *ctions:

    Njsp:includeD

    Njsp:+orwardD

    Njsp:pluinD

    Njsp:usebeanD

    Njsp:setPropertyD

    Njsp:etPropertyD

    8B 'hat #s d#fference between 0=EE 1B! and 0=EE 1B

    =0"" -)6 is an enhancement version o+ =0"" -)1) $t is the most complete Web services

    plat+orm ever)

    =0"" -)6 includes:

    http://void%280%29/http://void%280%29/
  • 8/13/2019 Servlets,Struts FAQs(P)

    34/35

    34

    o =ava *P$ +or Y;@Fased RP (=*Y@RP -)-!

    o SO*P with *ttachments *P$ +or =ava (S**=!,

    o ?eb Services +or =0""(=SR E0-!

    o =0"" ;anaement ;odel(-)]!

    o =0"" >eployment *P$(-)-!

    o =ava ;anaement "#tensions (=;Y!,

    o =ava *uthori3ation ontract +or ontainers(=ava*!

    o =ava *P$ +or Y; Reistries (=*YR!

    o Servlet 0)6

    o =SP 0)]

    o "=F 0)-

    o =;S -)-

    o =0"" onnector -)8

    The =0"" -)6 +eatures complete ?eb services support throuh the new =*Y@RP -)- *P$,

    which supports service endpoints based on Servlets and enterprise beans) =*Y@RP -)-provides interoperability with ?eb services based on the ?S> and SO*P protocols)

    The =0"" -)6 plat+orm also supports the ?eb Services +or =0"" speci+ication (=SR E0-!,which de+ines deployment reuirements +or ?eb services and utili3es the =*Y@RP

    prorammin model)

    $n addition to numerous ?eb services *P$s, =0"" -)6 plat+orm also +eatures support +or the

    ?S@$ Fasic Pro+ile -)]) This means that in addition to plat+orm independence and complete?eb services support, =0"" -)6 o++ers plat+orm ?eb services interoperability)

    The =0"" -)6 plat+orm also introduces the =0"" ;anaement -)] *P$, which de+ines thein+ormation model +or =0"" manaement, includin the standard ;anaement "=F (;"=F!)

    The =0"" ;anaement -)] *P$ uses the =ava ;anaement "#tensions *P$ (=;Y!)

    The =0"" -)6 plat+orm also introduces the =0"" >eployment -)- *P$, which provides a

    standard *P$ +or deployment o+ =0"" applications)

    The =0"" -)6 plat+orm includes security enhancements via the introduction o+ the =ava

    *uthori3ation ontract +or ontainers (=ava*!) The =ava* *P$ improves security bystandardi3in how authentication mechanisms are interated into =0"" containers)

  • 8/13/2019 Servlets,Struts FAQs(P)

    35/35

    35

    The =0"" plat+orm now ma4es it easier to develop web +ront ends with enhancements to=ava Servlet and =avaServer Paes (=SP! technoloies) Servlets now support reuest

    listeners and enhanced +ilters) =SP technoloy has simpli+ied the pae and e#tensiondevelopment models with the introduction o+ a simple e#pression lanuae, ta +iles, and a

    simpler ta e#tension *P$, amon other +eatures) This ma4es it easier than ever +ordevelopers to build =SP@enabled paes, especially those who are +amiliar with scripting

    languages)

    Other enhancements to the =0"" plat+orm include the =0"" onnector *rchitecture, which

    provides incomin resource adapter and =ava ;essae Service (=;S! plu ability) 5ew+eatures in "nterprise =avaFeans ("=F! technoloy include ?eb service endpoints, a timer

    service, and enhancements to "=F and messae@driven beans)

    The =0"" -)6 plat+orm also includes enhancements to deployment descriptors) They are

    now de+ined usin Y; Schema which can also be used by developers to validate their Y;structures)

    5ote: The above in+ormation comes +rom S25 released notes)

    http://void%280%29/http://void%280%29/http://void%280%29/http://void%280%29/

Recommended