Tải bản đầy đủ (.pdf) (0 trang)

Addison wesley javaserver pages 2nd edition aug 2003 ISBN 0321150791

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.99 MB, 0 trang )




TableofContents
Examples

JavaServerPages™,SecondEdition
ByLarnePekowsky
Publisher :AddisonWesley
PubDate :August15,2003
ISBN :0-321-15079-1
Pages :368

Sincebeingintroducedin1999,JavaServer
Pages(TM)(JSP)havebecomeapopularand
importanttechnologyforbuildingdynamic,
interactive,content-richWebsites.JavaServer
Pages(TM),SecondEditionisahands-onguideto
workingwithJSP,offeringtheeasiestandmost
efficientwaysfornon-programmersandWeb
designerstocreatesophisticated,dynamicsites.
Programmerscanalsoutilizethisbookto
independentlycreatenewdynamiccomponents.


Thissecondeditioncoversthelatestreleaseofthe
JSPspecification(2.0),manystandardextensions
toJSPs,andanumberofbestpracticesthathave
beendevelopedsincethepublicationofthefirst
edition.
Thisbookalsooffersoverviewsofsomerelated


technologies,including:
JavaBeans(TM)


Servlets
JavaServerPagesStandardTagLibrary(JSTL)


JakartaStruts


Databases
JavaServerPages(TM),SecondEditioncontainsall
theinformationnecessarytostartwritingJSP-for
anyonewhohasacomputerandcanwriteHTML.It
includespractical,Java-basedtechniquesfor
maintainingandpersonalizinginformation-richWeb
sites,aswellasexamplesbasedonJakartaStruts,
thenewJSPtoolkit.Recentupdatesprovidea
numberofnewtoolsandtechniquesthatwillallow
readerstogetthemostproductivityfromJSPs,with
theleastamountofeffort.







TableofContents

Examples

JavaServerPages™,SecondEdition
By

LarnePekowsky

Publisher :AddisonWesley
PubDate :August15,2003
ISBN :0-321-15079-1
Pages :368

Copyright
Preface
Acknowledgements
Chapter1.
Introduction
Section1.1.
ABriefHistoryoftheWeb
Section1.2.
BasicDynamicPageGeneration
Section1.3.


SolvingCGIProblems
Section1.4.
WelcometoJavaNewsToday
Section1.5.
TryingtheExamples


Chapter2.
SimpleJSPs
Section2.1.
RemovingTextfromaJSP
Section2.2.
JSPErrors
Section2.3.
IncludingTextinaJSP
Section2.4.
ThePhasesofaJSP
Section2.5.
CreatingCustomErrorPages
Section2.6.
JavaNewsToday
Section2.7.
SummaryandConclusions
Section2.8.
TagsLearnedinThisChapter

Chapter3.
UsingBeans
Section3.1.
SplittingBigTasksintoManageablePieces


Section3.2.
DefiningBeans
Section3.3.
JavaBeanTags
Section3.4.

MakingDataAvailableThroughoutanApplication
Section3.5.
SpecialActionsWhenBeansAreCreated
Section3.6.
MakingBeansLastForever
Section3.7.
JavaNewsTodayandBeans
Section3.8.
FutureDirections
Section3.9.
SummaryandConclusions
Section3.10.
TagsLearnedinThisChapter

Chapter4.
TheStandardTagLibrary
Section4.1.
TagLibraries
Section4.2.
TagswithBodies
Section4.3.
DynamicAttributesinTags
Section4.4.


DisplayingExpressions
Section4.5.
FormattingOutput
Section4.6.
CompoundDataintheExpressionLanguage

Section4.7.
BrowserDetection
Section4.8.
CombiningTags
Section4.9.
SelectingamongMultipleChoices
Section4.10.
SummaryandConclusions
Section4.11.
TagsLearnedinthisChapter

Chapter5.
JavaNewsToday:PartI
Section5.1.
TheBeans
Section5.2.
TheHeader
Section5.3.
TheLeft-HandNavigation
Section5.4.
TheLoginPage
Section5.5.
TheQuizResultPage


