java-JDBC-外文翻譯-外文文獻-英文文獻_第1頁
java-JDBC-外文翻譯-外文文獻-英文文獻_第2頁
java-JDBC-外文翻譯-外文文獻-英文文獻_第3頁
java-JDBC-外文翻譯-外文文獻-英文文獻_第4頁
java-JDBC-外文翻譯-外文文獻-英文文獻_第5頁
已閱讀5頁,還剩16頁未讀 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

原文一:

JavaProgrammingwithOracleJDBC:Performance

Performanceisusuallyconsideredanissueattheendofadevelopmentcyclewhenitshouldreallybeconsideredfromthestart.Often,ataskcalled"performancetuning"isdoneafterthecodingiscomplete,andtheenduserofaprogramcomplainsabouthowlongittakestheprogramtocompleteaparticulartask.Thenetresultofwaitinguntiltheendofthedevelopmentcycletoconsiderperformanceincludestheexpenseoftheadditionaltimerequiredtorecodeaprogramtoimproveitsperformance.It'smyopinionthatperformanceissomethingthatisbestconsideredatthestartofaproject.

WhenitcomestoperformanceissuesconcerningJDBCprogrammingtherearetwomajorfactorstoconsider.ThefirstistheperformanceofthedatabasestructureandtheSQLstatementsusedagainstit.ThesecondistherelativeefficiencyofthedifferentwaysyoucanusetheJDBCinterfacestomanipulateadatabase.

Intermsofthedatabase'sefficiency,youcanusetheEXPLAINPLANfacilitytoexplainhowthedatabase'soptimizerplanstoexecuteyourSQLstatements.Armedwiththisknowledge,youmaydeterminethatadditionalindexesareneeded,orthatyourequireanalternativemeansofselectingthedatayoudesire.

Ontheotherhand,whenitcomestousingJDBC,youneedtoknowaheadoftimetherelativestrengthsandweaknessesofusingauto-commit,SQL92syntax,andaStatementversusaPreparedStatementversusaCallableStatementobject.Inthischapter,we'llexaminetherelativeperformanceofvariousJDBCobjectsusingexampleprogramsthatreporttheamountoftimeittakestoaccomplishagiventask.We'llfirstlookatauto-commit.Next,we'lllookattheimpactoftheSQL92syntaxparser.Thenwe'llstartaseriesofcomparisonsoftheStatementobjectversusthePreparedStatementobjectversustheCallableStatementobject.Atthesametimewe'llalsoexaminetheperformanceoftheOCIversustheThindriverineachsituationtoseeif,asOracle'sclaims,thereisasignificantenoughperformancegainwiththeOCIdriverthatyoushoulduseitinsteadoftheThindriver.Forthemostpart,ourdiscussionswillbebasedontimingdatafor1,000insertsintothetestperformancetableTESTXXXPERF.Thereareseparateprogramsforperformingthese1,000insertsusingtheOCIdriverandtheThindriver.

Theperformancetestprogramsthemselvesareverysimpleandareavailableonlinewiththerestoftheexamplesinthisbook.However,forbrevity,I'llnotshowthecodefortheexamplesinthischapter.I'llonlytalkaboutthem.Althoughtheactualtimingvalueschangefromsystemtosystem,theirrelativevalues,orratiosfromonesystemtoanother,remainconsistent.ThetimingsusedinthischapterweregatheredusingWindows2000.Usingobjectivedatafromtheseprogramsallowsustocometofactualconclusionsonwhichfactorsimproveperformance,ratherthanrelyingonhearsay.

I'msureyou'llbesurprisedattherealityofperformancefortheseobjects,andIhopeyou'llusethisknowledgetoyouradvantage.Let'sgetstartedwithalookatthetestingframeworkusedinthischapter.

ATestingFramework

Forthemostpart,thetestprogramsinthischapterreportthetimingsforinsertingdataintoatable.IpickedanINSERTstatementbecauseiteliminatestheperformancegainofthedatabaseblockbuffersthatmayskewtimingsforanUPDATE,DELETE,orSELECT.

