You are on page 1of 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 doPost method: public void doGet(HttpServletRe uest 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 sin,le thread, and the web server will wait until that thread e#its be+ore sendin, any more threads into your service(! method) "very new client re uest ,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!) 2nder most circumstances, there is only one instance o+ your servlet, no matter how many client re uests 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 be care+ul to s"nchron#%e access to shared data (instance variables! usin, the synchroni3ed 4eyword) (5ote that the server will also allocate a new instance i+ you re,ister the servlet 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)! * 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)

0)

1)

8)

2
:) $+ you absolutely can/t deal with synchroni3in,, you can declare that your servlet 9amp& uot&implements Sin,leThread;odel9amp& uot&) This empty inter+ace tells the web server to only send one client re uest at a time into your servlet) <rom the =ava>oc: &amp;quot;If the target servlet is flagged with this interface, the servlet programmer is guaranteed that no two threads will execute concurrently the service method of that servlet. This guarantee is ensured by maintaining a pool of servlet instances for each such servlet, and dispatching each service call to a free servlet. In essence, if the servlet implements this interface, the servlet will be thread safe.&amp;quot; 5ote that 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 across instances than within a sin,le instance) See also ?hat/s a better approach +or enablin, thread@sa+e servlets and =SPsA Sin,leThread;odel $nter+ace or Synchroni3ationA B) To share data across successive or concurrent re uests, you can use either instance variables or class@static variables, or use Session Trac4in,) The destroy(! method is not necessarily as clean as the init(! method) The server calls destroy e#ther a+ter all service calls have been completed, or a+ter a certain number o+ seconds have passed, whichever comes +irst) This means that other threads mi,ht be runnin, service re uests at the same time as your destroy(! method is called7 So be sure to synchroni3e, andDor wait +or the other re uests to uit) Sun/s Servlet Tutorial has an e#ample o+ how to do this with re+erence countin,) destroy(! cannot throw an e#ception, so i+ somethin, bad happens, call lo,(! with a help+ul messa,e (li4e the e#ception!) See the 9amp& uot&closin, a =>FG connection9amp& uot& e#ample in Sun/s Tutorial)

C)

E)

&) '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 GG$ +orm so it is +it +or travel across the networ4 @@ basically, strippin, spaces and punctuation and replacin, with escape characters) 2RH >ecodin, is the reverse process) To per+orm these operations, call java)net)2RH"ncoder)encode(! and java)net)2RH>ecoder)decode(! (the latter was (+inally7! added to =>I -)0, a4a =ava 0!) E.ample: chan,in, J?e/re K-7J into J?eL0BreML01-L0-J ()* )ewr#t#n+ is a techni ue +or savin, state in+ormation on the user/s browser between pa,e hits) $t/s sort o+ li4e coo4ies, only the in+ormation ,ets stored inside the 2RH, as an additional parameter) The HttpSession *P$, which is part o+ the Servlet *P$, sometimes uses 2RH Rewritin, when coo4ies are unavailable) E.ample: chan,in, N* HR"<OJne#tpa,e)htmlJP into N* HR"<OJne#tpa,e)html&QsessionidQO>S=<S>I<SH><""IO"JP (or whatever the actual synta# is& $ +or,et o++hand! (2n+ortunately, the method in the Servlet *P$ +or doin, 2RH rewritin, +or session mana,ement is called encode2RH(!) Si,h)))!

3
There/s also a +eature o+ the *pache web server called 2RH Rewritin,& it is enabled by the modRrewrite module) $t rewrites 2RHs on their way #n to the server, allowin, you to do thin,s li4e automatically add a trailin, slash to a directory name, or to map old +ile names to new +ile names) This has nothin, to do with servlets) <or more in+ormation, see the *pache <*S (http:DDwww)apache)or,DdocsDmiscD<*S)htmlKrewrite@more@con+i,! ) /) How do I upload a f#le to m" servlet or 0SP

On the client side, the client/s browser must support +orm@based upload) ;ost modern browsers do, but there/s no ,uarantee) <or e#ample, N<OR; "5GT.P"O/multipartD+orm@data/ methodO/POST/ actionO/Dmyservlet/P N$5P2T T.P"O/+ile/ 5*;"O/mptest/P N$5P2T T.P"O/submit/ T*H2"O/upload/P ND<OR;P The input type 9amp& uot&+ile9amp& uot& brin,s up a button +or a +ile select bo# on the browser to,ether with a te#t +ield that ta4es the +ile name once selected) The servlet can use the G"T method parameters to decide what to do with the upload while the POST body o+ the re uest contains the +ile data to parse) ?hen the user clic4s the J2ploadJ button, the client browser locates the local +ile and sends it usin, HTTP POST, encoded usin, the ;$;"@type multipartD+orm@data) ?hen it reaches your servlet, your servlet must process the POST data in order to e#tract the encoded +ile) .ou can learn all about this +ormat in R<G -C:B) 2n+ortunately, there is no method in the Servlet *P$ to do this) <ortunately, there are a number o+ libraries available that do) Some o+ these assume that you will be writin, the +ile to dis4& others return the data as an $nputStream) U =ason Hunter/s ;ultipartRe uest (available +rom http:DDwww)servlets)comD! *pache =a4arta Gommons 2pload (pac4a,e or,)apache)commons)upload! Jma4es it easy to add robust, hi,h@per+ormance, +ile upload capability to your servlets and web applicationsJ GParseR<G-C:B (available +rom http:DDwww)servletcentral)comD!) Http;ultiPartParser by *nil Hemrajani, at the isavvi# Gode "#chan,e There is a multipartD+orm parser availailable +rom *nders Iristensen (http:DDwww@u4)hpl)hp)comDpeopleDa4DjavaD, a4Vhplb)hpl)hp)com! at http:DDwww@u4)hpl)hp)comDpeopleDa4DjavaDKutils) =ava;ail also has ;$;"@parsin, routines (see the Purple Servlet Re+erences!)

U U U

4
U =un $namori has written a class called or,)apache)tomcat)re uest)Parse;ime which is available in the Tomcat GTS tree) =SPSmart has a +ree set o+ =SP +or doin, +ile upload and download) 2ploadFean by =avaWoom claims to handle most o+ the hassle o+ uploadin, +or you, includin, writin, to dis4 or memory) There/s an 2pload Ta, in dot=

U U

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, on your 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:<iles Topic +or in+ormation on writin, +iles +rom a Servlet) Please note that you can/t access a +ile on the client system directly +rom a servlet& that would be a hu,e security hole) .ou have to as4 the user +or permission, and currently +orm@based upload is the only way to do that) 1) How does a servlet commun#cate w#th a 0SP pa+e

The +ollowin, code snippet shows how a servlet instantiates a bean and initiali3es it with <OR; data posted by a browser) The bean is then placed into the re uest, and the call is then +orwarded to the =SP pa,e, Fean-)jsp, by means o+ a re uest dispatcher +or downstream processin,) public void doPost (HttpServletRe uest re uest, HttpServletResponse response! % try % ,ovi)<ormFean + O new ,ovi)<ormFean(!& Strin, id O re uest),etParameter(JidJ!& +)set5ame(re uest),etParameter(JnameJ!!& +)set*ddr(re uest),etParameter(JaddrJ!!& +)set*,e(re uest),etParameter(Ja,eJ!!& DDuse the id to compute DDadditional bean properties li4e in+o DDmaybe per+orm a db uery, etc) DD ) ) ) +)setPersonali3ation$n+o(in+o!& re uest)set*ttribute(J+FeanJ,+!& ,etServletGon+i,(!),etServletGonte#t(!),etRe uest>ispatcher (JDjspDFean-)jspJ!)+orward(re uest, response!& ' catch ("#ception e#! % ))) '

'

The =SP pa,e Fean-)jsp can then process +Fean, a+ter +irst e#tractin, it +rom the de+ault re uest scope via the useFean action)

5
Njsp:useFean idOJ+FeanJ classOJ,ovi)<ormFeanJ scopeOJre uestJDP Njsp:,etProperty nameOJ+FeanJ propertyOJnameJ DP Njsp:,etProperty nameOJ+FeanJ propertyOJaddrJ DP Njsp:,etProperty nameOJ+FeanJ propertyOJa,eJ DP Njsp:,etProperty nameOJ+FeanJ propertyOJpersonali3ation$n+oJ DP 2) 'hat3s a better approach for enabl#n+ thread$safe servlets and 0SPs S#n+leThread-odel Interface or S"nchron#%at#on *lthou,h the Sin,leThread;odel techni ue is easy to use, and wor4s well +or low volume sites, it does not scale well) $+ you anticipate your users to increase in the +uture, you may be better o++ implementin, e#plicit synchroni3ation +or your shared data) The 4ey however, is to e++ectively minimi3e the amount o+ code that is synchron3ied so that you ta4e ma#imum advanta,e o+ multithreadin,) *lso, note that Sin,leThread;odel is pretty resource intensive +rom the server/s perspective) The most serious issue however is when the number o+ concurrent re uests e#haust the servlet instance pool) $n that case, all the unserviced re uests are ueued until somethin, becomes +ree @ which results in poor per+ormance) Since the usa,e is non@deterministic, it may not help much even i+ you did add more memory and increased the si3e o+ the instance pool) 4) 5an a servlet ma#nta#n a 0T6 (serTransact#on ob7ect across mult#ple servlet #nvocat#ons