Section5.6.
TheSectionPage
Section5.7.
TheArticlePage
Section5.8.

TheRemainingPages
Section5.9.
SummaryandConclusions
Section5.10.
TagsLearnedinthisChapter

Chapter6.
Databases
Section6.1.
AQuickIntroductiontoDatabases
Section6.2.
ALanguageforDatabases
Section6.3.
UsingSQLDirectlyfromJSPs
Section6.4.
InsertingDatafromJSPs
Section6.5.
SQLandBeans
Section6.6.
SummaryandConclusions
Section6.7.
TagsLearnedinThisChapter

Chapter7.


JavaNewsToday:Part2
Section7.1.
DesigningtheTables
Section7.2.

AddingArticles
Section7.3.
UserPages
Section7.4.
OtherUserPreferences
Section7.5.
Advertising
Section7.6.
SummaryandConclusions

Chapter8.
WorkingwithXML
Section8.1.
ABriefIntroductiontoXML
Section8.2.
UsingXMLinJSPs
Section8.3.
SelectingDatafromanXMLDocument
Section8.4.
ProcessingXMLinJSPs
Section8.5.
FormattingXML
Section8.6.
JavaNewsTodayandXML


Section8.7.
SummaryandConclusions
Section8.8.
TagsLearnedinthisChapter


Chapter9.
ASmallCupofJava
Section9.1.
Expressions
Section9.2.
Types
Section9.3.
StoringValues
Section9.4.
MethodCalls
Section9.5.
ConditionallyEvaluatingCode
Section9.6.
EvaluatingtheSameCodeMultipleTimes
Section9.7.
GroupingCode
Section9.8.
HandlingErrors
Section9.9.
ModelingaProblemwithObjects
Section9.10.
ObjectsinJava
Section9.11.
BuildingObjectsfromClasses


Section9.12.
SometimesNothingIsSomething
Section9.13.

BuildingClassesfromOtherClasses
Section9.14.
Interfaces
Section9.15.
CreatingGroupsofClassesandInterfaces
Section9.16.
UsingJavainJSPs
Section9.17.
DatabaseAccessfromJava
Section9.18.
SummaryandConclusions

Chapter10.
WritingBeans
Section10.1.
HowBeansAreImplemented
Section10.2.
AutomaticTypeConversion
Section10.3.
HowBeansWork
Section10.4.
BeanSerialization
Section10.5.
Events
Section10.6.


SpecialEvents
Section10.7.
BeanErrors

Section10.8.
SummaryandConclusions

Chapter11.
Servlets
Section11.1.
TheServletLifeCycle
Section11.2.
TheServletClassHierarchy
Section11.3.
ServletEvents
Section11.4.
ForwardingandIncludingRequests
Section11.5.
UsingScopesfromServlets
Section11.6.
UsingBeansfromServlets
Section11.7.
TheJSPClasses
Section11.8.
InterceptingRequests
Section11.9.
SummaryandConclusions

Chapter12.
TheController


Section12.1.
SomeCommonControllerTasks

Section12.2.
SupportforControllers:Struts
Section12.3.
SummaryandConclusions

Chapter13.
CreatingNewTagLibraries
Section13.1.
TheTagLifeCycle
Section13.2.
TagswithoutBodies
Section13.3.
TagswithBodies
Section13.4.
UsingtheExpressionLanguage
Section13.5.
JSPsasCustomTags
Section13.6.
SummaryandConclusions

Chapter14.
AdvancedTopics
Section14.1.
DeclaringVariablesandMethods
Section14.2.
ExtendingDifferentClasses
Section14.3.


ReturningOtherKindsofData

Section14.4.
Threads
Section14.5.
AdvancedErrorHandling
Section14.6.
SummaryandConclusions

AppendixA.
SummaryofTags
SectionA.1.
Built-inTags
SectionA.2.
CoreTags
SectionA.3.
Format,Parsing,andInternationalizationTags
SectionA.4.
SQLTags
SectionA.5.
XMLTags

AppendixB.
ConfiguringaWebApplication
SectionB.1.
LayoutoftheDirectories
SectionB.2.
TheWeb.xmlFile