Thetesttableusedintheexampleprogramsinthischapterisasimplerelationaltable.IwantedittohaveaNUMBER,asmallVARCHAR2,alargeVARCHAR2,andaDATEcolumn.TableTESTXXXPERFisdefinedas:

createtableTestXXXPerf(

idnumber,

codevarchar2(30),

descrvarchar2(80),

insert_uservarchar2(30),

insert_datedate)

tablespaceuserspctfree20

storage(initial1Mnext1Mpctincrease0);

altertableTestXXXPerf

addconstraintTestXXXPerf_Pk

primarykey(id)

usingindex

tablespaceuserspctfree20

storage(initial1Mnext1Mpctincrease0);

Theinitialextentsizeusedforthetablemakesitunlikelythatthedatabasewillneedtotakethetimetoallocateanotherextentduringtheexecutionofoneofthetestprograms.Therefore,extentallocationwillnotimpactthetimings.Giventhisbackground,youshouldhaveacontexttounderstandwhatisdoneineachsectionbyeachtestprogram.

Auto-Commit

Bydefault,JDBC'sauto-commitfeatureison,whichmeansthateachSQLstatementiscommittedasitisexecuted.IfmorethanoneSQLstatementisexecutedbyyourprogram,thenasmallperformanceincreasecanbeachievedbyturningoffauto-commit.

Let'stakealookatsomenumbers.

Table19-1

showstheaveragetime,inmilliseconds,neededtoinsert1,000rowsintotheTESTXXXPERFtableusingaStatementobject.Thetimingsrepresenttheaveragefromthreerunsoftheprogram.Bothdriversexperienceapproximatelyaone-secondlossasoverheadforcommittingbetweeneachSQLstatement.Whenyoudividethatonesecondby1,000inserts,youcanseethatturningoffauto-commitsavesapproximately0.001seconds(1millisecond)perSQLstatement.Whilethat'snotinterestingenoughtowritehomeabout,itdoesdemonstratehowauto-commitcanimpactperformance.

Table19-1:Auto-committimings(inmilliseconds)

Auto-commit

OCI

Thin

On

3,712

3,675

Off

2,613

2,594

Clearly,it'smoreimportanttoturnoffauto-commitformanagingmultisteptransactionsthanforgainingperformance.Butonaheavilyloadedsystemwheremanyusersarecommittingtransactions,theamountoftimeittakestoperformcommitscanbecomequitesignificant.Somyrecommendationistoturnoffauto-commitandmanageyourtransactionsmanually.Therestofthetestsinthischapterareperformedwithauto-committurnedoff.

SQL92TokenParsing

Likeauto-commit,SQL92escapesyntaxtokenparsingisonbydefault.Incaseyoudon'trecall,SQL92tokenparsingallowsyoutoembedSQL92escapesyntaxinyourSQLstatements(see"OracleandSQL92EscapeSyntax"inChapter9).Thesestandards-basedsnippetsofsyntaxareparsedbyaJDBCdrivertransformingtheSQLstatementintoitsnativesyntaxforthetargetdatabase.SQL92escapesyntaxallowsyoutomakeyourcodemoreportable--butdoesthisportabilitycomewithacostintermsofperformance?

Table19-2showsthenumberofmillisecondsneededtoinsert1,000rowsintotheTESTXXXPERFtable.TimingsareshownwiththeSQL92escapesyntaxparseronandoffforboththeOCIandThindrivers.Asbefore,thesetimingsrepresenttheresultofthreeprogramrunsaveragedtogether.

Table19-2:SQL92tokenparsertimings(inmilliseconds)

SQL92parser

OCI

Thin

On

2,567

2,514

Off

2,744

2,550

NoticefromTable19-2thatwiththeOCIdriverwelose177millisecondswhenescapesyntaxparsingisturnedoff,andweloseonly37millisecondswhentheparseristurnedoffwiththeThindriver.Theseresultsaretheoppositeofwhatyoumightintuitivelyexpect.ItappearsthatbothdrivershavebeenoptimizedforSQL92parsing,soyoushouldleaveitonforbestperformance.