5o) * =T* transaction must start and +inish within a sin,le invocation (o+ the service(! method!) 5ote that this uestion does not address servlets that maintain and manipulate =>FG connections, includin, a connection/s transaction handlin,) 8) How does the performance of 0SP pa+es compare w#th that of servlets How does #t compare w#th Perl scr#pts

The per+ormance o+ =SP pa,es is very close to that o+ servlets) However, users may e#perience a perceptible delay when a =SP pa,e is accessed +or the very +irst time) This is because the =SP pa,e under,oes a Jtranslation phaseJ wherein it is converted into a servlet by the =SP en,ine) Once this servlet is dynamically compiled and loaded into memory, it +ollows the servlet li+e cycle +or re uest processin,) Here, the jsp$nit(! method is automatically invo4ed by the =SP en,ine upon loadin, the servlet, +ollowed by the RjspService(! method, which is responsible +or re uest processin, and replyin, to the client) >o note that the li+etime o+ this servlet is non@ deterministic @ it may be removed +rom memory at any time by the =SP en,ine +or resource@related reasons) ?hen this happens, the =SP en,ine automatically invo4es the jsp>estroy(! method allowin, the servlet to +ree any previously allocated resources) Subse uent client re uests to the =SP pa,e do not result in a repeat o+ the translation phase as lon, as the servlet is cached in memory, and are directly

6
handled by the servlet/s service(! method in a concurrent +ashion (i)e) the service(! method handles each client re uest within a seperate thread concurrently)! There have been some recent studies contrastin, the per+ormance o+ servlets with Perl scripts runnin, 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 U U U use a Re uest>ispatcher use a 2RHGonnection or HTTPGlient send a redirect call ,etServletGonte#t(!),etServlet(name! (deprecated, doesn/t wor4 in 0)-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 re uest, you could use the Re uest>ispatcher object) $+, however, you want to ,ain access to the instance o+ the servlet that has been loaded into memory by the servlet en,ine, you have to 4now the alias o+ the servlet) (How it is de+ined depends on the en,ine)! <or e#ample, to invo4e a servlet in =S>I a servlet can be named by the property myname)codeOcom)sameer)servlets);yServlet The code below shows how this named servlet can be accessed in the service method o+ another servlet public void service (HttpServletRe uest re uest, HttpServletResponse response! throws Servlet"#ception, $O"#ception % ))) ;yServlet msO(;yServlet! ,etServletGon+i,(!),etServletGonte#t(!),etServlet(JmynameJ!& ))) '

7
That said, This whole apporach o+ accessin, servlets in another servlets has been deprecated 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 use the Re uest>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 re uest 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+orm a speci+ic tas4) Startin, at the basic level, a user is typically submittin, a re uest to a system throu,h a web browser) (?e are conveniently i,norin, all other types o+ clients (R;$, GORF*, GO;D>GO;, Gustom, etc))! +or the time bein, +or purposes o+ clarity)! The web re uest must be received by a 'eb Server (otherwise 4nown as an HTTP Server! o+ some sort) This web server must handle standard HTTP re uests and responses, typically returnin, HT;H to the callin, user) Gode that e#ecutes within the server environment may be GG$ driven, Servlets, *SP, or some other server@side pro,rammin, lan,ua,e, but the end result is that the web server will pass bac4 HT;H to the user) The web server may need to e#ecute an application in response to the users re uest) $t may be ,eneratin, a list o+ news items, or handlin, a +orm submission to a ,uest boo4) $+ 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 web server, this en,ine may be internal, e#ternal, or a completely di++erent product) This en,ine is continually runnin,, unli4e a traditional GG$ environment where a GG$ script is started upon each re uest to the server) This persistance ,ives a servlet connection and thread poolin,, as well as an easy way to maintain state between each HTTP re uest) =SP pa,es are usually tied in with the servlet en,ine, and would e#ecute within the same spaceDapplication as the servlets) There are many products that handle the web servin, and the servlet en,ine in di++erent manners) 5etscapeDiPlanet "nterprise Server builds the servlet en,ine directly into the web server and runs within the same process space) *pache re uires that a servlet en,ine run in an e#ternal process, and will communicate to the en,ine via TGPD$P soc4ets) Other servers, such as ;S $$S don/t o++icially support servlets, and re uire add@on products to add that capability) ?hen you move on to "nterprise =avaFeans (and other =0"" components li4e =;S and GORF*! you move into the application server space) *n 6ppl#cat#on Server is any server that supplies additional +unctionality related to enterprise computin, @@ +or instance, load balancin,, database access classes, transaction processin,, messa,in,, and so on) E0< 6ppl#cat#on Servers provide an "=F container, which is the environment that beans will e#ecute in, and this container will mana,e transactions, thread pools, and other issues as necessary) These application servers are usually stand@alone products, and developers would tie their servletsD=SP pa,es to the "=F components via remote object access *P$s) >ependin, on the application server, pro,rammers

8
may use GORF* 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 providers include some or all o+ these components in their product) $+ you loo4 at ?ebHo,ic (http:DDwww)beasys)comD! you will +ind that ?ebHo,ic contains a web server, servlet en,ine, =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 mana,eDserve "=F instances, while dedicated web servers handle the speci+ic HTTP re uests) 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 do somethin, re,ardless o+ whether the re uest is e),), a POST or a G"T, create a helper method and call that at the be,innin, 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)HttpSessionFindin,Histener) Greate a SessionTimeout5oti+ier object and add it to the user session) ?hen the session is removed, SessionTimeout5oti+ier)value2nbound(! will be called by the servlet en,ine) .ou can implement value2nbound(! to do whatever you want) 1&) 'h" use 0SP when we can do the same th#n+ w#th servlets

XOri,inal uestion: ?hy should $ use =SP when there is already servlet technolo,y 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@side processin,, and, with their si,ni+icant installed base, are here to stay) $n +act, architecturally spea4in,, you can view =SP as a hi,h@level abstraction o+ servlets that is implemented as an e#tension o+ the Servlet 0)- *P$) Still, you shouldn/t use servlets indiscriminately& they may not be appropriate +or everyone) <or instance, while pa,e desi,ners can easily write a =SP pa,e usin, conventional HT;H or Y;H tools, servlets are more suited +or bac4@end developers because they are o+ten written usin, an $>" @@ a process that ,enerally re uires a hi,her level o+ pro,rammin, e#pertise) ?hen deployin, servlets, even developers have to be care+ul and ensure that there is no ti,ht couplin, between presentation and content) .ou can usually do this by addin, a third@party HT;H wrapper pac4a,e li4e htmlIona to the mi#) Fut even this approach, thou,h providin, some +le#ibility with simple screen chan,es, still does not shield you +rom a chan,e in the presentation +ormat itsel+) <or e#ample, i+ your presentation chan,ed +rom HT;H to >HT;H, you would still need to ensure that wrapper pac4a,es were compliant with the new +ormat) $n a worst@case scenario, i+ a wrapper pac4a,e is not available, you may end up hardcodin, the presentation within the dynamic content) So, what is the solutionA One approach would be to use both =SP and servlet technolo,ies +or buildin, application systems)

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)2RH class, or Jroll your ownJ usin, java)net)Soc4et) See the HTTP spec at ?1G +or more detail) 5ote: The servlet cannot initiate this connection7 $+ the servlet needs to asynchronously send a messa,e to the applet, then you must open up a persistent soc4et usin, java)net)Soc4et (on the applet side!, and java)net)ServerSoc4et and Threads (on the server side!) 11) 5an I +et the path of the current servlet where #t l#ves on the f#le s"stem ;not #ts ()*)