[Tea79mefd1"tml"_toPm·ious"href="src=][



Tea79mefd1"tml"_toNext"href="src=]piif"
widta>dyS/p"ÙxwidGIF89aôÐ÷




[TeamLiB]


Copyright
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Wherethose
designationsappearinthisbook,andAddison-Wesleywasawareofa
trademarkclaim,thedesignationshavebeenprintedwithinitialcapital
lettersorinallcapitals.
Theauthorandpublisherhavetakencareinthepreparationofthisbook,
butmakenoexpressedorimpliedwarrantyofanykindandassumeno
responsibilityforerrorsoromissions.Noliabilityisassumedforincidental
orconsequentialdamagesinconnectionwithorarisingoutoftheuseof
theinformationorprogramscontainedherein.
Thepublisheroffersdiscountsonthisbookwhenorderedinquantityfor
bulkpurchasesandspecialsales.Formoreinformation,pleasecontact:
U.S.CorporateandGovernmentSales
(800)382-3419

ForsalesoutsideoftheU.S.,pleasecontact:
InternationalSales
(317)581-3793

VisitAddison-WesleyontheWeb:www.awprofessional.com

LibraryofCongressControlNumber:2003110544
Copyright©2004byPearsonEducation,Inc.
Allrightsreserved.Nopartofthispublicationmaybereproduced,stored
inaretrievalsystem,ortransmitted,inanyform,orbyanymeans,
electronic,mechanical,photocopying,recording,orotherwise,withoutthe
priorconsentofthepublisher.PrintedintheUnitedStatesofAmerica.


PublishedsimultaneouslyinCanada.
Forinformationonobtainingpermissionforuseofmaterialfromthis
work,pleasesubmitawrittenrequestto:
PearsonEducation,Inc.
RightsandContractsDepartment
75ArlingtonStreet,Suite300
Boston,MA02116
Fax:(617)848-7047
Textprintedonrecycledpaper.
12345678910CRS0706050403
Firstprinting,August2003

Dedication
Asalways,formyfriendswhoencouragedmebefore,keptmesane
during,andhelpedmecelebrateafter.


Preface
Thisisabookabouthowtouseanexcitingandpowerfultechnology,
JavaServerPages,(JSP)tocreatedynamic,interactiveWebsites.As
thenameimplies,thistechnologyisbasedontheJavaprogramming
languageandinheritsmanyofthelanguage'sfeaturesandbenefits.Most

notably,JavamakesJSPsavailableonalmosteverykindofcomputer
andoperatingsystemandcertainlyallthoseincommonuse.
JavaServerPagesarenowamatureandstabletechnology,alreadyin
useinthousandsofcompanies.Butmaturityhascertainlynotledto
stagnation!Recently,anewversionoftheJSPspecificationwas
released,bringingnewcapabilitiesandpossibilities.Inaddition,several
companiontechnologieshavebeendevelopedtoaugmentthe
fundamentalspecification.Thenewspecification,aswellasthemost
importantoftheseassociatedtechnologies,areallcoveredinthisbook.
Throughoutthisbook,efforthasbeenmadetoshowthecapabilitiesofall
thesetoolsandtodiscusshowtheycanbestbeused.
OneofthemostimportantfeaturesofJavaServerPagesishoweasy
theyaretouse.AnyonewhoisreasonablycomfortablewithHTML
(HypertextMarkupLanguage)canlearntowriteJavaServerPagesby
usingafewsimpletagsthatmaydoverysophisticatedthingsbehindthe
scenes,alongwithsmallpackagesofcodecalledJavaBeans.This
allowsforaveryproductiveworkingrelationshipbetweenHTMLexperts
whobuildpagesandJavaprogrammerswhobuildbeansandnewtags.
Bothkindsofdeveloperwillfindmaterialofinterestinthisbook.Chapter
1givesabriefhistoryoftheWeb,settingJSPsincontextandclarifying
whattheyare,howtheywork,andwhytheyworkthatway.Chapter2
introducessomeofthesimplerfeaturesofJSPsandshowsjusthow
easythetransitionfromHTMLtoJSPis.
ThenexttwochaptersintroducethetwovitaltechnologiesthatgiveJSPs
theirenormouspowerandflexibility:JavaBeansinChapter3andcustom
tagsinChapter4.Thesetagsarepresentedaspageauthorswilluse