NowthatyouknowyouneverhavetoworryaboutturningtheSQL92parseroff,let'smoveontosomethingthathassomepotentialforprovidingasubstantialperformanceimprovement.

StatementVersusPreparedStatement

There'sapopularbeliefthatusingaPreparedStatementobjectisfasterthanusingaStatementobject.Afterall,apreparedstatementhastoverifyitsmetadataagainstthedatabaseonlyonce,whileastatementhastodoiteverytime.Sohowcoulditbeanyotherway?Well,thetruthofthematteristhatittakesabout65iterationsofapreparedstatementbeforeitstotaltimeforexecutioncatchesupwithastatement.WhenitcomestowhichSQLstatementobjectperformsbetterundertypicaluse,aStatementoraPreparedStatement,thetruthisthattheStatementobjectyieldsthebestperformance.WhenyouconsiderhowSQLstatementsaretypicallyusedinanapplication--1or2here,maybe10-20(rarelymore)pertransaction--yourealizethataStatementobjectwillperformtheminlesstimethanaPreparedStatementobject.Inthenexttwosections,we'lllookatthisperformanceissuewithrespecttoboththeOCIdriverandtheThindriver.

TheOCIDriver

Table19-3

showsthetimingsinmillisecondsfor1insertand1,000insertsintheTESTXXXPERFtable.TheinsertsaredonefirstusingaStatementobjectandthenaPreparedStatementobject.Ifyoulookattheresultsfor1,000inserts,youmaythinkthatapreparedstatementperformsbetter.Afterall,at1,000inserts,thePreparedStatementobjectisalmosttwiceasfastastheStatementobject,butifyouexamine

Figure19-1

,you'llseeadifferentstory.

Table19-3:OCIdrivertimings(inmilliseconds)

Inserts

Statement

PreparedStatement

1

10

113

1,000

2,804

1,412

Figure19-1isagraphofthetimingsneededtoinsertvaryingnumbersofrowsusingbothaStatementobjectandaPreparedStatementobject.Thenumberofinsertsbeginsat1andclimbsinintervalsof10uptoamaximumof150inserts.Forthisgraphandforthosethatfollow,thelinesthemselvesarepolynomialtrendlineswithafactorof2.Ichosepolynomiallinesinsteadofstraighttrendlinessoyoucanbetterseeachangeintheperformanceasthenumberofinsertsincreases.Ichoseafactorof2sothelineshaveonlyonecurveinthem.Theimportantthingtonoticeaboutthegraphisthatit'snotuntilabout65insertsthatthePreparedStatementobjectoutperformstheStatementobject.65inserts!Clearly,theStatementobjectismoreefficientundertypicalusewhenusingtheOCIdriver.

Figure19-1

TheThinDriver

IfyouexamineTable19-4(whichshowsthesametimingsasforTable19-3,butfortheThindriver)andFigure19-2(whichshowsthedataincrementally),you'llseethattheThindriverfollowsthesamebehaviorastheOCIdriver.However,sincetheStatementobjectstartsoutperformingbetterthanthePreparedStatementobject,ittakesabout125insertsforthePreparedStatementtooutperformStatement.

Table19-4:Thindrivertimings(inmilliseconds)

Inserts

Statement

PreparedStatement

1

10

113

1,000

2,583

1,739

Figure19-2

WhenyouconsidertypicalSQLstatementusage,evenwiththeThindriver,you'llgetbetterperformanceifyouexecuteyourSQLstatementsusingaStatementobjectinsteadofaPreparedStatementobject.Giventhat,youmayask:whyuseaPreparedStatementatall?ItturnsoutthattherearesomereasonswhyyoumightuseaPreparedStatementobjecttoexecuteSQLstatements.First,thereareseveraltypesofoperationsthatyousimplycan'tperformwithoutPreparedStatementobject.Forexample,youmustuseaPreparedStatementobjectifyouwanttouselargeobjectslikeBLOBsorCLOBsorifyouwishtouseobjectSQL.Essentially,youtradesomelossofperformancefortheaddedfunctionalityofusingtheseobjecttechnologies.AsecondreasontouseaPreparedStatementisitssupportforbatching.