Try usin,: re uest),etRealPath(re uest),etServletPath(!! *n e#ample may be: out)println(re uest),etRealPath(re uest),etServletPath(!!!& 12) How can I da#s" cha#n servlets to+ether such that the output of one servlet serves as the #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 to,ether, you have to speci+y a se uential list o+ servlets and associate it to an alias) ?hen a re uest 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 as the re uest object) The output can be sent a,ain to another servlets) To accomplish this method, you need to con+i,ure your servlet en,ine (=Run, =ava?eb server, =Serv )))!) <or e#ample to con+i,ure =Run +or servlet chainin,, you select the =S" service (=Run servlet en,ine! to access to the =S" Service Gon+i, panel) .ou have just to de+ine a new mappin, rule where you de+ine your chainin, servlet) Het say DservletsDchainServlet +or the virtual path and a comma separated list o+ servlets as srv*,srvF) So when you invo4e a re uest li4e http:DDlocalhostDservletsDchainServlet, internally the servlet srv* will be invo4ed +irst and its results will be piped into the servlet srvF) The srv* servlet code should loo4 li4e :

10
public class srv* e#tends HttpServlet % ))) public void doGet ()))! % Print?riter out Ores),et?riter(!& rest)setGontentType(Jte#tDhtmlJ!& ))) out)println(JHello Ghainin, servletJ!& ' ' *ll the servlet srvF has to do is to open an input stream to the re uest object and read the data into a Fu++eredReader object as +or e#ample : Fu++eredReader b O new Fu++eredReader( new $nputStreamReader(re ),et$nputStream(! ! !& Strin, data O b)readHine(!& b)close(!& *+ter that you can +ormat your output with the data) $t should wor4 strai,th+orward with =ava ?eb Server or =serv too) =ust loo4 at in their 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 as a 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 should be 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@<5 w#th servlets

*ll the >F;S provide the +acility o+ loc4s whenever the data is bein, modi+ied) There can 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 pro,rammin,) 0) $+ database updates are on the same row then the rows are loc4ed automatically by the >F;S, hence we have to send re uests to the >F;S repetitively until the loc4 is released by >F;S) This issue is dealt with in the =>FG documentation& loo4 up JTransactionsJ and Jauto@commitJ) $t can ,et pretty con+usin,) =9) 'hat #s the d#fference between Gener#cServlet and HttpServlet

11
GenericServlet is +or servlets that mi,ht not use HTTP, li4e +or instance <TP servlets) O+ course, it turns out that there/s no such thin, as <TP servlets, but they were tryin, to plan +or +uture ,rowth when they desi,ned the spec) ;aybe some day there will be another subclass, but +or now, always use HttpServlet) =1) How do "ou share sess#on ob7ects between servlets and 0SP

Sharin, sessions between a servlet and a =SP pa,e is strai,ht +orward) =SP ma4es it a little easy by creatin, a session object and ma4in, it available already) $n a servlet you would have to do it yoursel+) This is how: DDcreate a session i+ one is not created already now HttpSession session O re uest),etSession(true!& DDassi,n the session variable to a value) session)putTalue(JvariableJ,JvalueJ!& $n the jsp pa,e this is how you ,et the session value: NL session),etTalue(JvariableJ!& LP ==) 'hat #s a servlet * servlet is a way o+ e#tendin, your web server with a =ava pro,ram to per+orm tas4s previously dealt with by GG$ scripts or proprietary server e#tension +ramewor4s) =!) Is there an" method to unload a servlet from 'eb Server memor" w#thout restart#n+ the server There is no standard methodDmechanism to unload a servlet +rom memory) Some servers, li4e =?S, provide the means to load and unload servlets +rom their administration module) Others, li4e Tomcat, re uire you to just replace the ?*R +ile) =&) 'hat d#st#n+u#shes a 0ava<ean from a Servlet =avaFeans are a set o+ rules to +ollow to create reusable so+tware components, or beans) This contains properties and events) *t the end you have a component which could be e#amined by a pro,ram (li4e an $>"! to allow the user o+ your =avaFean component to con+i,ure it and to run in its =ava pro,rams) Servlets are =ava classes runnin, in a Servlet en,ine implementin, a particular inter+ace: Servlet, +orcin, you to implement some methods (service(!!) The servlet is an e#tension o+ your web server where this servlet is runnin, on and only lets you 4now when a user re uests a G"T or POST calls +rom a web pa,e to your servlet) So, both have nothin, in common e#cept =ava) =/) How much data we can store #n a sess#on ob7ect *ny amount o+ data can be stored there because the session is 4ept on the server side) The only limitation is session$d len,th, which shouldn/t e#ceed \6]]] bytes @ this limitation is implied by HTTP header len,th limitation to 6Ib since session$d may be

12
stored in the coo4ie or encoded in 2RH (usin, A()* rewr#t#n+A! and the coo4ie speci+ication says the si3e o+ coo4ie as well as HTTP re uest (e),) G"T Ddocument)html^n! cannot be lon,er then 64b) =1) 'hat #s the d#fference between the doGet and doPost methods doGet is called in response to an HTTP G"T re uest) This happens when users clic4 on a lin4, or enter a 2RH into the browser/s address bar) $t also happens with some HT;H <OR;s (those with ;"THO>OJG"TJ speci+ied in the <OR; ta,!) doPost is called in response to an HTTP POST re uest) This happens with some HT;H <OR;s (those with ;"THO>OJPOSTJ speci+ied in the <OR; ta,!) Foth methods are called by the de+ault (superclass! implementation o+ service in the HttpServlet base class) .ou should override one or both to per+orm your servlet/s actions) .ou probably shouldn/t override service(!) =2) 'hat #s the d#fference between encode)ed#rect(rl and encode()* encode2RH and encodeRedirect2RH are methods o+ the HttpResponse object) Foth rewrite a raw 2RH to include session data i+ necessary) ($+ coo4ies are on, both are no@ops)! encode2RH is +or normal lin4s inside your HT;H pa,es) encodeRedirect2RH is +or a lin4 you/re passin, to response)sendRedirect(!) $t has sli,htly di++erent synta# re uirements too ,ory to ,et into here) =4) 5an I use S"stemBe.#t;) #n servlets Gac47 5o no no no no))) *t best, you/ll ,et a security e#ception) *t worst, you/ll ma4e the servlet en,ine, or maybe the entire web server, uit) .ou don/t really want to do that, =8) I am open#n+ a s#n+le 0@<5 connect#on #n m" #n#t;) methodB @o I need to s"nchron#%e on the 5onnect#on or the Statement ob7ect

.ou shouldn/t have to) $+ your =>FG driver supports multiple connections, then the various createStatement methods will ,ive you a thread@sa+e, reentrant, independent Statement that should wor4 OI, even i+ other re uestsDthreads are also accessin, other Statements on the same Gonnection) O+ course, crossin, your +in,ers never hurts))) ;any early =>FG drivers were not re@ entrant) The modern versions o+ =>FG drivers should wor4 OI, but there are never any ,uarantees) 2sin, connection poolin, will avoid the whole issue, plus will lead to improved per+ormance) See this <*S +or more in+ormation) !9) How can I determ#ne the name and vers#on number of the servlet or 0SP en+#ne that I am us#n+ <rom within a servlet, you can invo4e the ServletGonte#t),etServer$n+o(! method as +ollows:

13
Strin, thisServerO ,etServletGon+i,(!),etServletGonte#t(!),etServer$n+o(!& $+ you are usin, =SP, you can use this e#pression: NLO application),etServer$n+o(! LP !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 2RH +rom the re uest object) To reconstruct the absolute 2RH +rom the scheme, server name, port, 2R$ and uery strin, you can use the 2RH class +rom java)net) The +ollowin, code +ra,ment will determine your pa,e/s absolute 2RH: Strin, +ile O re uest),etRe uest2R$(!& i+ (re uest),etSueryStrin,(! 7O null! % +ile MO /A/ M re uest),etSueryStrin,(!& ' 2RH reconstructed2RH O new 2RH(re uest),etScheme(!, re uest),etServer5ame(!, re uest),etServerPort(!, +ile!& out)println(2RH)toStrin,(!!& !=) 'h" do Gener#cServlet and HttpServlet #mplement the Ser#al#%able #nterface GenericServlet and HttpServlet implement the Seriali3able inter+ace so that servlet en,ines can JhibernateJ 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 en,ines do this, and it could have serious implications, li4e brea4in, re+erences to objects ,otten in the init(! method without the pro,rammer 4nowin, it) Pro,rammers should be aware o+ this pit+all and implement servlets which are stateless as possible, dele,atin, data store to Session objects or to the ServletGonte#t) $n ,eneral stateless servlets are better because they scale much better and are cleaner code) !!) How does one choose between overr#d#n+ the doGet;), doPost;), and serv#ce;) methods The 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 re uest +rom a HTTP protocol re uest) * G"T re uest is a re uest to get a resource +rom the server) This is the case o+ a browser re uestin, a web pa,e) $t is also possible to speci+y parameters in the re uest, but the length of the parameters on the whole is limited) This is the case o+ a +orm in a web pa,e declared this way in html: N+orm methodOJG"TJP or N+ormP) * POST re uest is a re uest to post (to send! +orm data to a resource on the server) This is the case o+ o+ a +orm in a web pa,e declared this way in html: N+orm methodOJPOSTJP) $n this case the si3e o+ the parameters can be much ,reater) The GenericServlet has a service(! method that ,ets called when a client re uest is made) This means that it ,ets called by both incomin, re uests and the HTTP re uests 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 client re uest is G"T or POST) This means that the parsin, o+ the re uest is done by the servlet: you have the appropriate method called and have convenience methods to read the re uest parameters)

