programming for www (ice 1338) lecture #8 lecture #8 july 21, 2004 in-young ko iko.at. icu.ac.kr...
TRANSCRIPT
Programming for WWWProgramming for WWW(ICE 1338)(ICE 1338)
Lecture #8Lecture #8 July 21, 2004
In-Young Koiko .AT. icu.ac.kr
Information and Communications University (ICU)
July 21, 2004 2 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
AnnouncementsAnnouncements
Homework#2Homework#2 is due by today is due by today Submit a Submit a hard copyhard copy of your report of your report Send the TA (Send the TA (minhcuong .AT. icu.ac.kr minhcuong .AT. icu.ac.kr ) the ) the
source codesource code of your program via email of your program via email Include your English Include your English name and student IDname and student ID in the in the
source code source code Please make a zip file if you have more than on Please make a zip file if you have more than on
source filesource file
July 21, 2004 3 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
Review of the Previous LectureReview of the Previous Lecture
Java AppletsJava Applets Applet GUI structureApplet GUI structure Event handling in Applet GUIsEvent handling in Applet GUIs Concurrency in AppletsConcurrency in Applets
Plug-in programsPlug-in programs
July 21, 2004 4 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
Contents of Today’s LectureContents of Today’s Lecture
Interaction between Java Applets and Interaction between Java Applets and JavaScriptJavaScript
CGI programmingCGI programming Perl pattern matchingPerl pattern matching Perl modulesPerl modules CookiesCookies
July 21, 2004 5 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
LiveConnectLiveConnect Developed by Netscape Inc. in 1996Developed by Netscape Inc. in 1996 Allows Web browser Allows Web browser plug-insplug-ins, , Java AppletsJava Applets, and , and
JavaScriptJavaScript to communicate with each other to communicate with each other Java to JavaScript Communication Java to JavaScript Communication JavaScript to Java Communication JavaScript to Java Communication JavaScript to Plug-in Communication JavaScript to Plug-in Communication Java to Plug-in CommunicationJava to Plug-in Communication
http://wp.netscape.com/navigator/v3.0/liveconnect.html
July 21, 2004 6 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
LiveConnect ExampleLiveConnect Example
Applet
JavaScript
A Form
A ParagraphHTML (DOM)
July 21, 2004 7 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
The Applet CodeThe Applet Codeimportimport netscape.javascript.*netscape.javascript.*;;……public class AppletTest extends JApplet implements Runnable {public class AppletTest extends JApplet implements Runnable { private delay = 10; private Color bgColor = Color.white, fgColor = Color.blue;private delay = 10; private Color bgColor = Color.white, fgColor = Color.blue; private private JSObjectJSObject window, document, location; window, document, location; ……public void init() {public void init() { … … window = window = JSObject.getWindowJSObject.getWindow(this);(this); document = (JSObject)window.document = (JSObject)window.getMembergetMember("document");("document"); location = (JSObject)document.location = (JSObject)document.getMembergetMember("location");("location"); getContentPane().addMouseListener(new MouseAdapter() {getContentPane().addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {public void mouseClicked(MouseEvent e) { String colCode = Integer.toHexString(bgColor.getRGB());String colCode = Integer.toHexString(bgColor.getRGB()); colCode = "#" + colCode.substring(2);colCode = "#" + colCode.substring(2); document.document.evaleval("setBodyBackround(\"" + colCode + "\")");("setBodyBackround(\"" + colCode + "\")"); }}
});});}}public void setColor(public void setColor(StringString newbgColor, newbgColor, StringString newfgColor) { newfgColor) { bgColor = Color.decode(newbgColor); fgColor = Color.decode(newfgColor);bgColor = Color.decode(newbgColor); fgColor = Color.decode(newfgColor); setBackground(bgColor);setBackground(bgColor); start();start();}}public void setDelay(public void setDelay(StringString milisec) { milisec) { delay = delay = Integer.parseIntInteger.parseInt(milisec);(milisec); start();start();}}……
Methods to be Methods to be called by called by JavaScriptJavaScript
Accessing DOM Accessing DOM elements via JSObjectelements via JSObject
Calling a function in Calling a function in JavaScriptJavaScript
July 21, 2004 8 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
JSObjectJSObject A A Java-side objectJava-side object that allows the Java program to that allows the Java program to
interact with JavaScriptinteract with JavaScript Main Methods:Main Methods:
callcall: calls a JavaScript method : calls a JavaScript method evaleval: evaluates a JavaScript expression : evaluates a JavaScript expression getMembergetMember: retrieves a named member of an object : retrieves a named member of an object getSlotgetSlot: retrieves an indexed member of an object : retrieves an indexed member of an object setMembersetMember: sets a named member of an object : sets a named member of an object setSlotsetSlot: sets an indexed member of an object : sets an indexed member of an object removeMemberremoveMember: removes a named member of an object: removes a named member of an object
To compile the applet, ‘To compile the applet, ‘jaws.jarjaws.jar’, which is available ’, which is available in JRE must be included in the in JRE must be included in the classpathclasspath
http://developer.netscape.com/docs/technote/javascript/liveconnect/liveconnect_rh.html
July 21, 2004 9 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
The HTML CodeThe HTML Code <body><body> <OBJECT<OBJECT ID=" ID="icuAppleticuApplet" WIDTH="600" HEIGHT="50" border="0" classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"" WIDTH="600" HEIGHT="50" border="0" classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
ALIGN="middle“ codebase="http://java.sun.com/products/plugin/1.4/jinstall-14-win32.cab#Version=1,4,0,mn">ALIGN="middle“ codebase="http://java.sun.com/products/plugin/1.4/jinstall-14-win32.cab#Version=1,4,0,mn"> <PARAM NAME=CODE VALUE="<PARAM NAME=CODE VALUE="AppletTestLiveConnect.classAppletTestLiveConnect.class" >" > <PARAM NAME=CODEBASE VALUE="./"><PARAM NAME=CODEBASE VALUE="./"> <PARAM NAME="type" VALUE="application/x-java-applet;jpi-version=1.4"><PARAM NAME="type" VALUE="application/x-java-applet;jpi-version=1.4"> <PARAM NAME="scriptable" VALUE="true"><PARAM NAME="scriptable" VALUE="true"> <PARAM NAME="<PARAM NAME="messagemessage" VALUE="" VALUE="Information and Communications UniversityInformation and Communications University">"> <COMMENT><COMMENT>
<EMBED ID="<EMBED ID="icuAppleticuApplet" type="application/x-java-applet;jpi-version=1.4" CODE="" type="application/x-java-applet;jpi-version=1.4" CODE="AppletTestLiveConnect.classAppletTestLiveConnect.class““ CODEBASE="./" WIDTH="600" HEIGHT="50“ ALIGN="middle" CODEBASE="./" WIDTH="600" HEIGHT="50“ ALIGN="middle" message="Information and Communications University"message="Information and Communications University" scriptable=true pluginspage="http://java.sun.com/products/plugin/1.4/plugin-install.html">scriptable=true pluginspage="http://java.sun.com/products/plugin/1.4/plugin-install.html"></EMBED></EMBED>
</COMMENT></COMMENT> </OBJECT></OBJECT>
<FORM <FORM NAME="widgets1">NAME="widgets1"> Select Background Color:Select Background Color: <SELECT NAME="backgroundColor" <SELECT NAME="backgroundColor" onChange="onChange="setColor(this.form)setColor(this.form)"">> <OPTION SELECTED VALUE="#FFFFFF">White</OPTION><OPTION VALUE="#000000">Black</OPTION> <OPTION SELECTED VALUE="#FFFFFF">White</OPTION><OPTION VALUE="#000000">Black</OPTION> …… </SELECT></SELECT> Select Text Color:Select Text Color: <SELECT NAME="foregroundColor" <SELECT NAME="foregroundColor" onChange="onChange="setColor(this.form)setColor(this.form)"">> <OPTION VALUE="#FFFFFF">White</OPTION> <OPTION VALUE="#FFFFFF">White</OPTION> …… </SELECT><BR/></SELECT><BR/> Enter the delay time in miliseconds:Enter the delay time in miliseconds: <INPUT NAME="delay" TYPE="text" VALUE="10" <INPUT NAME="delay" TYPE="text" VALUE="10" onChange="onChange="setDelay(this.form)setDelay(this.form)""/>/>
</FORM></FORM>……
Calling JavaScript Calling JavaScript functionsfunctions
July 21, 2004 10 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
The JavaScript CodeThe JavaScript Code<script language = "JavaScript"><script language = "JavaScript">
function setDelay(form) {function setDelay(form) { var milisec = form.delay.value;var milisec = form.delay.value;
// send data to applet// send data to applet document.icuApplet.setDelay(milisec);document.icuApplet.setDelay(milisec);
}}
function setColor(form) {function setColor(form) { var bg = form.backgroundColor.options[form.backgroundColor.selectedIndex].value;var bg = form.backgroundColor.options[form.backgroundColor.selectedIndex].value; var fg = form.foregroundColor.options[form.foregroundColor.selectedIndex].value;var fg = form.foregroundColor.options[form.foregroundColor.selectedIndex].value; // send data to applet// send data to applet document.document.icuApplet.setColoricuApplet.setColor(bg, fg);(bg, fg); }}
function setBodyBackround(bgColor) {function setBodyBackround(bgColor) { alert("Setting the background color to "+bgColor);alert("Setting the background color to "+bgColor); document.body.setAttribute("bgColor", bgColor);document.body.setAttribute("bgColor", bgColor); }}</script></script>
Function to be called Function to be called by the Java Appletby the Java Applet
Calling the methods Calling the methods in the Java Appletin the Java Applet
July 21, 2004 11 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
Calling Applet Methods from Calling Applet Methods from JavaScriptJavaScript
documentdocument.appletName.varName.appletName.varName documentdocument.appletName.methodName(param.appletName.methodName(param
eters)eters) documentdocument..appletsapplets[i].varName[i].varName documentdocument..appletsapplets[i].methodName(paramet[i].methodName(paramet
ers)ers)
July 21, 2004 12 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
References for Java/JavaScript References for Java/JavaScript ConnectionConnection
LiveConnect: LiveConnect: http://developer.netscape.com/docs/technote/javascript/liveconnect/http://developer.netscape.com/docs/technote/javascript/liveconnect/liveconnect_rh.htmlliveconnect_rh.html
The Java/JavaScript Connection by Danny Goodman: The Java/JavaScript Connection by Danny Goodman: http://developer.netscape.com/viewsource/archive/goodman_liveconnect.htmlhttp://developer.netscape.com/viewsource/archive/goodman_liveconnect.html
Java-to-Javascript Communication: Java-to-Javascript Communication: http://java.sun.com/j2se/1.4.2/docs/guide/plugin/developer_guide/java_js.htmlhttp://java.sun.com/j2se/1.4.2/docs/guide/plugin/developer_guide/java_js.html
How Java to Javascript Communication Works in Java How Java to Javascript Communication Works in Java Plug-in: Plug-in: http://java.sun.com/products/plugin/1.3/docs/jsobject.html http://java.sun.com/products/plugin/1.3/docs/jsobject.html
JSObject API: JSObject API: http://wp.netscape.com/eng/mozilla/3.0/handbook/plugins/doc/netscape.javaschttp://wp.netscape.com/eng/mozilla/3.0/handbook/plugins/doc/netscape.javascript.JSObject.htmlript.JSObject.html
JavaScript DOM: http://krook.org/jsdom/JavaScript DOM: http://krook.org/jsdom/
July 21, 2004 13 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
CGI (Common Gateway Interface)CGI (Common Gateway Interface)
A common wayA common way to specify to specify computationscomputations, , interactions with interactions with usersusers, or to, or to provide provide access to databasesaccess to databases on the Web on the Web
AAllowllowss browsers to request the execution of browsers to request the execution of server-resident server-resident softwaresoftware
AAn n interface between browsers and serversinterface between browsers and servers An HTTP request to run a CGI program specifies a An HTTP request to run a CGI program specifies a programprogram, ,
rather than a documentrather than a document Servers can recognize such requests in two ways:Servers can recognize such requests in two ways:
By the location of the requested file (By the location of the requested file (special subdirectoriesspecial subdirectories, e.g., cgi_bin, e.g., cgi_bin)) A server can be configured to recognize executable files by their A server can be configured to recognize executable files by their file file
name extensionsname extensions
A CGI program can produce a complete A CGI program can produce a complete HTTPHTTP r responseesponse, or , or just the just the URLURL of an existing document of an existing document
AW lecture notes
July 21, 2004 14 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
CGI ArchitectureCGI Architecture
http://ironbark.bendigo.latrobe.edu.au/subjects/int32we/lectures/w08.d/Lect16.html
July 21, 2004 15 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
CGI LinkageCGI Linkage Some CGI programs are in Some CGI programs are in machine codemachine code, but Perl, but Perl
programs are usually kept in programs are usually kept in source formsource form A source file can be A source file can be made to be “executable” by adding a made to be “executable” by adding a
line at their beginningline at their beginning that specifies that a language that specifies that a language processing program be run on them firstprocessing program be run on them first
e.g., UNIXe.g., UNIX #!/usr/local/bin/perl #!/usr/local/bin/perl ––ww
WindowsWindows #!/#!/ProgramsPrograms/perl/bin/perl -w/perl/bin/perl -w
An HTML document specifies a CGI program with an An HTML document specifies a CGI program with an anchor taganchor tag
<a href = "http://<a href = "http://www.icu.ac.krwww.icu.ac.kr/cgi-bin/reply.pl>"/cgi-bin/reply.pl>"
Click here to run the CGI program, reply.plClick here to run the CGI program, reply.pl
</a></a>
AW lecture notes
July 21, 2004 16 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
CGI Linkage CGI Linkage (cont.)(cont.)
The HTTP header needs only the content type, The HTTP header needs only the content type, followed by a blank line:followed by a blank line:
print "Content-type: text/html \n\n";print "Content-type: text/html \n\n"; A sample CGI program:A sample CGI program:
#!/usr/local/bin/perl
# reply.pl – a CGI program that returns a greeting to the user
print "Content-type: text/html \n\n",
"<html> <head> \n",
"<title> reply.pl example </title>",
" </head> \n", "<body> \n",
"<h1> Greetings from your Web server!",
" </h1> \n </body> </html> \n";AW lecture notes
July 21, 2004 17 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
HTML FormsHTML Forms The most common way for a user to communicate The most common way for a user to communicate
information from a Web browser to the serverinformation from a Web browser to the server Provide tags to generate the commonly used objects, Provide tags to generate the commonly used objects,
called called widgetswidgetsee.g., checkboxes, radio buttons, menus, submit & reset .g., checkboxes, radio buttons, menus, submit & reset buttons, buttons, ……
Widgets are used to gather information from the user, Widgets are used to gather information from the user, in the in the formform
Values of all widgets in a form are called Values of all widgets in a form are called form dataform data When the user presses tWhen the user presses thhe e Submit buttonSubmit button, the form , the form
data is encoded in a data is encoded in a query stringquery string, and sent to the , and sent to the serverserver
July 21, 2004 18 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
HTML Form ExampleHTML Form Example<FORM action="http://somesite.com/prog/adduser“ <FORM action="http://somesite.com/prog/adduser“ method="post"method="post">><P><P>First name: <INPUT type="First name: <INPUT type="texttext" name="firstname“/><BR/>" name="firstname“/><BR/>Last name: <INPUT type="Last name: <INPUT type="texttext" name="lastname“/><BR/> " name="lastname“/><BR/> email: <INPUT type="email: <INPUT type="texttext" name="email“/><BR/>" name="email“/><BR/><INPUT type="<INPUT type="radioradio" name="sex" value="Male“/> Male<BR/>" name="sex" value="Male“/> Male<BR/><INPUT type="<INPUT type="radioradio" name="sex" value="Female“/> Female<BR/> " name="sex" value="Female“/> Female<BR/> <INPUT type="<INPUT type="submitsubmit" value="Send“/>" value="Send“/><INPUT type="<INPUT type="resetreset“/>“/></P> </P> </FORM> </FORM>
July 21, 2004 19 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
GET and POSTGET and POST GET (default method)GET (default method)
The browser The browser attaches the query string to the URLattaches the query string to the URL of the CGI of the CGI program (after ‘?’)program (after ‘?’)
The server removes the query string from the URL and places it in The server removes the query string from the URL and places it in the environmental variable the environmental variable QUERY_STRINGQUERY_STRING
DisadvantagesDisadvantages Some servers place a Some servers place a limit on the length of the URL stringlimit on the length of the URL string The query string is The query string is vulnerable to illegal accessvulnerable to illegal access
POSTPOST The query string is passes through standard input of the CGI The query string is passes through standard input of the CGI
programprogram The length of the query string is padded through the environmental The length of the query string is padded through the environmental
variable variable CONTENT_LENGTHCONTENT_LENGTH No length limitation for the query stringNo length limitation for the query string
July 21, 2004 20 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
Query String FormatQuery String Format A query string includes A query string includes namesnames and and valuesvalues of widgets of widgets Widget values are always Widget values are always coded as stringscoded as strings The form of a name/value pair in a query string is: The form of a name/value pair in a query string is:
name=valuename=value If the form has more than one widget, their values are If the form has more than one widget, their values are
separated with ampersandsseparated with ampersandse.g., e.g., milk=2milk=2&&payment=visapayment=visa
Each Each special characterspecial character is coded as a percent sign and a is coded as a percent sign and a two-character hexadecimal number (the ASCII code for the two-character hexadecimal number (the ASCII code for the character)character) Hangul is encoded in this wayHangul is encoded in this way Some browsers code Some browsers code spacesspaces as as plus signsplus signs, rather than as , rather than as %20%20
AW lecture notes
July 21, 2004 21 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
Decoding Query StringDecoding Query String1.1. Read the query string from Read the query string from $ENV{QUERY_STRING}$ENV{QUERY_STRING}2.2. If the If the $ENV{REQUEST_METHOD}$ENV{REQUEST_METHOD} is is POSTPOST, determine the , determine the
size of the request using size of the request using $ENV{CONTENT_LENGTH}$ENV{CONTENT_LENGTH} and and read that amount of data from the standard inputread that amount of data from the standard input. . Append this Append this data to the data read from the query stringdata to the data read from the query string, if present (this , if present (this should beshould be joined with "&" joined with "&"))
3.3. Split the result on the " &" characterSplit the result on the " &" character, which separates name-, which separates name-value pairsvalue pairs
4.4. Split each name-value pairSplit each name-value pair on the "=" character to get the on the "=" character to get the name and valuename and value
5.5. Decode the URL-encoded charactersDecode the URL-encoded characters in the name and value in the name and value6.6. Associate each name with its value(s); remember that each Associate each name with its value(s); remember that each
option name may have multiple valuesoption name may have multiple valueshttp://www.hk8.org/old_web/linux/cgi/ch04_03.htm
July 21, 2004 22 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
Query-string Decoding ExampleQuery-string Decoding Example
my %form_data;my %form_data;my $name_value;my $name_value;my @name_value_pairs = split /&/, my @name_value_pairs = split /&/, $ENV{QUERY_STRING}$ENV{QUERY_STRING};;if ( if ( $ENV{REQUEST_METHOD}$ENV{REQUEST_METHOD} eq 'POST' ) { eq 'POST' ) {
my $query = "";my $query = "";readread( ( STDINSTDIN, $query, , $query, $ENV{CONTENT_LENGTH}$ENV{CONTENT_LENGTH} ) == ) ==
$ENV{CONTENT_LENGTH} or return undef;$ENV{CONTENT_LENGTH} or return undef;push @name_value_pairs, split /&/, $query;push @name_value_pairs, split /&/, $query;
}}foreach $name_value ( @name_value_pairs ) {foreach $name_value ( @name_value_pairs ) {
my( $name, $value ) = split /=/, $name_value;my( $name, $value ) = split /=/, $name_value;$name =~ tr/+/ /;$name =~ tr/+/ /;$name =~ s/%([\da-f][\da-f])/chr( hex($1) )/egi;$name =~ s/%([\da-f][\da-f])/chr( hex($1) )/egi;$value = "" unless defined $value;$value = "" unless defined $value;$value =~ tr/+/ /;$value =~ tr/+/ /;$value =~ s/%([\da-f][\da-f])/chr( hex($1) )/egi;$value =~ s/%([\da-f][\da-f])/chr( hex($1) )/egi;$form_data{$name} = $value;$form_data{$name} = $value;
}}
July 21, 2004 23 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
CGI ReferencesCGI References
W3C’s CGI Pages: W3C’s CGI Pages: http://www.w3.org/CGI/http://www.w3.org/CGI/
CGI Made Really EasyCGI Made Really Easy: : http://http://www.jmarshall.com/easy/cgiwww.jmarshall.com/easy/cgi//
A CGI Tutorial: A CGI Tutorial: http://tech.irt.org/articles/js171/http://tech.irt.org/articles/js171/
CGI Programming with Perl: CGI Programming with Perl: http://www.hk8.org/old_web/linux/cgi/index.htmhttp://www.hk8.org/old_web/linux/cgi/index.htm
July 21, 2004 24 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
PerlPerl Began in the late 1980s as a more powerfulBegan in the late 1980s as a more powerful
replacement for the capabilities of replacement for the capabilities of awkawk (text file (text file processing) and processing) and shsh (UNIX system administration) (UNIX system administration)
Now includes sockets for communications andNow includes sockets for communications and modules for OOPmodules for OOP
Now the most commonly used language for CGI,Now the most commonly used language for CGI, in part because of its in part because of its pattern matching capabilitiespattern matching capabilities
Perl programs are usually processed the same Perl programs are usually processed the same way as many Java programs, compilation to anway as many Java programs, compilation to an intermediate formintermediate form, followed by interpretation, followed by interpretation
AW lecture notes
July 21, 2004 25 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
Perl Perl (cont.)(cont.)
Example program:Example program:
print "Please input the circle’s radius: ";print "Please input the circle’s radius: ";$radius = <STDIN>;$radius = <STDIN>;$area = 3.14159265 * $radius * $radius;$area = 3.14159265 * $radius * $radius;print "The area is: $area \n";print "The area is: $area \n";
RRununningning a Perl program: a Perl program:perl prog1.plperl prog1.plTwo useful flags:Two useful flags:
-c-c means compile only (for error checking) means compile only (for error checking)-w-w means produce warnings for suspicious stuff means produce warnings for suspicious stuff
AW lecture notes
July 21, 2004 26 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
Pattern Matching in PerlPattern Matching in Perl The default string against which the pattern is The default string against which the pattern is
matched is in matched is in $_$_ Character and character-class patternsCharacter and character-class patterns
MetacharactersMetacharacters: : \ | ( ) [ ] { } ^ $ * + ? .\ | ( ) [ ] { } ^ $ * + ? . A A non-metanon-meta, or normal character matches itself, or normal character matches itself
if (/gold/) {if (/gold/) { print print ""There's gold in that thar string!! \n";There's gold in that thar string!! \n";}}
Metacharacters can match themselves if they are Metacharacters can match themselves if they are backslashedbackslashed
The The periodperiod matches any character except newline matches any character except newline /a.b//a.b/ matches matches "aab", "abb", "acb""aab", "abb", "acb", ..., ... AW lecture notes
July 21, 2004 27 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
Character ClassesCharacter Classes A character class is a string in bracketsA character class is a string in brackets – e.g., – e.g., [abc][abc]
means a | b | cmeans a | b | c A dash can be used to specify a range of charactersA dash can be used to specify a range of characters – e.g., – e.g.,
[A-Za-z][A-Za-z] If a character class begins with a circumflex,If a character class begins with a circumflex, it means the oppositeit means the opposite
– e.g., – e.g., [[^A-Z]^A-Z] matches any character except an uppercase letter matches any character except an uppercase letter
Predefined character classes:Predefined character classes:NameName Equivalent PatternEquivalent Pattern MatchesMatches\d\d [0-9][0-9] a digita digit\D\D [^0-9][^0-9] not a digitnot a digit\w\w [A-Za-z_0-9][A-Za-z_0-9] a word charactera word character\W\W [^A-Za-z_0-9][^A-Za-z_0-9] not a word characternot a word character\s\s [ \r\t\n\f][ \r\t\n\f] a whitespace charactera whitespace character\S\S [^ \r\t\n\f][^ \r\t\n\f] not a whitespace characternot a whitespace character
AW lecture notes
July 21, 2004 28 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
Pattern Quantifiers and Pattern Quantifiers and Predefined PatternsPredefined Patterns
Pattern QuantifiersPattern Quantifiers pattern{n}pattern{n} means repeat the pattern n times means repeat the pattern n times – e.g., – e.g.,
/a{5}bc{5}//a{5}bc{5}/ pattern*pattern* means repeat the pattern zero or more times means repeat the pattern zero or more times – –
e.g.,e.g., /a*bc*//a*bc*/ pattern+pattern+ means repeat the pattern 1 or more times means repeat the pattern 1 or more times pattern?pattern? means zero or one match means zero or one match – e.g., – e.g., /\d*b?c+//\d*b?c+/
Two more useful predefined patterns:Two more useful predefined patterns: \b\b - matches - matches a word boundarya word boundary \B\B - matches a non-word boundary - matches a non-word boundary
e.g.,e.g., /\bis\b//\bis\b/ -- matches " matches "what it iswhat it is" and "" and "that is itthat is it"" /\Bis\B//\Bis\B/ -- matches " matches "thistlethistle" and "" and "artistartist"" /\bis\B//\bis\B/ -- matches " matches "istanbulistanbul" and "" and "so--isn't that butter?so--isn't that butter?"" /\Bis\b//\Bis\b/ -- matches " matches "confutatisconfutatis" and "" and "metropolis near youmetropolis near you" " AW lecture notes
July 21, 2004 29 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
Binding Operators, Anchors and Binding Operators, Anchors and Pattern ModifiersPattern Modifiers
Binding OperatorsBinding Operators - to match against a string - to match against a string other than the string in other than the string in $_$_
$str $str =~=~ /\w/; /\w/; $str $str !~!~ /\w/; /\w/;
AnchorsAnchors - match positions, not characters - match positions, not characters ^̂ in front of a patternin front of a pattern (not in a character class) (not in a character class) means means
the pattern must match at the beginningthe pattern must match at the beginning $$ at the end of a patternat the end of a pattern means the pattern must match means the pattern must match
at the end at the end Pattern modifiersPattern modifiers (after the pattern) (after the pattern)
ii makes letters in the pattern makes letters in the pattern match either uppercase or match either uppercase or lowercaselowercase
xx allows whitespace in the patternallows whitespace in the pattern, including comments, including commentsAW lecture notes
July 21, 2004 30 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
Remembering PatternsRemembering Patterns
After the match, the implicit variables After the match, the implicit variables $1, $2, …$1, $2, … have the parts of the string that matched the first, have the parts of the string that matched the first, second, … second, … parenthesized subpatternparenthesized subpattern
e.g., e.g., "John Fitzgerald Kennedy" =~ /(\w+) (\w+) (\w+)/;"John Fitzgerald Kennedy" =~ /(\w+) (\w+) (\w+)/;
Now, $1 has "John", $2 has "Fitzgerald", Now, $1 has "John", $2 has "Fitzgerald", and and
$3$3 has "Kennedy"has "Kennedy" Parts that preceded, matched and followedParts that preceded, matched and followed
$`$` has the part of the string before the part that has the part of the string before the part that matchedmatched $&$& has the part of the string that matched has the part of the string that matched $’$’ has the part of the string after the part that has the part of the string after the part that matchedmatched
AW lecture notes
July 21, 2004 31 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
SubstitutionsSubstitutions Used to find and replace a substringUsed to find and replace a substring
s/Pattern/New_String/s/Pattern/New_String/e.g., e.g., $_ = "Darcy is her name, yes, it’s Darcy"$_ = "Darcy is her name, yes, it’s Darcy"
s/Darcy/Darcie/;s/Darcy/Darcie/; ModifiersModifiers
The The gg modifier means find and replace modifier means find and replace allall of them in the of them in the stringstring
The The ee modifier means the New_String must be modifier means the New_String must be interpreted as Perl codeinterpreted as Perl code
e.g.,e.g., Find a single hex character and Find a single hex character and replace it with its decimal value replace it with its decimal value (unsigned char value)(unsigned char value)
s/%([\dA-Fa-f])/pack("C", hex($1))/e;s/%([\dA-Fa-f])/pack("C", hex($1))/e; The The ii modifier modifier means case-insensitive matchingmeans case-insensitive matching
AW lecture notes
July 21, 2004 32 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
Translate OperatorTranslate Operator
Translates a character or character class into Translates a character or character class into another character or character classanother character or character class
e.g., e.g., tr/a-z/A-Z/;tr/a-z/A-Z/;
Transliterates all lowercase letters to upperTransliterates all lowercase letters to upper
AW lecture notes
July 21, 2004 33 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
CGI.pm ModuleCGI.pm Module A A Perl modulePerl module serves as serves as a librarya library The Perl use declaration is used to The Perl use declaration is used to make a make a
module availablemodule available to a program to a program To make only part of a module available, specify the To make only part of a module available, specify the
part name after a colonpart name after a colone.g., e.g., use CGI ":standard";use CGI ":standard";
Common CGI.pm FunctionsCommon CGI.pm Functions ““Shortcut” functions produce tagsShortcut” functions produce tags, using their , using their
parameters as attribute valuesparameters as attribute valuese.g., e.g., h2("Very easy!");h2("Very easy!"); produces produces <h2> Very easy! </h2><h2> Very easy! </h2>
In this example, the parameter to the function h2 is In this example, the parameter to the function h2 is used as the content of the <h2> tagused as the content of the <h2> tag
AW lecture notes
July 21, 2004 34 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
CGI.pm ModuleCGI.pm Module (cont.) (cont.)
Tags can have both content and attributesTags can have both content and attributes Each attribute is passed as a name/value pair, just as in a hash Each attribute is passed as a name/value pair, just as in a hash
literalliteral Attribute namesAttribute names are passed with are passed with a preceding dasha preceding dash
e.g., e.g., textarea(-name => "Description", -rows => "2", -cols => "35");textarea(-name => "Description", -rows => "2", -cols => "35"); Produces: Produces:
<textarea name ="Description" rows=2 cols=35> </textarea><textarea name ="Description" rows=2 cols=35> </textarea> Tags and their attributes are distributed over the Tags and their attributes are distributed over the
parameters of the functionparameters of the functione.g., e.g., ol(li({-type => "square"}, ["milk", "bread", "cheese"]));ol(li({-type => "square"}, ["milk", "bread", "cheese"]));
Output: <ol>Output: <ol><li type="square"milk</li><li type="square"milk</li><li type="square"bread</li><li type="square"bread</li><li type="square"cheese</li><li type="square"cheese</li>
</ol></ol>
AW lecture notes
July 21, 2004 35 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
CGI.pm ModuleCGI.pm Module (cont.) (cont.)
Producing output for return to the userProducing output for return to the user A call to A call to header()header() produces: produces:
Content-type: text/html;charset=ISO-8859-1Content-type: text/html;charset=ISO-8859-1
-- blank line -- blank line ––
The start_html function is used to create the head of the The start_html function is used to create the head of the return document, as well as the <body> tagreturn document, as well as the <body> tag The parameter to The parameter to start_htmlstart_html is used as the title of the document is used as the title of the document
e.g., e.g., start_htmlstart_html(("Bill’s Bags""Bill’s Bags"););DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml11-transitional.dtd">"DTD/xhtml11-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml lang="en-US"><html xmlns="http://www.w3.org/1999/xhtml lang="en-US">
<head><title>Bill’s Bags</title><head><title>Bill’s Bags</title>
</head><body></head><body> The The end_htmlend_html function generates function generates </body></html></body></html> AW lecture notes
July 21, 2004 36 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
CGI.pm ModuleCGI.pm Module (cont.) (cont.)
The The paramparam function is given a widget’s name; function is given a widget’s name; it returns the widget’s valueit returns the widget’s value If the query string has If the query string has name=Abrahamname=Abraham in it, in it,
param("name")param("name") will return "Abraham“ will return "Abraham“ee.g., .g., my($age, $gender, $vote) =my($age, $gender, $vote) =
(param("age"), param("gender"), param("vote"));(param("age"), param("gender"), param("vote"));
AW lecture notes
July 21, 2004 37 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
CookiesCookies A A sessionsession is the is the collection of all of the requests collection of all of the requests
made by a particular browsermade by a particular browser from the time the from the time the browser is started until the user exits the browserbrowser is started until the user exits the browser
The HTTP protocol is The HTTP protocol is statelessstateless, but, there are , but, there are several reasons why it is useful for the server to several reasons why it is useful for the server to relate a request to a sessionrelate a request to a session Shopping cartsShopping carts for many different simultaneous for many different simultaneous
customerscustomers Customer profilingCustomer profiling for advertising for advertising Customized interfacesCustomized interfaces for specific clients for specific clients
Approaches to storing client information:Approaches to storing client information: Store it on the serverStore it on the server – too much to store! – too much to store! Store it on the client machineStore it on the client machine –– this works this works AW lecture notes
July 21, 2004 38 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
CookiesCookies (cont.) (cont.) A A cookiecookie is an object sent by the server to the client is an object sent by the server to the client Cookies are created by some software system on the server Cookies are created by some software system on the server
(maybe a CGI program)(maybe a CGI program) Every HTTP communication between the browser and the Every HTTP communication between the browser and the
server server includes information in its headerincludes information in its header about the message about the message At the time a cookie is created, it is given a lifetimeAt the time a cookie is created, it is given a lifetime Every time the browser sends a requestEvery time the browser sends a request to the server that to the server that
created the cookie, while the cookie is still alive, created the cookie, while the cookie is still alive, the cookie is the cookie is includedincluded
A browser can be set to reject all cookiesA browser can be set to reject all cookies CGI.pm includes support for cookiesCGI.pm includes support for cookies
cookiecookie(-(-namename => a_name, - => a_name, -valuevalue => a_value, - => a_value, -expiresexpires => a_time); => a_time); The name can be any stringThe name can be any string The value can be any scalar valueThe value can be any scalar value The time is a number followed by a unit code The time is a number followed by a unit code (d, s, m, h, M, y)(d, s, m, h, M, y)
July 21, 2004 39 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
CookiesCookies (cont.) (cont.) Cookies must be placed in the HTTP header at the time the Cookies must be placed in the HTTP header at the time the
header is created - header is created - header(-cookie => $my_cookie);header(-cookie => $my_cookie); To fetch the cookies from an HTTP request, call To fetch the cookies from an HTTP request, call cookiecookie with with
no parametersno parameters –– A hash of all cookies is returned A hash of all cookies is returned To fetch the value of one particular cookie, send the cookie’s To fetch the value of one particular cookie, send the cookie’s
name to the name to the cookiecookie function, function, e.g., e.g., $age = $age = cookiecookie(′age′);(′age′);
Example: A cookie that Example: A cookie that tells the client the time of his or her tells the client the time of his or her last visitlast visit to this site to this site Use the Perl function, Use the Perl function, localtimelocaltime, to get the parts of time, to get the parts of time
($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtimelocaltime;;@day_stuff = ($sec, $min, $hour, $mday, $mon, $year);@day_stuff = ($sec, $min, $hour, $mday, $mon, $year);$day_cookie = $day_cookie = cookiecookie(-(-namename => 'last_time', => 'last_time',
--valuevalue => \@day_stuff, - => \@day_stuff, -expiresexpires => => '+5d');'+5d');
July 21, 2004 40 Programming for WWW (Lecture#8) In-Young Ko, Information Communications University
Perl ReferencesPerl References Textbook chapters 4 and 5Textbook chapters 4 and 5 Perl.com: Perl.com: http://www.perl.com/http://www.perl.com/
A Perl Tutorial: A Perl Tutorial: http://http://www.comp.leeds.ac.uk/Perl/start.htmlwww.comp.leeds.ac.uk/Perl/start.html
Perl Pattern Matching: Perl Pattern Matching: http://www.sarand.com/td/ref_perl_pattern.htmlhttp://www.sarand.com/td/ref_perl_pattern.html
Perl Functions: Perl Functions: http://www.sunsite.ualberta.ca/Documentation/Misc/perl-5.http://www.sunsite.ualberta.ca/Documentation/Misc/perl-5.6.1/pod/perlfunc.html6.1/pod/perlfunc.html
Perl Modules:Perl Modules: http://www.cpan.org/modules/ http://www.cpan.org/modules/