Batching

Asyousawintheprevioussection,PreparedStatementobjectseventuallybecomemoreefficientthantheirStatementcounterpartsafter65-125executionsofthesamestatement.Ifyou'regoingtoexecuteagivenSQLstatementalargenumberoftimes,itmakessensefromaperformancestandpointtouseaPreparedStatementobject.Butifyou'rereallygoingtodothatmanyexecutionsofastatement,orperhapsmorethan50,youshouldconsiderbatching.BatchingismoreefficientbecauseitsendsmultipleSQLstatementstotheserveratonetime.AlthoughJDBCdefinesbatchingcapabilityforStatementobjects,OraclesupportsbatchingonlywhenPrepared-Statementobjectsareused.Thismakessomesense.ASQLstatementinaPreparedStatementobjectisparsedonceandcanbereusedmanytimes.Thisnaturallylendsitselftobatching.

TheOCIDriver

Table19-5listsStatementandbatchedPreparedStatementtimings,inmilliseconds,for1insertandfor1,000inserts.Atthelowend,oneinsert,youtakeasmallperformancehitforsupportingbatching.Atthehighend,1,000inserts,you'vegained75%throughput.

Table19-5:OCIdrivertimings(inmilliseconds)

Inserts

Statement

Batched

1

10

117

1,000

2,804

691

IfyouexamineFigure19-3,atrendlineanalysisoftheStatementobjectversusthebatchedPreparedStatementobject,you'llseethatthistime,thebatchedPrepared-StatementobjectbecomesmoreefficientthantheStatementobjectatabout50inserts.Thisisanimprovementoverthepreparedstatementwithoutbatching.

Figure19-3

WARNING:There'sacatchhere.The8.1.6OCIdriverhasadefectbywhichitdoesnotsupportstandardJavabatching,sothenumbersreportedherewerederivedusingOracle'sproprietarybatching.

Now,let'stakealookatbatchinginconjunctionwiththeThindriver.

TheThinDriver

TheThindriverisevenmoreefficientthantheOCIdriverwhenitcomestousingbatchedpreparedstatements.Table19-6showsthetimingsfortheThindriverusingaStatementobjectversusabatchedPreparedStatementobjectinmillisecondsforthespecifiednumberofinserts.

Table19-6:Thindrivertimings(inmilliseconds)

Inserts

Statement

Batched

1

10

117

1,000

2,583

367

TheThindrivertakesthesameperformancehitonthelowend,oneinsert,butgainsawhopping86%improvementonthehighend.Yes,1,000insertsinlessthanasecond!IfyouexamineFigure19-4,you'llseethatwiththeThindriver,theuseofabatchedPreparedStatementobjectbecomesmoreefficientthanaStatementobjectmorequicklythanwiththeOCIdriver--atabout40inserts.

Figure19-4

IfyouintendtoperformmanyiterationsofthesameSQLstatementagainstadatabase,youshouldconsiderbatchingwithaPreparedStatementobject.

We'vefinishedlookingatimprovingtheperformanceofinserts,updates,anddeletes.Nowlet'sseewhatwecandotosqueakoutalittleperformancewhileselectingdata.

PredefinedSELECTStatements

EverytimeyouexecuteaSELECTstatement,theJDBCdrivermakestworoundtripstothedatabase.Onthefirstroundtrip,itretrievesthemetadataforthecolumnsyouareselecting.Onthesecondroundtrip,itretrievestheactualdatayouselected.Withthisinmind,youcanimprovetheperformanceofaSELECTstatementby50%ifyoupredefinetheSelecstatementbyusingOracle'sdefineColumnType()methodwithanOracleStatementobject(see"DefiningColumns"inChapter9).WhenyoupredefineaSELECTstatement,youprovidetheJDBCdriverwiththecolumnmetadatausingthedefineColumnType()method,obviatingtheneedforthedrivertomakearoundtriptothedatabaseforthatinformation.Hence,forasingletonSELECT,youeliminatehalftheworkwhenyoupredefinethestatement.