14
N T!" the doGet(! and doPost(! methods (as well as other HttpServlet methods! are called by the service(! method) Goncludin,, i+ you must respond to G"T or POST re uests 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 re uests made by a client that is not usin, the HTTP protocol, you must 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;H document) * servlet can receive a re uest to ,et some in+ormation throu,h "=F +rom one or more databases, then convert this data into a static HT;HD?;H pa,e +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 remote machines) $t is way +or an application to tal4 to another remote machine and e#ecute di++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 address and the pa,es 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 client who 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 thin,s! 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 TGPD$P soc4ets to the 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) !1) How can I des#+n m" servlet?0SP so that >uer" results +et d#spla"ed on several pa+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#c:ed, I should see the ne.t?prev#ous 19 records and so onB

2se a =ava Fean to store the entire result o+ the search that you have +ound) The servlet will then set a pointer to the +irst line to be displayed in the pa,e and the number o+ lines to display, and +orce a display o+ the pa,e) The *ction in the +orm would point bac4 to the servlet in the =SP pa,e which would determine whether a ne#t or previous button has been pressed and reset the pointer to previous pointer M number o+ lines and redisplay the pa,e) The =SP pa,e would have a scriplet to display data +rom the =ava Fean +rom the start pointer set to the ma#imum number o+ lines with buttons to allow previous or ne#t pa,es to be selected) These buttons would be displayed based on the pa,e number (i)e) i+ +irst then don/t display previous button!)

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

$nstead o+ usin, ,etParameter(! with the ServletRe uest, as you would with sin,le@ valued parameters, use the ,etParameterTalues(! method) This returns a Strin, array (or null! containin, all the values o+ the parameter re uested) !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 desi,n a bean which can act as a wrapper +or storin, the resultset 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 re uest object and +orwarded to a display =SP pa,e as +ollows: com)+oo)dbFean bean O new com)+oo)dbFean(!& DDcall setters to initiali3e bean re )set*ttribute(JdbFeanJ, bean!& urlOJ)))J& DDrelative url +or display jsp pa,e ServletGonte#t sc O ,etServletGonte#t(!& Re uest>ispatcher rd O sc),etRe uest>ispatcher(url!& rd)+orward(re , res!& The bean can then be accessed within the =SP pa,e via the useFean ta, as: Njsp:useFean idOJdbFeanJ classOJcom)+oo)dbFeanJ scopeOJre uestJDP ))) NL DDiterate throu,h the rows within dbFean and DDaccess the values usin, a scriptlet LP *lso, it is best to desi,n your application such that you avoid placin, beans into the session unless absolutely necessary) Placin, lar,e objects within the session imposes a heavy burden on the per+ormance o+ the servlet en,ine) O+ course, there may be additional desi,n considerations to ta4e care o+ @ especially i+ your servlets are runnin, 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 uni ue document capable o+ sendin, its own re uests and receivin, its own responses) .ou can create a top servlet (say, <rameServlet! that upon invocation creates the +rame layout you desire and sets the SRG parameters +or the +rame ta,s to be another servlet, a static pa,e or any other le,al value +or SRG) @@@@@@@@@@@@@@@@@@@@@@ S*;PH" @@@@@@@@@@@@@@@@@@@@@@

16
public void doGet(HttpServletRe uest re uest, HttpServletResponse response! throws Servlet"#ception, $O"#ception % response)setGontentType(Jte#tDhtmlJ!& Print?riter out O new Print?riter (response),et?riter(!!& out)println(JNhtmlPJ!& out)println(JNheadP.our TitleNDheadPJ!& DD DD DD DD de+inin,the three rows o+ <rames +or the main pa,e top : +rmRmiddle : +rmR0 bottom : +rmR1

out)println(JN+rameset rowsO-0L,B]L,_ colsO_PJ!& out)println(JN+rame srcODservletsD;enuServlet nameO+rmR-PJ!& out)println(JN+rame srcODservletsD>ummyServletAmodeO+ull nameO+rmR0PJ!& out)println(JN+rame srcODservletsD>ummyServletAmodeOsmall nameO+rmR1PJ!& out)println(JND+ramesetPJ!& out)println(JNbodyPJ!& out)println(JNDbodyPNDhtmlPJ!& out)close(!& @@@@@@@@@@@@@@@@@@@@@@@@@@ "5> @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ?here ;enuServlet and >ummyServlet provide content and behavior +or the +rames ,enerated by <rameServlet) /1) 5an I send mult#ple responses for a s#n+le re>uest

5o) That doesn/t even ma4e sense :@! .ou can, however, send a JredirectJ, which tells the user/s browser to send another re uest, possibly to the same servlet with di++erent parameters) Search this <*S on JredirectJ to learn more) /=) 'hat #s CO)- based lo+#n and how do I use #t 6lso, what servlet conta#ners support #t

<orm based lo,in is one o+ the +our 4nown web based lo,in mechanisms) <or completeness $ list all o+ them with a description o+ their nature: -) HTTP <as#c 6uthent#cat#on *n authentication protocol de+ined within the HTTP protocol (and based on headers!) $t indicates the HTTP realm +or which access is bein, ne,otiated

17
and sends passwords with base:6 encodin,, there+ore it is not very secure) (See R<G0]:C +or more in+ormation)! 0) HTTP @#+est 6uthent#cat#on Hi4e HTTP Fasic *uthentication, but with the password transmitted in an encrypted +orm) $t is more secure than Fasic, but less then HTTPS *uthentication which uses private 4eys) .et it is not currently in widespread use) 1) HTTPS 6uthent#cat#on ;SS* -utual 6uthent#cat#on) This security mechanism provides end user authentication usin, HTTPS (HTTP over SSH!) $t per+orms mutual (client 9 server! certi+icate based authentication with a set o+ di++erent cipher suites) 6) Corm <ased *o+#n * standard HT;H +orm (static, ServletD=SP or script ,enerated! +or lo,,in, in) $t can be associated with protection or user domains, and is used to authenticate previously unauthenticated users) The major advanta,e is that the loo4 and +eel o+ the lo,in screen can be controlled (in comparison to the HTTP browsers/ built in mechanisms!) To support -), 1), and 6) o+ these authentication mechanisms is a re uirement o+ the =0"" Speci+ication (as o+ v-)0, 1)6)-)1 Re uired Ho,in ;echanisms!) (HTTP >i,est *uthentication is not a re uirement, but containers are encoura,ed to support it)! #ou can also see section $.$.%%.% of the &'!! (pecs. )*ser +uthentication, ,eb -lient. for more detailed descriptions of the mechanisms. Thus any Servlet container that con+orms to the =0"" Plat+orm speci+ication should support +orm based lo,in) To be more speci+ic, the Servlet 0)0 Speci+ication describesDspeci+ies the same mechanisms in --)8 includin, +orm based lo,in in --)8)1) This section )%%./.$. describes in depth the nature, the requirements and the naming conventions of form based login and I suggest to ta0e a loo0 at it. Here is a sample o+ a con+ormin, HT;H lo,in +orm: N+orm methodOJPOSTJ actionOJjRsecurityRchec4JP Ninput typeOJte#tJ nameOJjRusernameJP Ninput typeOJpasswordJ nameOJjRpasswordJP ND+ormP Inown Servlet containers that support <OR;@based lo,in are: iPlanet *pplication Server Tomcat (the re+erence implementation o+ the =ava Servlet *P$!

/!) How do I capture a re>uest and d#spatch the e.act re>uest ;w#th all the parameters rece#ved) to another ()*

*s +ar as i 4now it depends on the location o+ the ne#t tar,et url)

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: Re uest>ispatcher rd O null& Strin, tar,et2RH O Jtar,etRservletRnameJ& ServletGonte#t ct# O this),etServletGonte#t(!& rd O ct#),etRe uest>ispatcher(tar,et2RH!& rd)+orward(re uest, response!&

U U U U U

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

=SP is intended +or dynamically ,eneratin, pa,es) The ,enerated pa,es can include wml, html, dhtml or whatever you want))) ?hen you have a ,enerated pa,e, =SP has already made its wor4) <rom this moment you have a pa,e) $+ you want automatic re+reshin,, then this should be acomplished by the technolo,y included in the ,enerated pa,e (=SP will tell only what to include in the pa,e!) The browser can not be loaded by e#tern +actors) The browser is the one who +etches url/s since the http protocol is re uest@response based) $+ a server can reload a browser without its allow, it implies that we could be receivin, pa,es which we haven/t as4ed +or +rom servers) ;ay you could use applets and a ServerSoc4et +or receivin, incomin, si,nals +rom the server +or chan,ed data in the >F) This way you can load new in+ormation inside the applet or try to +orce a pa,e reload) XThat/s a nice idea @@ it could use the show>ocument(! call to reload the current pa,e) $t could also use HTTP pollin, instead o+ maintainin, an e#pensive soc4et connection) @*le#( Perhaps (i+ possible!, could be simpler usin, an automatic =avaScript re+reshin, +unction that +orce pa,e 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 pa,es, classes, and other resources that can be bundled and run on multiple containers +rom multiple vendors) * web application is rooted at a speci+ic path within a web server) <or e#ample, a catalo, application could be located at http:DD www)mycorp)comDcatalo,) *ll re uests that start with this pre+i# will be routed to the ServletGonte#t which represents the catalo, application) /1) How can I call a servlet from a 0SP pa+e How can I pass var#ables from the 0SP that the servlet can access

