Tải bản đầy đủ - 0 (trang)
Chapter 16. CGI and Perl: The Hyper Dynamic Duo

Chapter 16. CGI and Perl: The Hyper Dynamic Duo

Tải bản đầy đủ - 0trang

Figure16.2.Viewingpartialsourcepageforgoogle.com.



Sothatthebrowserrecognizesthefile,itsnameendsineither

.htmlor.htm.TheHTMLtagstellthebrowserhowtodisplay

thedocumentonyourscreen.LearningthebasicsofHTMLis

notdifficult,butdevelopinganartisticandinterestingdesignis

anotherstory,andtherearethousandsofcompaniesdevotedto

creatingthesemaster-piecesforothercompaniesdoing

competitivebusinessovertheWeb.



Therearetwotypesofpages:staticpagesanddynamic

pages.Staticpagesdonotrequireinteractionwiththeuser.The

mosttheycandoissendalreadyexistingdocumentstousers.

Theyareanalagoustoapageinabookandusuallydescribe

theservicessomeindividualorcompanyoffers.Theycanbe

veryartisticandinteresting,buttheycan'thandleinformation

ondemand.Dynamicpages,ontheotherhand,are"alive."

Theycanacceptandretrieveinformationfromtheuser,

producespecializedandcustomizedcontent,searchthrough

text,respondwithe-mail,querydatabases,andgenerate

documentsonthefly.Theycanmanageinformationthatis

continuallychanging,basedontherequestsofdifferentusers.

ThesedynamicpagesrequiremorethananHTMLtextfile.They

aredrivenbyprograms,orscripts,thatinteractwiththeWeb

server,whichthentransfersinformationtoyourbrowser.To

sendtheinformationbackandforthbetweentheprogramand

theserver,aserver-sideprogramisused.Theserveritself

relaysuserrequeststoaprogram,whichinturnmanagesthe

information,suchasparsingthedatafromaform,retrieving

datafromafileordatabaseasaresultofauserrequest,and

thensendingitbacktotheserver.

TheCGI(CommonGatewayInterface)protocoldefineshowa

servercancommunicatewithprograms.Itsfunctionistoallow

theWebservertogobeyonditsnormalboundariesfor

retrievingandaccessinginformationfromexternaldatabases

andfiles.Itis,then,aspecificationthatdefineshowdatacan

betransferredfromthescripttotheserverandfromtheserver

tothescript.Gatewayprograms,calledCGIscripts,canbe

writteninanyprogramminglanguage,butPerlhasbecomethe

defactostandardlanguage,mainlybecauseitisflexibleand

easytouse.

Ifyouhavereadthepreviouschapters,youknowthatthePerl

interpreteriseasytoobtain.Youknowthatitisportable.And

youknowaboutPerl'scapabilitytohandleregularexpressions,

files,sockets,andI/O.OnceyouknowPerl,writingCGIscripts

isrelativelyeasy.Thecriticalpartismakingsurethattheserver



andPerlhavebeenproperlyinstalledandthatyourscriptsare

placedinthedirectorywheretheserverwilllookforthem.The

pathnamesmustalsobesetcorrectlysothattheserverknows

whereyouarestoringthescriptsandhowtoreachthe

necessarylibraries.Alleffortsarefornothingifanyofthe

necessarystepsfrominstallationtoimplementationare

incorrectinanyway.Itisveryfrustratingtoseethebrowser

whiningaboutnotfindingarequestedfileoraserverscolding

thatyouareforbiddentorunaprogramorthatyourdocument

containsnodatawhenyouknowitdoes.

ThischapterisnotwrittentomakeyouamasterWebdesigner;

itistogiveyousomeunderstandingofhowPerlfitsintothe

CGIschemeandhowdynamicpagesfortheWebarecreated.

Sometimes,seeingtheoverallpictureisthekeyto

understandingthepurposeandplanofthemoredetailed

design.ThereisaplethoraofWebinformationavailableonthe

Internetandintradebookstofillinthedetails.

Today,PHPandASP.netareserverprogrammingmodules

embeddedintheserveritself,eliminatingtheneedforCGI

scripts,butduetothepopularityofPerlandthefactthatthere