Table19-7showsthetimingsinmillisecondsrequiredtoselectasinglerowfromtheTESTXXXPERFtable.Timingsareshownforwhenthecolumntypehasbeenpredefinedandwhenithasnotbeenpredefined.TimingsareshownforboththeOCIandThindrivers.AlthoughthedefineColumnType()methodshowslittleimprovementwitheitherdriverinmytest,onaloadednetwork,you'llseeadifferentiationinthetimingsofabout50%.GivenasituationinwhichyouneedtomakeseveraltightcallstothedatabaseusingaStatement,apredefinedSELECTstatementcansaveyouasignificantamountoftime.

Table19-7:Selecttimings(inmilliseconds)

Driver

Statement

defineColumnType()

OCI

13

10

Thin

13

10

Nowthatwe'velookedatauto-commit,SQL92parsing,preparedstatements,andapredefinedSELECT,let'stakealookattheperformanceofcallablestatements.

CallableStatements

Asyoumayrecall,CallableStatementobjectsareusedtoexecutedatabasestoredprocedures.I'vesavedCallableStatementobjectsuntillast,becausetheyaretheslowestperformersofalltheJDBCSQLexecutioninterfaces.Thismaysoundcounterintuitive,becauseit'scommonlybelievedthatcallingstoredproceduresisfasterthanusingSQL,butthat'ssimplynottrue.GivenasimpleSQLstatement,andastoredprocedurecallthataccomplishesthesametask,thesimpleSQLstatementwillalwaysexecutefaster.Why?Becausewiththestoredprocedure,younotonlyhavethetimeneededtoexecutetheSQLstatementbutalsothetimeneededtodealwiththeoverheadoftheprocedurecallitself.

Table19-8liststherelativetime,inmilliseconds,neededtocallthestoredprocedureTESTXXXPERF$.SETTESTXXXPERF().ThisstoredprocedureinsertsonerowintothetableTESTXXXPERF.TimingsareprovidedforboththeOCIandThindrivers.Noticethatbothdriversareslowerwheninsertingarowthiswaythanwhenusingeitherastatementorabatchedpreparedstatement(refertoTables19-3through19-6).Commonsensewilltellyouwhy.TheSETTESTXXXPERF()procedureinsertsarowintothedatabase.ItdoesexactlythesamethingthattheotherJDBCobjectsdidbutwiththeaddedoverheadofaroundtripforexecutingtheremoteprocedurecall.

Table19-8:Storedprocedurecalltimings(inmilliseconds)

Inserts

OCI

Thin

1

113

117

1,000

1,723

1,752

Storedproceduresdohavetheiruses.IfyouhaveacomplextaskthatrequiresseveralSQLstatementstocomplete,andyouencapsulatethoseSQLstatementsintoastoredprocedurethatyouthencallonlyonce,you'llgetbetterperformancethanifyouexecutedeachSQLstatementseparatelyfromyourprogram.Thisperformancegainistheresultofyourprogramnothavingtomovealltherelateddatabackandforthoverthenetwork,whichisoftentheslowestpartofthedatamanipulationprocess.ThisishowstoredproceduresaresupposedtobeusedwithOracle--notasasubstituteforSQL,butasameanstoperformworkwhereitcanbedonemostefficiently.

OCIVersusThinDrivers

Oracle'sdocumentationstatesthatyoushouldusetheOCIdriverformaximumperformanceandtheThindriverformaximumportability.However,IrecommendusingtheThindriverallthetime.Let'stakealookatsomenumbersfromWindows2000.Table19-9listsallthestatisticswe'vecoveredinthischapter.

Table19-9:OCIversusThindrivertimings(inmilliseconds)

Metric

OCI

Thin

1,000insertswithauto-commit

3,712

3,675

1,000insertswithmanualcommit

2,613

2,594

1insertwithStatement

10

10

1,000insertswithStatement

2,804

2,583

1insertwithPreparedStatement

113

113

1,000insertsbatched

1,482

367

SELECT

10

10

PredefinedSELECT

10

10