19

.ou can use Njsp:+orward pa,eOJDrelativepathD.ourServletJ DP or response)sendRedirect(Jhttp:DDpathD.ourServletJ!) Tariables can be sent as: Njsp:+orward pa,eODrelativepathD.ourServletP Njsp:param nameOJname-J valueOJvalue-J DP Njsp:param nameOJname0J valueOJvalue0J DP NDjsp:+orwardP .ou may also pass parameters to your servlet by speci+yin, response)sendRedirect(Jhttp:DDpathD.ourServletAparam-Oval-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 (ervlet class in the servlet container. 1or example, this can occur where there was more than one servlet definition that utili2ed a specific servlet class with different initiali2ation parameters. This can also occur when a servlet implements the (ingleThread3odel interface and the container creates a pool of servlet instances to use. /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 U U U U U U Re uest >ispatchin, HTTP Redirect Servlet Ghainin, HTTP re uest (usin, soc4ets or the 2RHGonnection class! Shared session, re uest, or application objects (beans! >irect method invocation (deprecated! Shared static or instance variables (deprecated!

Search the <*S, especially topic ;essa,e Passin, (includin, Re uest >ispatchin,! +or in+ormation on each o+ these techni ues) @*le#( Fasically interServlet communication is acheived throu,h servlet chainin,) ?hich is a process in which you pass the output o+ one servlet as the input to other) These servlets should be runnin, in the same server)

20
e),) ServletGonte#t),etRe uest>ispatcher(HttpRe uest, HttpResponse!)+orward(J5e#tServletJ! & .ou can pass in the current re uest and response object +rom the latest +orm submission to the ne#t servletD=SP) .ou can modi+y these objects and pass them so that the ne#t servletD=SP can use the results o+ this servlet) There are some Servlet en,ine speci+ic con+i,urations +or servlet chainin,) Servlets can also call public +unctions o+ other servlets runnin, in the same server) This can be done by obtainin, a handle to the desired servlet throu,h the ServletGonte#t Object by passin, it the servlet name ( this object can return any servlets runnin, in the server!) *nd then callin, the +unction on the returned Servlet object) e),) TestServlet testO (TestServlet!,etServletGon+i,(!),etServletGonte#t(!),etServlet(JOtherServletJ!& otherServlet>etailsO Test),etServlet>etails(!& .ou must be care+ul when you call another servlet/s methods) $+ the servlet that you want to call implements the Sin,leThread;odel inter+ace, your call could con+lict with the servlet/s sin,le threaded nature) (The server cannot intervene and ma4e sure your call happens when the servlet is not interactin, with another client)! $n this case, your servlet should ma4e an HTTP re uest to the other servlet instead o+ direct calls) Servlets could also invo4e other servlets pro,rammatically by sendin, an HTTP re uest) This could be done by openin, a 2RH connection to the desired Servlet) 41) 'hat #s the d#fference between re>uest attr#butes, sess#on attr#butes, and Servlet5onte.t attr#butes

* Servlet5onte.t attribute is an object bound into a conte#t throu,h Servlet5onte.tBset6ttr#bute;) method and which is available to *HH servlets (thus =SP! in that conte#t, or to other conte#ts via the ,etGonte#t(! method) Fy de+inition a conte#t attribute e#ists locally in the T; where they were de+ined) So, they/re unavailable on distributed applications) Sess#on attributes are bound to a session, as a mean to provide state to a set o+ related HTTP re uests) Session attributes are available O5H. to those servlets which join the session) They/re also unavailable to di++erent =T;s in distributed scenarios) Objects can be noti+ied when they/re boundDunbound to the session implementin, the HttpSessionFindin,Histener inter+ace) )e>uest attributes are bound to a speci+ic re uest object, and they last as +ar as the re uest is resolved or while it 4eep dispatched +rom servlet to servlet) They/re used more as communication channel between Servlets via the Re uest>ispatcher $nter+ace (since you can/t add Parameters)))! and by the container) Re uest attributes are very use+ul in web apps when you must provide setup in+ormation between in+ormation providers and the in+ormation presentation layer (a =SP! that is bound to a speci+ic re uest and need not be available any lon,er, which usually happens with sessions without a ri,orous control strate,y)

21
Thus we can say that conte#t attributes are meant +or in+ra@structure such as shared connection pools, session attributes to conte#tual in+ormation such as user identi+ication, and re uest attributes are meant to speci+ic re uest in+o such as uery results) 4=) 6re s#n+leton?stat#c ob7ects shared between servlet conte.ts XSuestion continues: <or e#ample i+ $ have two conte#ts on a sin,le web server, and each conte#t uses a lo,in servlet and the lo,in servlet connects to a >F) The >F connection is mana,ed by a sin,leton object) >o both conte#ts have their own instance o+ the >F sin,leton or does one instance ,et shared between the twoA( $t depends on +rom where the class is loaded) The classes loaded +rom conte#t/s ,!45IN1 directory are not shared by other conte#ts, whereas classes loaded +rom -6+((7+T8 are shared) So i+ you have e#actly the same >FGonnection class in ?"F@$5<Dclasses directory o+ two di++erent conte#ts, each conte#t ,ets its own copy o+ the sin,leton (static! object) 4!) 'hen bu#ld#n+ web appl#cat#ons, what are some areas where s"nchron#%at#on problems arr#se $n ,eneral, you will run into synchroni3ation issues when you try to access any shared resource) Fy shared resource, $ mean anythin, which mi,ht be used by more than one re uest) Typical e#amples include: U U Gonnections to e#ternal servers, especially i+ you have any sort o+ poolin,) *nythin, which you include in a HttpSession) (.our user could open many browser windows and ma4e many simultaneous re uests within the one session)! Ho, destinations, i+ you do your own lo,,in, +rom your servlets)

4&) 'hat #s the d#fference between apache webserver, 7ava webserver and tomcat server *pache is an HTTP server written in G that can be compiled and run on many plat+orms) =ava ?ebServer is an HTTP server +rom Sun written in =ava that also supports Servlets and =SP) Tomcat is an open@source HTTP server +rom the *pache <oundation, written in =ava, that supports Servlets and =SP) $t can also be used as a Jplu,@inJ to native@code HTTP servers, such as *pache ?eb Server and $$S, to provide support +or Servlets (while still servin, normal HTTP re uests +rom the primary, native@code web server!) 4/) How can "ou embed a 0avaScr#pt w#th#n servlets ? 0SP pa+es

22
.ou don/t have to do anythin, special to include =avaScript in servlets or =SP pa,es) =ust have the servletD=SP pa,e ,enerate the necessary =avaScript code, just li4e you would include it in a raw HT;H pa,e) 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;H, with the included =avaScript) 41) How can I ma:e a POST re>uest throu+h responseBsend)ed#rect;) or responseBsetStatus;) and responseBsetHeader;) methods .ou can/t) $t/s a +undamental limitation o+ the HTTP protocol) .ou/ll have to +i,ure out some other way to pass the data, such as U U U 2se G"T instead ;a4e the POST +rom your servlet, not +rom the client 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 Re uest >ispatcher)

44) I call a servlet as the act#on #n a form, from a 7spB How can I red#rect the response from 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+et)e>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 call sendRedirect to ,o bac4 to the =SP) <or e#ample:

N<OR; *GT$O5OJD+ooDmyservletJP N$5P2T T.P"OJH$>>"5J 5*;"OJredirectJ T*H2"OJD+ooDthisjsp)jspJP Shoe si3e: N$5P2T 5*;"OJshoesi3eJP N$5P2T T.P"OJS2F;$TJP ND<OR;P Then in the servlet))) response)sendRedirect(re uest),etParameter(JredirectJ!!& 48) 'hat #s the Servlet5onf#+ ob7ect, and wh" #s #t useful The ServletGon+i, object is an inter+ace) $t contains the methods