them:componentsthathideallthecomplexitiesofJavabehindsimple
interfacesthatcanbecombinedandusedinlimitlessways.Chapter5

usesbeansandtagstobuildafullyfunctionalWebsite.
OneofthegreatbenefitsofJSPsisthattheymakeitpossibleforpages
tointeractwithcomplexsystems.Averycommonsuchsystemisa
database.Chapter6introducesdatabaseconceptsanddiscusseseasy
waysinwhichapageauthorcanaccessdata.Chapter7usesthis
informationtoexpandtheutilityofthesitebuiltinChapter5.
XML(ExtensibleMarkupLanguage)isanincreasinglyimportant
technology,andJSPsarealreadywellequippedtoworkwithXML.This
topiciscoveredinChapter8.
Thefirsteightchapterscomprisealogicalfirsthalfofthebook,dealing
withthemyriadthingspageauthorscandowithJSPswithoutknowing
anythingaboutJava.Theremainderofthebookdelvesunderthehoodto
explainhowallthisisaccomplishedandhowJavaprogrammerscan
extendthecapabilitiesofJSPs.Forreaderswhoarenotyetfamiliarwith
Java,Chapter9introducesthelanguage.
Chapter10coverstheprocessofcreatingnewbeans.Chapter11covers
atechnology,calledservlets,thatunderliesJSPs.Thisinformationis
thenusedinChapter12totalkaboutcontrollers,Javacodethathelps
piecesofaWebsiteworktogethersimplyandcleanly.Chapter13
discusseshowtouseJavatocreatenewtags.Chapter14coversafew
remainingadvancedtopics.
Readerswhoarenotinterestedinprogrammingwillgetthemostoutof
thisbookbyreadingChapters1through9,whichcompriseacomplete
courseonhowtouseJSPs,beans,tags,andrelatedtechnologiesto
buildjustaboutanyWebsiteimaginable.Atthatpoint,suchreadersmay
wishtolearnalittleJavafromChapter9andthenproceedonthrough
therestofthebookinordertounderstandbetterhoweverythingworks.
Ontheotherhand,readerswhoalreadyknowJavabutwhomaynotbe
familiarwithJSPs,thenewfeaturesaddedaspartofthelatest
specification,orrelatedtechnologieswillwanttomovequicklythrough



Chapter2togetafeelforJSPsyntaxandthengothroughChapters3
and4toseehowJSPsinterfacewithJavaviatagsandbeans.
ProgrammersmaythenwishtoproceedtoChapter10toseehownew
beansarecreated,andfromtherethroughthesecondhalfofthebookin
ordertounderstandservletsandtags.
Finally,asamazingasitmayseem,thereisabsolutelynocostto
developinganddeployingJSPs!Thereisnoneedtobuyaspecialserver
orparticularhardwareoroperatingsystem.Allthetoolsneeded,and
manyothers,havebeenreleasedforfreebytheApachegroup.TheCDROMaccompanyingthisbookcontainsthesetools,aswellasallthe
examplesfromthebook.Itismysincerehopethatthisbook,in
conjunctionwiththesetools,willhelpyougetthemostoutofthis
revolutionarynewtechnologyforbuildingexciting,compellingWebsites.


Acknowledgements
Thisbookisverymuchagroupeffort,andIamdeeplyindebtedto
everyonewhohelpedmakeitpossible.
Ithasbeenmygreatpleasuretoworkwithsomeofthebrightestand
mostdedicatedpeopleinNewYorkatCapitalThinking.Althoughthere
aretoomanytoname,Iwanttothankthemallforhelpingtokeep
technologyfunandexcitingenoughtowriteabout.Almosteveryrealworldconsiderationregardingserver-sideJavathatappearsinthisbook
cameoutofprojectsmycolleaguesandIworkedon.
ManythanksandhighpraisetoeveryoneattheApacheprojectbehind
Tomcat,thestandardtaglibraries,struts,andsomuchmore.Their
decisiontomakesuchhigh-qualitytoolsfreeandopensourcedeserves
aroundofapplausefromeveryJavaandJSPdeveloper.
AllthecodeinthisbookwasdevelopedonaFreeBSDsystem.Iowea
debtofgratitudetoeveryonebehindboththeoperatingsystemandthe