1insertwithCallableStatement

113

117

1,000insertswithCallableStatement

1,723

1,752

Totals

12,590

11,231

AsyoucanseefromTable19-9,theThindriverclearlyoutperformstheOCIdriverforeverytypeofoperationexceptexecutionsofCallableStatementobjects.OnaUnixplatform,myexperiencehasbeenthattheCallableStatementnumbersaretiltedevenmoreinfavoroftheOCIdriver.Nonetheless,youcanfeelcompletelycomfortableusingtheThindriverinalmostanysetting.TheThindriverhasbeenwell-tunedbyOracle'sJDBCdevelopmentteamtoperformbetterthanitsOCIcounterpart.

原文二:

ExtendingStruts

Introduction

IhaveseenlotofprojectswherethedevelopersimplementedaproprietaryMVCframework,notbecausetheywantedtodosomethingfundamentallydifferentfromStruts,butbecausetheywerenotawareofhowtoextendStruts.YoucangettotalcontrolbydevelopingyourownMVCframework,butitalsomeansyouhavetocommitalotofresourcestoit,somethingthatmaynotbepossibleinprojectswithtightschedules.

Struts

isnotonlyaverypowerfulframework,butalsoveryextensible.YoucanextendStrutsinthreeways.

PlugIn:CreateyourownPlugInclassifyouwanttoexecutesomebusinesslogicatapplicationstartuporshutdown.

RequestProcessor:CreateyourownRequestProcessorifyouwanttoexecutesomebusinesslogicataparticularpointduringtherequest-processingphase.Forexample,youmightextendRequestProcessortocheckthattheuserisloggedinandhehasoneoftherolestoexecuteaparticularactionbeforeexecutingeveryrequest.

ActionServlet:YoucanextendtheActionServletclassifyouwanttoexecuteyourbusinesslogicateitherapplicationstartuporshutdown,orduringrequestprocessing.ButyoushoulduseitonlyincaseswhereneitherPlugInnorRequestProcessorisabletofulfillyourrequirement.

Inthisarticle,wewilluseasampleStrutsapplicationtodemonstratehowtoextendStrutsusingeachofthesethreeapproaches.Downloadablesamplecodeforeachisavailablebelowinthe

Resources

sectionattheendofthisarticle.TwoofthemostsuccessfulexamplesofStrutsextensionsarethe

StrutsValidation

frameworkandthe

Tiles

framework.

IassumethatyouarealreadyfamiliarwiththeStrutsframeworkandknowhowtocreatesimpleapplicationsusingit.Pleaseseethe

Resources

sectionifyouwanttoknowmoreaboutStruts.

PlugIn

AccordingtotheStrutsdocumentation"Apluginisaconfigurationwrapperforamodule-specificresourceorservicethatneedstobenotifiedaboutapplicationstartupandshutdownevents."WhatthismeansisthatyoucancreateaclassimplementingthePlugIninterfacetodosomethingatapplicationstartuporshutdown.

SayIamcreatingawebapplicationwhereIamusingHibernateasthepersistencemechanism,andIwanttoinitializeHibernateassoonastheapplicationstartsup,sothatbythetimemywebapplicationreceivesthefirstrequest,Hibernateisalreadyconfiguredandreadytouse.WealsowanttoclosedownHibernatewhentheapplicationisshuttingdown.WecanimplementthisrequirementwithaHibernatePlugInbyfollowingtwosimplesteps.

CreateaclassimplementingthePlugIninterface,likethis:

publicclassHibernatePlugInimplementsPlugIn{

privateStringconfigFile;

//Thismethodwillbecalledatapplicationshutdowntime

publicvoiddestroy(){

System.out.println("EnteringHibernatePlugIn.destroy()");

//Puthibernatecleanupcodehere

System.out.println("ExitingHibernatePlugIn.destroy()");

}

//Thismethodwillbecalledatapplicationstartuptime

publicvoidinit(ActionServletactionServlet,ModuleConfigconfig)

throwsServletException{

System.out.println("EnteringHibernatePlugIn.init()");

System.out.println("Valueofinitparameter"+

getConfigFile());

System.out.println("ExitingHibernatePlugIn.init()");

}

publicStringgetConfigFile(){

returnname;

}

publicvoidsetConfigFile(Stringstring){

configFile=string;

}

}