23
,et$nitParameter ,et$nitParameter5ames ,etServletGonte#t ,etServlet5ame .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 Gonte#t the servlet is runnin, in) ,etServletGonte#t is the most valuable method, as it allows you to share in+ormation accross 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 <ramewor4 this class plays the role o+ controller) *ll the re uests to the server ,oes throu,h the controller) Gontroller is responsible +or handlin, all the re uests) D=: How "ou w#ll ma:e ava#lable an" -essa+e )esources @ef#n#t#ons f#le to the Struts Cramewor: Env#ronment 6: ;essa,e Resources >e+initions +ile are simple )properties +iles and these +iles contains the messa,es that can be used in the struts project) ;essa,e Resources >e+initions +iles can be added to the struts@con+i,)#ml +ile throu,h Emessa+e$resources ?F ta,) E.ample: Nmessa,e@resources parameterOJ;essa,eResourcesJ DP D!: 'hat #s 6ct#on 5lass 6: The *ction is part o+ the controller) The purpose o+ *ction Glass is to translate the HttpServletRe uest to the business lo,ic) To use the *ction, we need to Subclass and overwrite the e#ecute(! method) The *ctionServlet (commad! passes the parameteri3ed class to *ction <orm usin, the e#ecute(! method) There should be no database interactions in the action) The action should receive the re uest, call business objects (which then handle database, or inter+ace with =0"", etc! and then determine where to ,o ne#t) "ven better, the business objects could be handed to the action at runtime ($oG style! thus removin, any dependencies on the model) The return type o+ the e#ecute method is *ction<orward which is used by the Struts <ramewor4 to +orward the re uest to the +ile as per the value o+ the returned *ction<orward object) D&: 'r#te code of an" 6ct#on 5lass 6: Here is the code o+ *ction Glass that returns the *ction<orward object) Test6ct#onB7ava pac:a+e roseindia)net& #mport java#)servlet)http)HttpServletRe uest& #mport java#)servlet)http)HttpServletResponse& #mport #mport #mport #mport or,)apache)struts)action)*ction& or,)apache)struts)action)*ction<orm& or,)apache)struts)action)*ction<orward& or,)apache)struts)action)*ction;appin,&

publ#c class Test*ction e.tends *ction

24
%

publ#c *ction<orward e#ecute( *ction;appin, mappin,, *ction<orm +orm, HttpServletRe uest re uest, HttpServletResponse response! throws "#ception% return mappin,)+ind<orward(Jtest*ctionJ!& '

' D/: 'hat #s 6ct#onCorm 6: *n *ction<orm is a =avaFean that e#tends or,)apache)struts)action)*ction<orm) *ction<orm maintains the session state +or web application and the *ction<orm object is automatically populated on the server side with data entered +rom a +orm on the client side) D1: 'hat #s Struts Gal#dator Cramewor: 6: Struts <ramewor4 provides the +unctionality to validate the +orm data) $t can be use to validate the data on the users browser as well as on the server side) Struts <ramewor4 emits the java scripts and it can be used validate the +orm data on the client browser) Server side validation o+ +orm can be accomplished by sub classin, your <rom Fean with @"naGal#datorCorm class) The Talidator +ramewor4 was developed by >avid ?inter+eldt as third@party add@on to Struts) 5ow the Talidator +ramewor4 is a part o+ =a4arta Gommons project and it can be used with or without Struts) The Talidator +ramewor4 comes inte,rated with the Struts <ramewor4 and can be used without doin, any e#tra settin,s)

D2B G#ve the @eta#ls of H-* f#les used #n Gal#dator Cramewor: 6: The Talidator <ramewor4 uses two Y;H con+i,uration +iles val#dator$rulesB.ml and val#dat#onB.ml) The val#dator$rulesB.ml de+ines the standard validation routines, these are reusable and used in val#dat#onB.ml) to de+ine the +orm speci+ic validations) The val#dat#onB.ml de+ines the validations applied to a +orm bean) D4B How "ou w#ll d#spla" val#dat#on fa#l errors on 7sp pa+e 6: <ollowin, ta, displays all the errors: Nhtml:errorsDP

D8B How "ou w#ll enable front$end val#dat#on based on the .ml #n val#dat#onB.ml 6: The Nhtml:javascriptP ta, to allow +ront@end validation based on the #ml in validation)#ml) <or e#ample the code: Nhtml:javascript +orm5ameOJlo,on<ormJ dynamic=avascriptOJtrueJ static=avascriptOJtrueJ DP ,enerates the client side java script +or the +orm Jlo,on<ormJ as de+ined in the validation)#ml +ile) The Nhtml:javascriptP when added in the jsp +ile ,enerates the client site validation script) Duest#on19: 'hat are )e>uestProcessor & )e>uest@#spatcher 6nswer: The controller is responsible +or interceptin, and translatin, user input into actions to be per+ormed by the model) The controller is responsible +or selectin, the ne#t view based on user input and the outcome o+ model operations) The Gontroller receives the re uest +rom the browser& invo4e a business operation and coordinatin, the view to return to the client)

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 5lass The 6ct#on 5lass The *ctionServlet e#tends the 7ava.BservletBhttpBhttpServlet class) 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, re uests are mapped to the central controller in the deployment descriptor as +ollows) NservletP Nservlet@namePactionNDservlet@nameP Nservlet@classPor,)apache)struts)action)*ctionServletNDservlet@classP NDservletP *ll re uest 2R$s with the pattern _)do are mapped to this servlet in the deployment descriptor as +ollows) Nservlet@mappin,P Nservlet@namePactionNDservlet@nameP Nurl@patternP_)doNDurl@patternP Nurl@patternP_)doNDurl@patternP * re uest 2R$ that matches this pattern will have the +ollowin, +orm) http:DDwww)myRsiteRname)comDmyconte#tDaction5ame)do The precedin, mappin, is called e#tension mappin,, however, you can also speci+y path mappin, where a pattern ends with D_ as shown below) Nservlet@mappin,P Nservlet@namePactionNDservlet@nameP Nurl@patternPDdoD_NDurl@patternP Nurl@patternP_)doNDurl@patternP * re uest 2R$ that matches this pattern will have the +ollowin, +orm) http:DDwww)myRsiteRname)comDmyconte#tDdoDactionR5ame

The class or+BapacheBstrutsBact#onBre>uestProcessor process the re uest +rom the controller) .ou can sublass the Re uestProcessor with your own version and modi+y how the re uest is processed) Once the controller receives a client re uest, it dele,ates the handlin, o+ the re uest to a helper class) This helper 4nows how to e#ecute the business operation associated with the re uested action) $n the Struts +ramewor4 this helper class is descended o+ or,)apache)struts)action)*ction class) $t acts as a brid,e between a client@side user action and business operation) The *ction class decouples the client re uest +rom the business model) This decouplin, allows +or more than one@to@

26
one mappin, between the user re uest 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<orward e#ecute(*ction;appin, mappin,, *ction<orm +orm, HttpServletRe uest re uest, HttpServletResponse response! throws "#ception The e#ecute(! method is called by the controller when a re uest is received +rom a client) The controller creates an instance o+ the *ction class i+ one doesn`t already e#ist) The struts framewor: w#ll create onl" a s#n+le #nstance of each 6ct#on class #n "our appl#cat#on )

*ction is mapped in the struts con+i,uration +ile and this con+i,uration is loaded into memory at startup and made available to the +ramewor4 at runtime) "ach *ction element is represented in memory by an instance o+ the or,)apache)struts)action)*ction;appin, class) The *ction;appin, object contains a path attribute that is matched a,ainst a portion o+ the 2R$ o+ the incomin, re uest) NactionP pathO JDsomere uestJ typeOJcom)somepac4a,e)some*ctionJ scopeOJre uestJ nameOJsome<ormJ validateOJtrueJ inputOJsomejsp)jspJ N+orward nameOJSuccessJ pathOJDactionD#ysJ redirectOJtrueJDP N+orward nameOJ<ailureJ pathOJDsomejsp)jspJ redirectOJtrueJDP NDactionP Once this is done the controller should determine which view to return to the client) The e#ecute method si,nature in *ction class has a return type or,)apache)struts)action)*ction<orward class) The *ction<orward class represents a destination to which the controller may send control once an action has completed) $nstead o+ speci+yin, an actual =SP pa,e in the code, you can declaratively associate as action +orward throu,h out the application) The action +orward are speci+ied in the con+i,uration +ile) NactionP pathO JDsomere uestJ typeOJcom)somepac4a,e)some*ctionJ scopeOJre uestJ nameOJsome<ormJ validateOJtrueJ inputOJsomejsp)jspJ N+orward nameOJSuccessJ pathOJDactionD#ysJ redirectOJtrueJDP N+orward nameOJ<ailureJ pathOJDsomejsp)jspJ redirectOJtrueJDP NDactionP The action +orward mappin,s also can be speci+ied in a ,lobal section, independent o+ any speci+ic action mappin,) N,lobal@+orwardsP

