计算机外文翻译 XML与JSP联手.docx
《计算机外文翻译 XML与JSP联手.docx》由会员分享,可在线阅读,更多相关《计算机外文翻译 XML与JSP联手.docx(14页珍藏版)》请在冰点文库上搜索。
计算机外文翻译XML与JSP联手
英文原文:
UsingXMLandJSPtogether
I'mgoingtoassumethat,likemostJavaprogrammers,youknowwhatJavaServerPages(JSP)andExtensibleMarkupLanguage(XML)are,butyoumaybealittleunclearonhowyoucanusethem.JSPuseisprettyeasytodefend.ItallowsyoutodesignaWebsitebuiltfromfilesthatlookandactalotlikeHTML.TheonlydifferenceisthatJSPsalsoactdynamically--forexample,theycanprocessformsorreaddatabases--usingJavaasaserver-sidescriptinglanguage.XMLuseismoredifficulttojustify.Whileitseemsasifeverynewproductsupportsit,eachoneseemstobeusingXMLforadifferentpurpose.
Inthisarticle,youwilllearntodesignasystemusingXMLinafairlymodestway.ManyWebsiteshavevastcollectionsofdatathataredisplayedinamoreorlessstandardway.IwilldesignasystemthatusesXMLfilestostoredataonaWebserverandJSPfilestodisplaythatdata.
XMLversusrelationaldatabases
"Butwait,"youmayask,"you'reusingXMLtostoredata?
Whynotuseadatabase?
"Goodquestion.Theansweristhatformanypurposes,adatabaseisoverkill.Touseadatabase,youhavetoinstallandsupportaseparateserverprocess,whichoftenalsorequiresinstallingandsupportingadatabaseadministrator.YoumustlearnSQL,andwriteSQLqueriesthatconvertdatafromarelationaltoanobjectstructureandbackagain.IfyoustoreyourdataasXMLfiles,youlosetheoverheadofanextraserver.Youalsogainaneasywaytoedityourdata:
justuseatexteditor,ratherthanacomplicateddatabasetool.XMLfilesarealsoeasiertobackup,tosharewithyourfriends,ortodownloadtoyourclients.Youcanalsoeasilyuploadnewdatatoyoursite,usingFTP.
AmoreabstractadvantageofXMListhat,beingahierarchicalratherthanarelationalformat,itcanbeusedinamuchmorestraightforwardmannertodesigndatastructuresthatfityourneeds.Youdon'tneedtouseanentityrelationshipeditornornormalizeyourschema.Ifyouhaveoneelementthatcontainsanotherelement,youcanrepresentthatdirectlyintheformat,ratherthanusingajointable.
Notethatformanyapplications,afilesystemwillnotsuffice.Ifyouhaveahighvolumeofupdates,afilesystemmaygetconfusedorcorruptedbysimultaneouswrites;databasesusuallysupporttransactions,whichallowconcurrencywithoutcorruption.Further,adatabaseisanexcellenttoolifyouneedtomakecomplicatedqueries,especiallyiftheywillvaryfromtimetotime.Databasesbuildindexes,andareoptimizedforkeepingtheindexesuptodatewithaconstantlychangingdataset.Relationaldatabasesalsohavemanyotheradvantages,includingarichquerylanguage,matureauthoringandschemadesigntools,provenscalability,fine-grainedaccesscontrol,andsoon.
(Note:
Youcanusesimplefilelockingtoprovideapoorman'stransactionserver.AndyoucanalsoimplementanXMLindex-and-searchtoolinJava,butthat'satopicforanotherarticle.)
Inthiscase,asinmostlow-to-mediumvolume,publishing-basedWebsites,youcanassumethefollowing:
mostofthedataaccessisreads,notwrites;thedata,thoughpotentiallylarge,isrelativelyunchanging;youwon'tneedtodocomplicatedsearches,butifyoudo,you'lluseaseparatesearchengine.TheadvantagesofusingamatureRDBMSfade,whiletheadvantageofusinganobject-orienteddatamodelcometothefore.
Finally,it'sentirelypossibletoprovideawrapperforyourdatabasethatmakesSQLqueriesandtranslatesthemintoXMLstreams,soyoucouldhaveitbothways.XMLbecomesamorerobust,programmer-friendlyfrontendtoamaturedatabaseforstoringandsearching.(Oracle'sXSQLservletisoneexampleofthistechnique.)
Theapplication:
Anonlinephotoalbum
Everybodylovesphotos!
Peopleloveshowingpicturesofthemselves,theirfriends,theirpets,andtheirvacations.TheWebistheultimatemediumforself-indulgentshutterbugs--theycanannoytheirrelativesfromthousandsofmilesaway.Whileafull-fledgedphotoalbumsitewouldrequireacomplicatedobjectmodel,I'llfocusondefiningasinglePictureobject.(ThesourcecodeforthisapplicationisavailableinResources.)Theobjectrepresentingapictureneedsfieldsrepresentingitstitle,thedateitwastaken,anoptionalcaption,and,obviously,apointertotheimagesource.
Animage,inturn,needsafewfieldsofitsown:
thelocationofthesourcefile(aGIForJPEG)andtheheightandwidthinpixels(toassistyouinbuildingtags).Herethereisoneneatadvantagetousingthefilesystemasyourdatabase:
youcanstoretheimagefilesinthesamedirectoryasthedatafiles.
Finally,let'sextendthepicturerecordwithanelementdefiningasetofthumbnailimagesforuseinthetableofcontentsorelsewhere.HereIusethesameconceptofimageIdefinedearlier.
TheXMLrepresentationofapicturecouldlooksomethinglikethis:
AlexOnTheBeach1999-08-08
Tryinginvaintogetatan
alex-beach.jpg
340
200
alex-beach-sm.jpg
72
72
alex-beach-med.jpg
150
99
NotethatbyusingXML,youputalltheinformationaboutasinglepictureintoasinglefile,ratherthanscatteringitamongthreeorfourseparatetables.Let'scallthisa.pixfile--soyourfilesystemmightlooklikethis:
summer99/alex-beach.pix
summer99/alex-beach.jpg
summer99/alex-beach-sm.jpg
summer99/alex-beach-med.jpg
summer99/alex-snorkeling.pix
etc.
Techniques
There'smorethanonewaytoskinacat,andthere'smorethanonewaytobringXMLdataontoyourJSPpage.Hereisalistofsomeofthoseways.(Thislistisnotexhaustive;manyotherproductsandframeworkswouldserveequallywell.)
DOM:
YoucanuseclassesimplementingtheDOMinterfacetoparseandinspecttheXMLfile
XMLEntryList:
YoucanusemycodetoloadtheXMLintoajava.util.Listofname-valuepairs
XPath:
YoucanuseanXPathprocessor(likeResin)tolocateelementsintheXMLfilebypathname
XSL:
YoucanuseanXSLprocessortotransformtheXMLintoHTML
Cocoon:
YoucanusetheopensourceCocoonframework
Rollyourownbean:
YoucanwriteawrapperclassthatusesoneoftheothertechniquestoloadthedataintoacustomJavaBean
NotethatthesetechniquescouldbeappliedequallywelltoanXMLstreamyoureceivefromanothersource,suchasaclientoranapplicationserver.
JavaServerPages
TheJSPspechashadmanyincarnations,anddifferentJSPproductsimplementdifferent,incompatibleversionsofthespec.IwilluseTomcat,forthefollowingreasons:
Itsupportsthemostup-to-dateversionsoftheJSPandservletspecs
It'sendorsedbySunandApache
YoucanrunitstandalonewithoutconfiguringaseparateWebserver
It'sopensource
(FormoreinformationonTomcat,seeResources.)
YouarewelcometouseanyJSPengineyoulike,butconfiguringitisuptoyou!
BesurethattheenginesupportsatleasttheJSP1.0spec;thereweremanychangesbetween0.91and1.0.TheJSWDK(JavaServerWebDevelopmentKit)willworkjustfine.
TheJSPstructure
WhenbuildingaJSP-drivenWebsite(alsoknownasaWebapp),Iprefertoputcommonfunctions,imports,constants,andvariabledeclarationsinaseparatefilecalledinit.jsp,locatedinthesourcecodeforthisarticle.
IthenloadthatfileintoeachJSPfileusing<%@includefile="init.jsp"%>.The<%@include%>directiveactsliketheClanguage's#include,pullinginthetextoftheincludedfile(here,init.jsp)andcompilingitasifitwerepartoftheincludingfile(here,picture.jsp).Bycontrast,theinclude>tagcompilesthefileasaseparateJSPfileandembedsacalltoitinthecompiledJSP.
Findingthefile
WhentheJSPstarts,thefirstthingitneedstodoafterinitializationisfindtheXMLfileyouwant.Howdoesitknowwhichofthemanyfilesyouneed?
TheanswerisfromaCGIparameter.TheuserwillinvoketheJSPwiththeURLpicture.jsp?
file=summer99/alex-beach.pix(orbypassingafileparameterthroughanHTMLform).
However,whentheJSPreceivestheparameter,you'restillonlyhalfwaythere.Youstillneedtoknowwhereonthefilesystemtherootdirectorylies.Forexample,onaUnixsystem,theactualfilemaybeinthedirectory/home/alex/public_html/pictures/summer99/alex-beach.pix.JSPsdonothaveaconceptofacurrentdirectorywhileexecuting,soyouneedtoprovideanabsolutepathnametothejava.iopackage.
TheServletAPIprovidesamethodtoturnaURLpath,relativetothecurrentJSPorServlet,intoanabsolutefilesystempath.ThemethodServletContext.getRealPath(String)doesthetrick.EveryJSPhasaServletContextobjectcalledapplication,sothecodewouldbe:
Stringpicturefile=
application.getRealPath("/"+request.getParameter("file"));
or
Stringpicturefile=
getServletContext().getRealPath("/"+request.getParameter("file"));
whichalsoworksinsideaservlet.(Youmustappenda/becausethemethodexpectstobepassedtheresultsofrequest.getPathInfo().)
Oneimportantnote:
wheneveryouaccesslocalresources,beverycarefultovalidatetheincomingdata.Ahacker,oracarelessuser,cansendbogusdatatohackyoursite.Forinstance,considerwhatwouldhappenifthevaluefile=../../../../etc/passwdwereentered.Theusercouldinthiswayreadyourserver'spasswordfile.
TheDocumentObjectModel
DOMstandsfortheDocumentObjectModel.ItisastandardAPIforbrowsingXMLdocuments,developedbytheWorld