aresomanyCGIscriptsinuse,mod_perl(dubbed"Perlon

steroids")allowsyoutoembedthePerlinterpreterrightinthe

ApacheservertoincreasePerl'sperformanceandto

accommodatethedeveloperswhoprefertousePerltocreate

dynamicpagesandstillbeabletouseCGIscriptswith

enhancedspeedandpower.Tolearnmoreaboutmod_perl,see

AppendixDandhttp://perl.apache.org/.

Figure16.3.Therelationshipbetweenthebrowser,

server,andCGIprogram.



Figure16.4.AsimpleCGIprogramsendsoutputtothe

browser.

[Viewfullsizeimage]



Chapter16.CGIandPerl:TheHyper

DynamicDuo



16.1.StaticandDynamicWebPages

OnceyoustartbrowsingtheInternet,youjumpfromonesite

toanother,viewingallkindsofWebpagesfromsimplehome

pagestohighlydevelopedsites,suchasGoogleorAmazon.

EvenasimpleWebpageisafilethatnormallycontainsHTML

tagsandtext,formattinginstructions,andunderlinedphrases

calledlinksthatconnectyoutootherdocumentseitheronthe

samemachineoronsomeothermachineonthenetwork.The

document(calledahypertextdocument)tellsthebrowserhow

todisplaythedocument;e.g.,whatfonts,colors,styleswillbe

used.Thepagemayalsocontainhypermedia,whichincludes

images,sound,movies,andhotlinkstootherdocuments.A

Webpageiscreatedinatexteditor,andtheresultingHTMLfile

iscalledthesourcefile,whichcanbeviewedinthebrowserby

clickingon"View"inthemenubar.

Figure16.1.Toviewthesourcefile.



Figure16.2.Viewingpartialsourcepageforgoogle.com.



Sothatthebrowserrecognizesthefile,itsnameendsineither

.htmlor.htm.TheHTMLtagstellthebrowserhowtodisplay

thedocumentonyourscreen.LearningthebasicsofHTMLis

notdifficult,butdevelopinganartisticandinterestingdesignis

anotherstory,andtherearethousandsofcompaniesdevotedto

creatingthesemaster-piecesforothercompaniesdoing

competitivebusinessovertheWeb.



Therearetwotypesofpages:staticpagesanddynamic

pages.Staticpagesdonotrequireinteractionwiththeuser.The

mosttheycandoissendalreadyexistingdocumentstousers.

Theyareanalagoustoapageinabookandusuallydescribe

theservicessomeindividualorcompanyoffers.Theycanbe

veryartisticandinteresting,buttheycan'thandleinformation

ondemand.Dynamicpages,ontheotherhand,are"alive."

Theycanacceptandretrieveinformationfromtheuser,

producespecializedandcustomizedcontent,searchthrough

text,respondwithe-mail,querydatabases,andgenerate

documentsonthefly.Theycanmanageinformationthatis

continuallychanging,basedontherequestsofdifferentusers.

ThesedynamicpagesrequiremorethananHTMLtextfile.They

aredrivenbyprograms,orscripts,thatinteractwiththeWeb

server,whichthentransfersinformationtoyourbrowser.To

sendtheinformationbackandforthbetweentheprogramand

theserver,aserver-sideprogramisused.Theserveritself

relaysuserrequeststoaprogram,whichinturnmanagesthe

information,suchasparsingthedatafromaform,retrieving

datafromafileordatabaseasaresultofauserrequest,and

thensendingitbacktotheserver.

TheCGI(CommonGatewayInterface)protocoldefineshowa

servercancommunicatewithprograms.Itsfunctionistoallow

theWebservertogobeyonditsnormalboundariesfor

retrievingandaccessinginformationfromexternaldatabases

andfiles.Itis,then,aspecificationthatdefineshowdatacan

betransferredfromthescripttotheserverandfromtheserver

tothescript.Gatewayprograms,calledCGIscripts,canbe

writteninanyprogramminglanguage,butPerlhasbecomethe

defactostandardlanguage,mainlybecauseitisflexibleand

easytouse.

Ifyouhavereadthepreviouschapters,youknowthatthePerl

interpreteriseasytoobtain.Youknowthatitisportable.And

youknowaboutPerl'scapabilitytohandleregularexpressions,

files,sockets,andI/O.OnceyouknowPerl,writingCGIscripts

isrelativelyeasy.Thecriticalpartismakingsurethattheserver



andPerlhavebeenproperlyinstalledandthatyourscriptsare

placedinthedirectorywheretheserverwilllookforthem.The

pathnamesmustalsobesetcorrectlysothattheserverknows

whereyouarestoringthescriptsandhowtoreachthe

necessarylibraries.Alleffortsarefornothingifanyofthe

necessarystepsfrominstallationtoimplementationare

incorrectinanyway.Itisveryfrustratingtoseethebrowser

whiningaboutnotfindingarequestedfileoraserverscolding

thatyouareforbiddentorunaprogramorthatyourdocument

containsnodatawhenyouknowitdoes.

ThischapterisnotwrittentomakeyouamasterWebdesigner;

itistogiveyousomeunderstandingofhowPerlfitsintothe

CGIschemeandhowdynamicpagesfortheWebarecreated.

Sometimes,seeingtheoverallpictureisthekeyto

understandingthepurposeandplanofthemoredetailed

design.ThereisaplethoraofWebinformationavailableonthe

Internetandintradebookstofillinthedetails.

Today,PHPandASP.netareserverprogrammingmodules

embeddedintheserveritself,eliminatingtheneedforCGI

scripts,butduetothepopularityofPerlandthefactthatthere

aresomanyCGIscriptsinuse,mod_perl(dubbed"Perlon

steroids")allowsyoutoembedthePerlinterpreterrightinthe

ApacheservertoincreasePerl'sperformanceandto

accommodatethedeveloperswhoprefertousePerltocreate

dynamicpagesandstillbeabletouseCGIscriptswith

enhancedspeedandpower.Tolearnmoreaboutmod_perl,see

AppendixDandhttp://perl.apache.org/.

Figure16.3.Therelationshipbetweenthebrowser,

server,andCGIprogram.



Figure16.4.AsimpleCGIprogramsendsoutputtothe

browser.

[Viewfullsizeimage]



16.2.HowItallWorks

16.2.1.InternetCommunicationbetweenClient

andServer

TheHTTPServer

Wediscusstheclient/servermodelandtheTCP/IPprotocolsfor

regulatingnetworkoperationsinChapter20,"SendItOverthe

NetandSockItto'Em!"OntheInternet,communicationisalso

handledbyaTCP/IPconnection.TheWebisbasedonthis

model.Theserversiderespondstoclient(browser)requests

andprovidesfeedbackbysendingbackadocument,by

executingaCGIprogram,orbyissuinganerrormessage.The

networkprotocolthatisusedbytheWebsothattheserverand

clientknowhowtotalktoeachotheristheHypertextTransport

Protocol,orHTTP.ThisdoesnotprecludetheTCP/IPprotocol's

beingimplemented.HTTPobjectsaremappedontothe

transportdataunits,aprocessthatisbeyondthescopeofthis

discussion;itisasimple,straightforwardprocessthatis

unnoticedbythetypicalWebuser.(Seewww.cis.ohiostate.edu/cgi-bin/rfc/rfc2068.htmlforatechnicaldescriptionof

HTTP.)TheHTTPprotocolwasbuiltfortheWebtohandle

hypermediainformation;itisobjectorientedandstateless.In

object-orientedterminology,thedocumentsandfilesarecalled

objects,andtheoperationsthatareassociatedwiththeHTTP

protocolarecalledmethods.Whenaprotocolisstateless,

neithertheclientnortheserverstoresinformationabouteach

otherbutmanagesitsownstateinformation.

OnceaTCP/IPconnectionisestablishedbetweentheWeb

serverandclient,theclientwillrequestsomeservicefromthe

server.Webserversarenormallylocatedatwell-knownTCP

port80.Theclienttellstheserverwhattypeofdataitcan

handle,bysendingAcceptstatementswithitsrequests.For

example,oneclientmayacceptonlyHTMLtext,whereas

anotherclientmightacceptsoundsandimagesaswellastext.

Theserverwilltrytohandletherequest(requestsand



responsesareinASCIItext)andsendbackwhatever

informationitcantotheclient(browser).

Example16.1.



(Client's(Browser)Request)

GET/pubHTTP/1.1

Connection:Keep-Alive

User-Agent:Mozilla/4.0Gold

Host:severname.com

Accept:image/gif,image/x-xbitmap,image/jpeg,image/pjpeg,*/*

Example16.2.

(Server'sResponse)

HTTP/1.1200OK

Server:Apache/1.2b8

Date:Mon,22Jan200713:43:22GMT

Last-modified:Mon,01Dec200712:15:33

Content-length:288

Accept-Ranges:bytes

Connection:close

Content-type:text/html

HelloWorld!

---continuewithbody--

Connectionclosedbyforeignhost.



TheresponseconfirmswhatHTTPversionwasused,thestatus

codedescribingtheresultsoftheserver'sattempt(didit

succeedorfail?),aheader,anddata.Theheaderpartofthe

messageindicateswhethertherequestisokay,whattypeof

dataisbeingreturned(forexample,thecontenttypemaybe



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 16. CGI and Perl: The Hyper Dynamic Duo

Tải bản đầy đủ ngay(0 tr)

×