27
N+orward nameOJSuccessJ pathOJDactionDsomejsp)jspJ DP N+orward nameOJ<ailureJ pathOJDsomeotherjsp)jspJ DP ND,lobal@+orwardsP publ#c #nterface )e>uest@#spatcher >e+ines an object that receives re uests +rom the client and sends them to any resource (such as a servlet, HT;H +ile, or =SP +ile! on the server) The servlet container creates the Re uest>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 Re uest>ispatcher objects to wrap any type o+ resource) +et)e>uest@#spatcher public Re uest>ispatcher ,etRe uest>ispatcher(java)lan,)Strin, path! Returns a Re uest>ispatcher object that acts as a wrapper +or the resource located at the ,iven path) * Re uest>ispatcher object can be used to +orward a re uest to the resource or to include the resource in a response) The resource can be dynamic or static) The pathname must be,in with a JDJ and is interpreted as relative to the current conte#t root) 2se ,etGonte#t to obtain a Re uest>ispatcher +or resources in +orei,n conte#ts) This method returns null i+ the ServletGonte#t cannot return a Re uest>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#ed path See 6lso: )e>uest@#spatcher, +et5onte.t;7avaBlan+BStr#n+) ,et5amed>ispatcher public Re uest>ispatcher ,et5amed>ispatcher(java)lan,)Strin, name! Returns a Re uest>ispatcher object that acts as a wrapper +or the named servlet) Servlets (and =SP pa,es also! may be ,iven names via server administration or via a web application deployment descriptor) * servlet instance can determine its name usin, ServletGon+i,),etServlet5ame(!) This method returns null i+ the ServletGonte#t cannot return a Re uest>ispatcher +or any reason) Parameters: name @ a Strin, speci+yin, the name o+ a servlet to wrap Returns: a Re uest>ispatcher object that acts as a wrapper +or the named servlet

28
See *lso: Re uest>ispatcher, ,etGonte#t(java)lan,)Strin,!, ServletGon+i,),etServlet5ame(! Duest#on11: 'h" canIt we overr#de create method #n StatelessSess#on<ean 6nswer: <rom the "=F Spec: @ * Session bean/s home inter+ace de+ines one or morecreate()))! methods) "ach create method must be named create and must match one o+ the ejbGreate methods de+ined in the enterprise Fean class) The return type o+ a create method must be the enterprise Fean/s remote inter+ace type) The home inter+ace o+ a stateless session bean must have one create method that ta4es no ar,uments)

Duest#on1=: Is struts threadsafe G#ve an e.ample 6nswer: Struts is not only thread@sa+e but thread@dependant) The response to a re uest is handled by a li,ht@wei,ht *ction object, rather than an individual servlet) Struts instantiates each *ction class once, and allows other re uests to be threaded throu,h the ori,inal object) This core strate,y conserves resources and provides the best possible throu,hput) * properly@desi,ned application will e#ploit this +urther by routin, related operations throu,h a sin,le *ction)

Duest#on1!: 5an we ser#al#%e stat#c var#able 6nswer: Seriali3ation is the process o+ convertin, a set o+ object instances that contain re+erences to each other into a linear stream o+ bytes, which can then be sent throu,h a soc4et, stored to a +ile, or simply manipulated as a stream o+ data) Seriali3ation is the mechanism used by R;$ to pass objects between =T;s, either as ar,uments in a method invocation +rom a client to a server or as return values +rom a method invocation) $n the +irst section o+ this boo4, there are three e#ceptions in which seriali3ation doesn`t necessarily read and write to the stream) These are -) Ser#al#%at#on #+nores stat#c f#elds, because the" are not part of an" part#cular ob7ect3s state) 0) Fase class +ields are only handled i+ the base class itsel+ is seriali3able) 1) Transient +ields) There are +our basic thin,s you must do when you are ma4in, a class seriali3able) They are: -) $mplement the Seriali3able inter+ace) 0) ;a4e sure that instance@level, locally de+ined state is seriali3ed properly) 1) ;a4e sure that superclass state is seriali3ed properly) 6) Override e uals( ! and hashGode(!) it is possible to have control over seriali3ation process) The class should implement "#ternali3able inter+ace) This inter+ace contains two methods namely read"#ternal and write"#ternal) .ou should implement these methods and write the lo,ic +or customi3in, the seriali3ation process)))) (Source: http:DDwww)oreilly)comDcatalo,DjavarmiDchapterDch-])html!

Duest#on1&: 'hat are the uses of t#les$defB.ml f#le, resourcebundleBpropert#es f#le, and val#dat#onB.ml f#le 6nswer: tiles@de+)#ml is is an #ml +ile used to con+i,ure tiles with the struts application) .ou can de+ine the layout D header D +ooter D body content +or your Tiew) See more at http:DDwww)roseindia)netDstrutsDusin,@tiles@de+s@#ml)shtml) The resourcebundleBpropert#es +ile is used to con+i,ure the messa,e (errorD other messa,es! +or

29
the struts applications) The +ile validation)#ml is used to declare sets o+ validations that should be applied to <orm Feans) <pr more in+ormation please visit http:DDwww)roseindia)netDstrutsDaddressRstrutsRvalidator)shtml)

Duest#on 1/: 'hat #s the d#fference between perform;) and e.ecute;) methods *nswer: Per+orm method is the method which was deprecated in the Struts Tersion -)-) $n Struts -)#, *ction)per+orm(! is the method called by the *ctionServlet) This is typically where your business lo,ic resides, or at least the +low control to your =avaFeans and "=Fs that handle your business lo,ic) *s we already mentioned, to support declarative e#ception handlin,, the method si,nature chan,ed in per+orm) 5ow e#ecute just throws "#ception) *ction)per+orm(! is now deprecated& however, the Struts v-)- *ctionServlet is smart enou,h to 4now whether or not it should call per+orm or e#ecute in the *ction, dependin, on which one is available)

Duest#on 11: 'hat are the var#ous Struts ta+ l#brar#es *nswer: Struts is very rich +ramewor4 and it provides very ,ood and user +riendly way to develop web application +orms) Struts provide many ta, libraries to ease the development o+ web applications) These ta, libraries are: _ Fean ta, library @ Ta,s +or accessin, =avaFeans and their properties) _ HT;H ta, library @ Ta,s to output standard HT;H, includin, +orms, te#t bo#es, chec4bo#es, radio buttons etc) _ Ho,ic ta, library @ Ta,s +or ,eneratin, conditional output, iteration capabilities and +low mana,ement _ Tiles or Template ta, library @ <or the application usin, tiles _ 5ested ta, library @ <or usin, the nested beans in the application Duest#on 12: 'hat do "ou understand b" @#spatch6ct#on 6nswer: >ispatch*ction is an action that comes with Struts -)- or later, that lets you combine Struts actions into one class, each with their own method) The or,)apache)struts)action)>ispatch*ction class allows multiple operation to mapped to the di++erent +unctions in the same *ction class) <or e#ample: * pac4a,e mi,ht include separate Re,Greate, Re,Save, and Re,>elete *ctions, which just per+orm di++erent operations on the same Re,Fean object) Since all o+ these operations are usually handled by the same =SP pa,e, it would be handy to also have them handled by the same Struts *ction) * very simple way to do this is to have the submit button modi+y a +ield in the +orm which indicates which operation to per+orm) Nhtml:hidden propertyOJdispatchJ valueOJerrorJDP NSGR$PTP+unction set(tar,et! %document)+ormsX]()dispatch)valueOtar,et&'NDSGR$PTP Nhtml:submit onclic4OJset(/save/!&JPS*T"NDhtml:submitP Nhtml:submit onclic4OJset(/create/!&JPS*T" *S 5"?NDhtml:submitlP Nhtml:submit onclic4OJset(/delete!&JP>"H"T"NDhtml:submitP Then, in the *ction you can setup di++erent methods to handle the di++erent operations, and branch to one or the other dependin, on which value is passed in the dispatch +ield)

30
Strin, dispatch O my<orm),et>ispatch(!& i+ (JcreateJ)e uals(dispatch!! % ))) i+ (JsaveJ)e uals(dispatch!! % ))) The Struts >ispatch *ction Xor,)apache)struts)actions( is desi,ned to do e#actly the same thin,, but without messy branchin, lo,ic) 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 same si,nature as per+orm) This is a very modest re uirement, since in practice you usually end up doin, that 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<orward create( *ction;appin, mappin,, *ction<orm +orm, HttpServletRe uest re uest, HttpServletResponse response! throws $O"#ception, Servlet"#ception % ))) public *ction<orward save( *ction;appin, mappin,, *ction<orm +orm, HttpServletRe uest re uest, HttpServletResponse response! throws $O"#ception, Servlet"#ception % ))) Gool) Fut do you have to use a property named dispatchA 5o, you don/t) The only other step is to speci+y the name o+ o+ the dispatch property as the JparameterJ property o+ the action@mappin,) So a mappin, +or our e#ample mi,ht loo4 li4e this: Naction pathOJDre,DdispatchJ typeOJapp)re,)Re,>ispatchJ nameOJre,<ormJ scopeOJre uestJ validateOJtrueJ parameterOJdispatchJDP $+ you wanted to use the property JoJ instead, as in oOcreate, you would chan,e the mappin, to Naction pathOJDre,DdispatchJ typeOJapp)re,)Re,>ispatchJ nameOJre,<ormJ scopeOJre uestJ validateOJtrueJ parameterOJoJDP *,ain, very cool) Fut why use a =avaScript button in the +irst placeA ?hy not use several buttons named JdispatchJ and use a di++erent value +or eachA

31
.ou can, but the value o+ the button is also its label) This means i+ the pa,e desi,ners want to label the button somethin, di++erent, they have to coordinate the *ction pro,rammer) Hocali3ation becomes virtually impossible) (Source: http:DDhusted)comDstrutsDtipsD]]0)html!)

