计算机外文翻译 XML与JSP联手.docx
- 文档编号:28779989
- 上传时间:2023-07-19
- 格式:DOCX
- 页数:14
- 大小:26.18KB
计算机外文翻译 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:
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,the include>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
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 计算机外文翻译 XML与JSP联手 计算机 外文 翻译 XML JSP 联手