TheclassimplementingPlugIninterfacemustimplementtwomethods:init()anddestroy().init()iscalledwhentheapplicationstartsup,anddestroy()iscalledatshutdown.StrutsallowsyoutopassinitparameterstoyourPlugInclass.Forpassingparameters,youhavetocreateJavaBean-typesettermethodsinyourPlugInclassforeveryparameter.InourHibernatePlugInclass,IwantedtopassthenameoftheconfigFileinsteadofhard-codingitintheapplication.

InformStrutsaboutthenewPlugInbyaddingtheselinestostruts-config.xml:

<struts-config>

<!--MessageResources-->

<message-resourcesparameter=

"sample1.resources.ApplicationResources"/>

<plug-inclassName="com.sample.util.HibernatePlugIn">

<set-propertyproperty="configFile"

value="/hibernate.cfg.xml"/>

</plug-in>

</struts-config>

TheclassNameattributeisthefullyqualifiednameoftheclassimplementingthePlugIninterface.Adda<set-property>elementforeveryinitializationparameterwhichyouwanttopasstoyourPlugInclass.Inourexample,Iwantedtopassthenameoftheconfigfile,soIaddedthe<set-property>elementwiththevalueofconfigfilepath.

BoththeTilesandValidatorframeworksusePlugInsforinitializationbyreadingconfigurationfiles.TwomorethingswhichyoucandoinyourPlugInclassare:

Ifyourapplicationdependsonsomeconfigurationfiles,thenyoucanchecktheiravailabilityinthePlugInclassandthrowaServletExceptioniftheconfigurationfileisnotavailable.ThiswillresultinActionServletbecomingunavailable.

ThePlugIninterface'sinit()methodisyourlastchanceifyouwanttochangesomethinginModuleConfig,whichisacollectionofstaticconfigurationinformationthatdescribesaStruts-basedmodule.StrutswillfreezeModuleConfigonceallPlugInsareprocessed.

HowaRequestisProcessed

ActionServletistheonlyservletinStrutsframework,andisresponsibleforhandlingalloftherequests.Wheneveritreceivesarequest,itfirsttriestofindasub-applicationforthecurrentrequest.Onceasub-applicationisfound,itcreatesaRequestProcessorobjectforthatsub-applicationandcallsitsprocess()methodbypassingitHttpServletRequestandHttpServletResponseobjects.

TheRequestPcess()iswheremostoftherequestprocessingtakesplace.Theprocess()methodisimplementedusingtheTemplateMethoddesignpattern,inwhichthereisaseparatemethodforperformingeachstepofrequestprocessing,andallofthosemethodsarecalledinsequencefromtheprocess()method.Forexample,thereareseparatemethodsforfindingtheActionFormclassassociatedwiththecurrentrequest,andcheckingifthecurrentuserhasoneoftherequiredrolestoexecuteactionmapping.Thisgivesustremendousflexibility.TheRequestProcessorclassintheStrutsdistributionprovidesadefaultimplementationforeachoftherequest-processingsteps.Thatmeansyoucanoverrideonlythemethodsthatinterestyou,andusedefaultimplementationsforrestofthemethods.Forexample,bydefaultStrutscallsrequest.isUserInRole()tofindoutiftheuserhasoneoftherolesrequiredtoexecutethecurrentActionMapping,butifyouwanttoqueryadatabaseforthis,thenthenallyouhavetodoisoverridetheprocessRoles()methodandreturntrueorfalse,basedwhethertheuserhastherequiredroleornot.

Firstwewillseehowtheprocess()methodisimplementedbydefault,andthenIwillexplainwhateachmethodinthedefaultRequestProcessorclassdoes,sothatyoucandecidewhatpartsofrequestprocessingyouwanttochange.

publicvoidprocess(HttpServletRequestrequest,

HttpServletResponsere

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論