Duest#on14: How Struts relates to 0=EE 6nswer: Struts +ramewor4 is built on =0"" technolo,ies (=SP, Servlet, Ta,libs!, but it is itsel+ not part 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+i,uration +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 can additionally 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 re uest that invo4es an action) The servlet receives a +orward +rom the action and as4s the servlet container to pass the re uest to the +orward/s 2RH) *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+i,uration +iles) Here is the con+i,uration e#ample: NservletP Nservlet@namePban4in,NDservlet@nameP Nservlet@classPor,)apache)struts)action)*ctionServlet NDservlet@classP Ninit@paramP Nparam@namePcon+i,NDparam@nameP Eparam$valueF?'E<$IJC?struts$conf#+B.ml, ?'E<$IJC?struts$authent#cat#onB.ml, ?'E<$IJC?struts$helpB.ml E?param$valueF NDinit@paramP Nload@on@startupP-NDload@on@startupP NDservletP Duest#on=1: 'hat are the d#sadvanta+es of Struts 6nswer: Struts is very robust +ramewor4 and is bein, used e#tensively in the industry) Fut there are some disadvanta,es o+ the Struts: a) H#+h *earn#n+ 5urve Struts re uires lot o+ e++orts to learn and master it) <or any small project less e#perience developers could spend more time on learnin, the Struts)

32
b) Harder to learn Struts are harder to learn, benchmar4 and optimi3e) Duest#on==: 'hat #s Struts Clow 6nswer: Struts <low is a port o+ Gocoon/s Gontrol <low to Struts to allow comple# wor4+low, li4e multi@+orm wi3ards, to be easily implemented usin, continuations@capable =avaScript) $t provides the ability to describe the order o+ ?eb pa,es that have to be sent to the client, at any ,iven point in time in an application) The code is based on a proo+@o+@concept >ave =ohnson put to,ether to show how the Gontrol <low could be e#tracted +rom Gocoon) (Re+: http:DDstruts)source+or,e)netDstruts@+lowDinde#)html ! Duest#on=!: 'hat are the d#fference between Ebean:messa+eF and Ebean:wr#teF 6nswer: Ebean:messa+eF: This ta, is used to output locale@speci+ic te#t (+rom the properties +iles! +rom a ;essa,eResources bundle) Ebean:wr#teF: This ta, is used to output property values +rom a bean) Nbean:writeP is a commonly used ta, which enables the pro,rammers to easily present the data) Duest#on=&: 'hat #s *oo:up@#spatch6ct#on 6nswer: *n abstract *ction that dispatches to the subclass mapped e#ecute method) This is use+ul in cases where an HT;H +orm has multiple submit buttons with the same name) The button name is speci+ied by the parameter property o+ the correspondin, *ction;appin,) (Re+) http:DDstruts)apache)or,D-)0)BDapiDor,DapacheDstrutsDactionsDHoo4up>ispatch*ction)html!) Duest#on=/: 'hat are the components of Struts 6nswer: Struts is based on the ;TG desi,n pattern) Struts components can be cate,ories into -odel, G#ew and 5ontroller) -odel: Gomponents li4e business lo,ic D business processes and data are the part o+ ;odel) G#ew: =SP, HT;H etc) are part o+ Tiew 5ontroller: *ction Servlet o+ Struts is part o+ Gontroller components which wor4s as +ront controller to handle all the re uests) Duest#on=1: '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) <ean Ta+s: Fean Ta,s are used to access the beans and their properties) b) HT-* Ta+s: HT;H Ta,s provides ta,s +or creatin, the view components li4e +orms, buttons, etc)) c) *o+#c Ta+s: Ho,ic Ta,s provides presentation lo,ics that eliminate the need +or scriptlets) d) Jested Ta+s: 5ested Ta,s helps to wor4 with the nested conte#t) Duest#on=2: ?hat are the core classes o+ the Struts <ramewor4A 6nswer: Gore classes o+ Struts <ramewor4 are *ction<orm, *ction, *ction;appin,, *ction<orward, *ctionServlet etc) Duest#on=4: 'hat are d#fference between 6ct#onErrors and 6ct#on-essa+e 6nswer: 6ct#on-essa+e: * class that encapsulates messa,es) ;essa,es can be either ,lobal or they are speci+ic to a particular bean property) "ach individual messa,e is described by an *ction;essa,e object, which contains a messa,e 4ey (to be loo4ed up in an appropriate messa,e resources database!, and up to +our placeholder ar,uments used +or parametric substitution in the resultin, messa,e)

33
6ct#onErrors: * class that encapsulates the error messa,es bein, reported by the validate(! method o+ an *ction<orm) Talidation errors are either ,lobal to the entire *ction<orm bean they are associated with, or they are speci+ic to a particular bean property (and, there+ore, a particular input +ield on the correspondin, +orm!) Duest#on=8: How "ou w#ll handle e.cept#ons #n Struts 6nswer: $n Struts you can handle the e#ceptions in two ways: a) @eclarat#ve E.cept#on Handl#n+: .ou can either de+ine ,lobal e#ception handlin, ta,s in your struts@con+i,)#ml or de+ine the e#ception handlin, ta,s within NactionP))NDactionP ta,) E.ample: Ne#ception 4eyOJdatabase)error)duplicateJ pathOJD2ser"#ists)jspJ typeOJmyban4)account)>uplicate2ser"#ceptionJDP b) Pro+rammat#c E.cept#on Handl#n+: Here you can use try%'catch%' bloc4 to handle the e#ception)

Duest#on!9: 'hat do "ou understand b" 0SP 6ct#ons 6nswer: =SP actions are Y;H ta,s that direct the server to use e#istin, components or control the behavior o+ the =SP en,ine) =SP *ctions consist o+ a typical (Y;H@based! pre+i# o+ JjspJ +ollowed by a colon, +ollowed by the action name +ollowed by one or more attribute parameters) There are si# =SP *ctions: Njsp:includeDP Njsp:+orwardDP Njsp:plu,inDP Njsp:usebeanDP Njsp:setPropertyDP Njsp:,etPropertyDP

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:

34
o o o o o o o o o o o o o =ava *P$ +or Y;H@Fased RPG (=*Y@RPG -)-! SO*P with *ttachments *P$ +or =ava (S**=!, ?eb Services +or =0""(=SR E0-! =0"" ;ana,ement ;odel(-)]! =0"" >eployment *P$(-)-! =ava ;ana,ement "#tensions (=;Y!, =ava *uthori3ation Gontract +or Gontainers(=ava*GG! =ava *P$ +or Y;H Re,istries (=*YR! Servlet 0)6 =SP 0)] "=F 0)=;S -)=0"" Gonnector -)8

The =0"" -)6 +eatures complete ?eb services support throu,h the new =*Y@RPG -)- *P$, which supports service endpoints based on Servlets and enterprise beans) =*Y@RPG -)provides interoperability with ?eb services based on the ?S>H and SO*P protocols) The =0"" -)6 plat+orm also supports the ?eb Services +or =0"" speci+ication (=SR E0-!, which de+ines deployment re uirements +or ?eb services and utili3es the =*Y@RPG pro,rammin, 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"" ;ana,ement -)] *P$, which de+ines the in+ormation model +or =0"" mana,ement, includin, the standard ;ana,ement "=F (;"=F!) The =0"" ;ana,ement -)] *P$ uses the =ava ;ana,ement "#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 Gontract +or Gontainers (=ava*GG!) The =ava*GG *P$ improves security by standardi3in, how authentication mechanisms are inte,rated into =0"" containers)

35
The =0"" plat+orm now ma4es it easier to develop web +ront ends with enhancements to =ava Servlet and =avaServer Pa,es (=SP! technolo,ies) Servlets now support re uest listeners and enhanced +ilters) =SP technolo,y has simpli+ied the pa,e and e#tension development models with the introduction o+ a simple e#pression lan,ua,e, ta, +iles, and a simpler ta, e#tension *P$, amon, other +eatures) This ma4es it easier than ever +or developers to build =SP@enabled pa,es, especially those who are +amiliar with scripting languages) Other enhancements to the =0"" plat+orm include the =0"" Gonnector *rchitecture, which provides incomin, resource adapter and =ava ;essa,e Service (=;S! plu, ability) 5ew +eatures in "nterprise =avaFeans ("=F! technolo,y include ?eb service endpoints, a timer service, and enhancements to "=F SH and messa,e@driven beans) The =0"" -)6 plat+orm also includes enhancements to deployment descriptors) They are now de+ined usin, Y;H Schema which can also be used by developers to validate their Y;H structures) 5ote: The above in+ormation comes +rom S25 released notes)

You might also like