Javaports.
Iwouldalsoliketothankeveryonewhotookthetimetoreadoverthe
manuscriptandmakesuggestions.Thefinalresultisprofoundlybetterfor
theirefforts.
Thisbookwouldbenothingbutacollectionofunreadbitsonmyhard
driveifnotforeveryoneatAddison-Wesley,includingAnnSellers,Jacqui
Doucette,DebbyVanDijk,MichaelMullen,MaryO'Brien,andthemany
otherswhomImaynothavebeenluckyenoughtoworkwithdirectly.
Finally,Iwouldliketothanktheartistswhocreatedthemusicthatkept
mecompanywhileIwaswriting.Manyoftheirnamesappearin
examplesscatteredthroughoutthetext.
...andIwrotethisbookforevilgraymonkeyswhohauntme...


Chapter1.Introduction
SinceJavaServerPageswereintroducedinJune1999,theyhavetaken
theworldbystorm!DozensofproductsaredevotedtoJSPs,and
hundredsofcompaniesareusingJSPstobuildtheirWebsitesand
corporateintranets.Thefriendly.jspextensioncanbeseenalloverthe
Web.
Themostsignificantofthemanygoodreasonsforthisisthatitis
amazinglyeasytodevelopsophisticatedWebsiteswithJSPs.Anyone
whocanwriteHTMLcanquicklycreaterich,dynamic,andresponsive
Websitesthatenableuserstogetthemostoutoftheironlinetime.
ThroughamechanismcalledJavaBeans,JSPshavemadeitpossiblefor
largeteamsorindividualsworkingoncomplexprojectstodividethework
insuchawayastomakeeachpiecesimpleandmanageable,without
sacrificinganypower.JSPsalsoprovideagreatdealofflexibilitywhen
generatingHTML,throughtheabilitytocreateHTML-likecustomtags.
Inadditiontothisfundamentaleaseofdevelopment,high-qualityJSP

toolsarereadilyavailableandeasytouse.Developersdonotneedto
buyexpensivesoftwareorcommittoaparticularoperatingsystemin
ordertouseJSPs.TheCD-ROMaccompanyingthisbookcontains
everythingaJSPauthorneedstogetstarted,andthetoolsarepowerful
enoughtoserveevenamidsizedWebsitewithoutproblems.Thesefree,
open-sourcetoolsarestableandsecureandrunonnearlyevery
platform.Ofcourse,high-qualitycommercialJSPtoolsareavailableas
well,suitableforservingeventhemostcomplexandhigh-trafficWeb
sites.
AlthoughJSPshavebeenusefulandpowerfulsincethebeginning,thisis
anespeciallyexcitingtimetobeaJSPdeveloper.Therecentlyreleased
version2.0oftheJSPspecificationprovidesevenmorefeaturesthat
simplifytheprocessofcreatingWebsites.Inaddition,astandardtag
librarythatprovidesmanyJSPtagsthatsolveawiderangeofcommon
problemshasbeenreleased.Finally,inthetimesincetheywere
released,anumberofbestpracticesforusingJSPshaveemerged.


Thisbookcoversallthetopics:thebasicpowerfulfeaturesoftheJSP
specification,theimprovementsintroducedwithversion2.0,aswellas
thenewstandardtaglibraryandallthethingsitdoes.Inaddition,this
bookdiscusseshowbesttousethesetools,basedonreal-world
experiences.
However,beforewegetintoallthefun,let'stakealookbackathowthe
Webhasevolved.ThiswillhighlightthekindsofproblemsthatWeb
authorshavefacedsincethebeginning.Oncethisisunderstood,itwill
beclearhowJSPssolvetheseproblemsandmakepagecreationso
easy.



×