计算机专业文献翻译XML与JSP联手Word文档格式.docx
《计算机专业文献翻译XML与JSP联手Word文档格式.docx》由会员分享,可在线阅读,更多相关《计算机专业文献翻译XML与JSP联手Word文档格式.docx(11页珍藏版)》请在冰豆网上搜索。
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(toassistyouinbuilding<
img>
tags).Herethereisoneneatadvantagetousingthefilesystemasyourdatabase:
youcanstoretheimagefilesinthesamedirectoryasthedatafiles.
Finally,let'
sextendthepicturerecordwithanelementdefiningasetofthumbnailimagesforuseinthetableofcontentsorelsewhere.HereIusethesameconceptofimageIdefinedearlier.
TheXMLrepresentationofapicturecouldlooksomethinglikethis:
<
picture>
<
title>
AlexOnTheBeach<
/title>
date>
1999-08-08<
/date>
caption>
Tryinginvaintogetatan<
/caption>
image>
src>
alex-beach.jpg<
/src>
width>
340<
/width>
height>
200<
/height>
/image>
thumbnails>
alex-beach-sm.jpg<
72<
alex-beach-med.jpg<
150<
99<
/thumbnails>
/picture>
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
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<
jsp:
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
getServletContext().getRealPath("
whichalsoworksinsideaservlet.(Youmustappenda/becausethemethodexpectstobepassedtheresultsofrequest.getPathInfo().)
Oneimportantnote:
wheneveryouaccesslocalresources,beverycarefultovalidatetheincomingdata.Ahacker,oracarelessuser,cansendbogusdatatohackyoursite.Forinstance,considerwhatwouldhappenifthevaluefile=../../../../etc/passwdwereentered.Theusercouldinthiswayreadyourserver'
spasswordfile.
TheDocumentObjectModel
DOMstandsfortheDocumentObjectModel.ItisastandardAPIforbrowsingXMLdocuments,developedbytheWorld