ebook img

Practical guide for Java programmers PDF

182 Pages·2003·4.882 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Practical guide for Java programmers

Practical Guide to JavaServer Pages Robert J. Brunner AMSTERDAM•BOSTON•HEIDELBERG•LONDON NEWYORK•OXFORD•PARIS•SANDIEGO SANFRANCISCO•SINGAPORE•SYDNEY•TOKYO MorganKaufmannisanimprintofElsevier SeniorEditor RickAdams PublishingServicesManager SimonCrump SeniorProductionEditor BrandyPalacios DevelopmentEditor KarynJohnson ProjectManagement GraphicWorldPublishingServices TechnicalIllustration GraphicWorldIllustrationStudio Composition CephaImagingPVTLTD. Copyeditor GraphicWorldPublishingServices Proofreader GraphicWorldPublishingServices Indexer GraphicWorldPublishingServices InteriorPrinter MaplePress Designationsusedbycompaniestodistinguishtheirproductsareoftenclaimedastrademarksor registeredtrademarks.InallinstancesinwhichMorganKaufmannPublishersisawareofaclaim, theproductnamesappearininitialcapitalorallcapitalletters.Readers,however,shouldcontact theappropriatecompaniesformorecompleteinformationregardingtrademarksandregistration. MorganKaufmannPublishers AnimprintofElsevierScience 340PineStreet,SixthFloor SanFrancisco,CA94104-3205 www.mkp.com ©2003byElsevierScience(USA) Allrightsreserved. PrintedintheUnitedStatesofAmerica 07 06 05 04 03 5 4 3 2 1 Nopartofthispublicationmaybereproduced,storedinaretrievalsystem,ortransmittedinany formorbyanymeans—electronic,mechanical,photocopying,orotherwise—withouttheprior writtenpermissionofthepublisher. ISBN:1-55860-836-2 Thisbookisprintedonacid-freepaper. Contents 1 Introduction to JavaServer Pages 1 1.1 IntroductiontoWebApplications 1 1.1.1 TheHTTPModel 2 1.1.2 ABriefIntroductiontoServlets 4 1.1.3 Packaging 6 1.1.4 TheDeploymentDescriptor 6 1.2 GettingStartedwithJavaServerPages 7 1.2.1 BuildingaSimpleJSPPage 8 1.2.2 ThePJBankWebApplication 11 Exercises 12 2 The Fundamentals of JavaServer Pages 13 2.1 Directives 13 2.1.1 ThePageDirective 14 2.1.2 TheIncludeDirective 17 2.1.3 TheTaglibDirective 17 2.2 JSPDeclarations 18 2.3 Expressions 19 2.4 Scriptlets 20 2.5 Comments 22 2.6 Scope 24 2.7 ImplicitObjects 24 2.7.1 TheRequestObject 25 2.7.2 TheResponseObject 27 2.7.3 TheSessionObject 29 2.7.4 TheExceptionObject 31 2.7.5 TheOtherImplicitObjects 33 2.8 StandardActions 34 2.8.1 JavaBeanStandardActions 34 2.8.2 ResourceActions 37 2.8.3 AdvancedActions 39 Exercises 41 3 JavaBeans and Forms 43 3.1 HTMLForms 43 3.1.1 AnOverviewofHTMLForms 44 3.1.2 JSPFormProcessing 50 3.1.3 AnEmailForm 53 3.2 JavaBeans 55 3.2.1 BeanBasics 56 3.2.2 JavaBeansandForms 58 3.3 SimpleWebApplication 61 3.3.1 TheWelcomePage 61 3.3.2 TheLoginPage 67 Exercises 70 4 Expression Language 71 4.1 ELOverview 72 4.1.1 AccessingData 73 4.1.2 ImplicitObjects 74 4.1.3 LiteralValues 74 4.1.4 Operators 75 4.2 ELandJavaBeans 78 4.3 ELandCollections 81 4.4 Functions 87 Exercises 91 5 The Standard Tag Library 93 5.1 CoreTags 94 5.1.1 GeneralActions 94 5.1.2 ConditionalActions 97 5.1.3 IteratorActions 99 5.1.4 URLActions 101 5.2 FormattingTags 103 5.3 XMLTags 107 5.4 SQLTags 110 Exercises 116 6 Custom Actions 117 6.1 TagOverview 117 6.1.1 TagHandlers 118 6.1.2 TagLibraryDescriptors 120 6.2 TagFiles 121 6.2.1 ProcessingAttributesinaTagFile 123 6.2.2 ProcessingaTagBody 125 6.2.3 ProcessingVariablesinaTagFile 128 6.3 SimpleTagHandlers 131 6.3.1 SimpleTagInterface 132 6.3.2 ImplementingaSimpleTagHandler 132 6.4 ClassicTagHandlers 136 6.4.1 TagInterface 136 6.4.2 IterationTagInterface 137 6.4.3 BodyTagInterface 137 6.4.4 ImplementingaClassicTagHandler 137 Exercises 141 7 Building a Web Application 143 7.1 JavaServletTechnology 143 7.1.1 ServletOverview 144 7.1.2 TheServletController 145 7.1.3 TheServletFilter 149 7.2 AncillaryWeb-ApplicationTechnologies 152 7.2.1 CascadingStyleSheets 152 7.2.2 JavaScriptandFormValidation 155 7.2.3 Web-ApplicationFrameworks 157 7.3 Security 158 7.3.1 ProgrammaticSecurity 159 7.3.2 DeclarativeSecurity 159 7.3.3 SecureSocketsLayer 161 Exercises 163 A Tool Installation 165 A.1 InstallingTomcat 165 A.2 InstallingtheExampleCode 166 A.3 InstallingtheJSPStandardTagLibrary 166 A.4 InstallingMySQL 167 A.4.1 Installation 167 A.4.2 CreatingtheDatabase 167 B Further Resources 171 B.1 TheWorldWideWeb 171 B.2 Java 171 B.3 JavaServlets 172 B.4 JavaServerPages 172 B.5 TheJSPStandardTagLibrary 173 B.6 DatabasesandJDBC 173 B.7 InternationalizationandLocalization 174 B.8 Security 174 B.9 WebApplications 174 Index 175 1 c h a p t e r Introduction to JavaServer Pages J avaServerPages(JSP)isaJavatechnologythatallowsadevelopertorapidlycreate dynamic Web applications. While other technologies exist, only JSP provides a powerful, portable,andeasilyextensibleframeworkthatsupportsthedevelopmentofdynamicWeb applications. The JSP specification, or standard, continues to evolve. The latest version, coveredinthisbook,istheJSP2.0specification,whichintroducesnewfunctionalitythat simplifies the task of JSP page authors—making JSP technology an even better choice for buildingyournextWebapplication. Thischapterlaysthefoundationfortherestofthebook,byintroducingWebappli- cationsandtherelatedconceptsofHypertextTransportProtocol(HTTP)andJavaServlets. ThischapterendswithabriefdiscussionoftheWebapplicationusedtodemonstrateJSP developmentthroughoutthisbook. 1.1 Introduction to Web Applications WhileJSPtechnologycanbeusedtobuildsimpleWebsites,itsrealpowerliesinitsability toprovidethefoundationforbuildingWebapplications.JavaServerPagescanbeusedto buildonlinebankingWebsites,e-commercesites,publicforums,orjustaboutanyother typeofinteractiveWebsiteinwhichyoumightbeinterested. While other technologies can also play a role in building these types of Web sites andwillbediscussedinmoredetailinChapter7,JSPhasquicklyevolvedintoapowerful technology that can support the construction of dynamic Web applications, even when usershavelittlepreviousexperience. RecentadvancesliketheExpressionLanguage(EL), whichisdiscussedinChapter4,andtheJSPStandardTagLibrary,introducedinChapter5, 1 2 Chapter1:IntroductiontoJavaServerPages ■ allowsmallJSPdocumentsthatprovidepowerfulcapabilitiestobecreated.TheJSPspec- ificationalsoallowsadevelopertoconstructcustomactions, whichallowasinglelinein a JSP page to provide considerable behind-the-scenes functionality. Custom actions are detailedinChapter6,whereJSPtagfilesareextensivelycovered. At the heart of a JSP Web application, however, are several simple concepts that mustbeaddressedbeforeplungingdirectlyintoJavaServerPages.First,JSPWebapplica- tionsrelyonHTTPtoprovideclient-servercommunicationovertheInternet.Second,the JavaServerPagespecificationisdependentontheJavaServletspecification.Asaresult,a basic understanding of Java Servlets, including the Servlet lifecycle, is necessary before jumping into building JSP pages. Third, JSP applications follow a simple directory lay- out that groups both configuration information and resources for easier identification and processing. Finally, a Web application requires a deployment descriptor that pro- videsconfigurationinformationtotheWebapplicationserverregardingaparticularWeb application. 1.1.1 The HTTP Model AJSP-basedWebapplicationusesaclient-servermodel, asdemonstratedinFigure1.1. A clientmakesarequesttotheserver,whichrespondsaccordingly.ThelanguagethatWeb servers and Web browsers use to communicate is called HTTP. Currently, HTTP version 1.1 is the standard in use, which defines the commands HEAD, GET, PUT, POST, DELETE, TRACE, OPTIONS, and CONNECT.1 For a Web-application developer, only GET and POST aregenerallyofinterest,astheyarethecommandsusedbyaclienttomakearequestof aserver. A Uniform Resource Locator (URL) identifies a resource and is the target of a client request. An HTTP message consists of a header that contains information that describes the client to the server, including browser type, possible authentication credentials, the actualHTTPcommand, andabodythatcontainstheentirecontentofthemessagebeing transmitted. Request Client Server Response Figure1.1: TheHTTPmodel. 1TheHTTP/1.1specificationisavailableathttp://www.w3.org/Protocols/rfc2616/rfc2616.html. ■ 1.1 IntroductiontoWebApplications 3 HTTP is a stateless protocol in which a client makes a request for a resource, and a serverrespondsbyprovidingtheresourceoranerrorcondition.Theservertreatssubse- quentclientrequestsascompletelyindependentrequests.Thus,noinformation,orstate, is carried over between subsequent requests from the same client. To support stateful communication, which is mandatory for e-commerce to work, extra information must be transmitted between the client and server to coordinate different HTTP requests into a coherentclientrequestandtoallowtheservertokeeptrackofaclient’sactions(suchas fillingashoppingcartortransferringfunds).Theprocessofassociatingmultiplerequests togetherresultsinaclientsession. The server generally manages sessions either by returning data to the client, which will be attached to future requests, or else by adding an additional attribute to an HTTP header.Theextradatacommunicatedviathefirsttechniqueiscommonlycalledacookie. The client can use the cookie as a session identification, or ID, in subsequent requests to identify itself to the server, as shown in Figure 1.2. The second technique is more commonly known as URL rewriting, as the session identification is actually appended to the resource URL. This approach proves useful when a cookie cannot be used, which can happeniftheclient’sbrowserhasdisabledcookies. Request Client Server ID Response Request ID ID Response Request ID ID Response Figure1.2: UsingacookienamedIDtoimplementasession. 4 Chapter1:IntroductiontoJavaServerPages ■ 1.1.2 A Brief Introduction to Servlets The original method for building Web applications using Java was provided by Java Servlets. A Servlet is a Java class that extended the functionality of a server, such as the Apache Web server, to dynamically process incoming requests and generate appro- priateresponses.Servletsprovidedagreatdealoffunctionality,allowingearlyWebsites toleveragethefullpoweroftheJavaprogramminglanguage. Thispower,however,requiredanyonewhowantedtouseServletstohaveadetailed understandingoftheJavaprogramminglanguage—somethingmanyearlyWebdevelopers lacked.Inresponsetothisdifficulty,JSPtechnologywasdeveloped.JSPstillprovidesthe fullpoweroftheJavaprogramminglanguage,butinamucheasierpackage.JSPtechnology islayeredovertheServlettechnologybecauseaJSPpagemustbetranslatedintoaServlet beforetheWebservercanprocessit.Thus,aprimeronServletsisusefulinunderstanding howtodevelopJSPWebapplications. The component of a Web-application server that provides access to JSP resources is called a container. This container first translates the JSP page into a Java source code file that by default implements the javax.servlet.http.HttpServlet class (experts can changetheimplementationclass,butforthemajorityofcases,thedefaultworksjustfine). Next,thisServletclassiscompiledintoaJavaclassfile,whichcanbeusedtoprocessthe originalclientrequest. BecauseJSPpagesarehandledasServlets, theyfollowtheServlet lifecycle. Inaddition, theycanusefunctionalityprovidedbythecontainerinaccordance withtheServletspecification,suchasFiltersandServletListeners.TheServletapplication programminginterface(API)alsoincludesclassesthatencapsulateHTTPconcepts,suchas arequestandaresponse,aswellassessioninformation,cookies,andHTTPheadersand attributes. Objects that implement these classes are made available to the JSP developer, whichsimplifiestheprocessofwritingWebapplicationsconsiderably. TheServletlifecycleisstraightforward(seeFigure1.3)andismanagedbytheServlet container. When a request for a Servlet-backed resource is made, the Servlet container locates the implementation class and loads it into a Java Virtual Machine (JVM). For a JSP, the extra steps of translating and compiling the JSP implementation page occur at this stage. After the Servlet class is loaded into the JVM, an object of the Servlet class is instantiated. ThenewlyinstantiatedobjectisreadyforthefirststageofaServlet’slifecycle,which iscalledinitialization.Anyprocessingthatshouldoccurduringthisstageisplacedinside theServlet’sinitmethod.Thisstageisoftenusedtoobtaincurrentruntimeparameters, read ancillary files, or establish a database connection. Once the initialization stage is complete, the Servlet enters the second stage, called the service stage. Processing that occurs during this stage is placed in the service method for a GenericServlet or in the appropriate HTTP service method, such as doGet or doPost, for an HttpServlet. Once the Servlet is no longer needed, which can occur when the server is being shutdown or resourcesarebeingreclaimed, thedestructionphaseisentered. Allprocessingthatmust occurtocleanupaServletatthisstageisplacedinthedestroymethod.Thismethodcan beusedtocloseexternalresourcessuchasdatabaseconnectionsorfiles.

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.