Introduction to Web Programming Gary Stewart gstewart@cs.uct.ac.za World Wide Web • The World Wide Web is a hypertext based system on the internet • Developed by Tim Berners-Lee • Although it forms just one part of the internet, it is the one most people are familiar with • It is used for research, recreation, business, etc. 2 Client-Server • The World Wide Web uses a simple clientserver based model • Information resides on a central server and is distributed to many different clients • The web server is typically a high end computer running a web server application • Clients can be personal computers, tablets, cellphones running a browser 3 Web Servers and Browsers • There a number of web servers available – Apache, Internet Information Server (IIS) • There are a number of browsers available – Internet Explorer, Mozilla Firefox, Google Chrome, Apple Safari • Web servers store and serve/issue pages • The browser is responsible for interpreting the HTML and drawing/rendering the page • Different browsers may render a page slightly differently 4 Web Programming • Web programming is complex, using a many different “programming languages” – Content: HyperText Markup Language (HTML) – Style: Cascading Style Sheets (CSS) – Client-Side Scripting: Javascript – Server-Side Scripting: e.g. PHP, ASP, JSP or Python 5 HTML • HTML is used to define the content/text to be displayed on the page • Text is surrounded by tags which specify how the text should be displayed • Tags are defined between less than < and greater than > signs and usually come in pairs, open and close, close has a slash / <TITLE>My Homepage</TITLE> • HTML files are saved with *.html extension 6 HTML: Standard Page Structure • HTML pages have a standard page structure <HTML> <HEAD> <TITLE>Appears in the title bar of the browser</TITLE> </HEAD> <BODY> Appears in the main browser window. </BODY> </HTML> 7 HTML: Common Tags • There are a number of HTML common tags, e.g.: – – – – – – – <P>, for defining new paragraphs <UL>,<OL>,<LI>, for defining lists <TABLE><TR><TD>, for defining tables <DIV>, for blocking sections of the page <IMG>, for specifying images <A>, anchor for specifying links <LINK>, <SCRIPT>, for importing styles and scripts 8 HTML: Tag attributes • Tags can have attributes which specify additional properties, e.g. – width <TABLE width=“200”> … </TABLE> – alignment <P align=“center”> … </P> – id, unique identifier <DIV id=“sidebar”> … </DIV> – class, groups related <P class=“subheading”> … </P> 9 HTML: Paragraph & Whitespace • The <P> tag defines a new paragraph on a new line <P>This is a new paragraph.</P> • The <BR> tag is used to start a new line and doesn’t require a closing tag End of the line.<BR> • The HTML escape sequence &nbsp; is used for spacing Extra &nbsp;&nbsp;&nbsp; spaces 10 HTML: Image • The <IMG> tag is used to insert images and doesn’t require a closing tag • It has a src attribute for specifying the image source <IMG src=“images\pic.jpg”> • Browsers can only images in the following formats – GIF, JPG, PNG 11 HTML: Lists • • • • HTML has ordered lists and unordered lists Ordered, numbered, lists use the <OL> tag Unordered lists use the <UL> tag List items are indicated with the <LI> tag <OL> <LI>first item</LI> <LI>second item</LI> <LI>third item</LI> </OL> 12 HTML: Tables • The <TABLE> tag is used to define a table • Table rows are indicated with the <TR> tag • Table data cells are indicated with the <TD> tag <TABLE> <TR><TD>cell 0,0</TD><TD>cell 0,1</TD></TR> <TR><TD>cell 1,0</TD><TD>cell 1,1</TD></TR> </TABLE> 13 HTML: Anchor • The <A> tag defines an anchor which is used to establish a link to another page • The href attribute is used to define a the page being linked to • The text or image display is placed between open and close tag <A href=“otherpage.html”>click this</A><BR> <A href=“http://www.uct.ac.za”><IMG src=“uct.jpg”></A> 14 HTML: Division • The <DIV> tag is used to group related blocked content • The related blocked content is nested within open and close <DIV> tags <DIV id=“footer”> <P>copyright</P> <IMG src=“logo.gif”> </DIV> 15 HTML: Comments • HTML comments are enclosed between <!-- and --> <!-- this is a comment --> 16 Cascading Style Sheets (CSS) • Cascading Style Sheets (CSS) are used to define the style for HTML pages • CSS files are saved with *.css extension • A CSS style file is typically referenced in the header of an HTML page <HEAD> <TITLE> … <TITLE> <LINK rel=“stylesheet” href=“styles.css”> </HEAD> 17 Cascading Style Sheets (CSS) • CSS defines how HTML tags, classes and IDs should be displayed • The styles are set by specifying values for various properties P {font-size:14px; font-family:Arial,sans-serif;} • CSS files allow the definition off all the styles for a website in one file ensuring easy maintenance 18 CSS: Comments • CSS comments are indicated between slash-asterisk pairs /* this is a comment */ 19 CSS:Setting Styles • Styles are set by first specifying the selector followed by all the necessary properties and values enclosed in curly brackets {} • Properties and values are separated by colons : • Property-value sets are separated by semi-colons ; P {font-size:14px; font-family:Arial,sans-serif;} 20 CSS: Tags, Classes, IDs • Selectors can be tags, classes or id’s • Tags are indicated as is P {font-size:14px; font-family:Arial,sans-serif;} • IDs are indicated with a hash # which will typically be applied to one HTML page item #banner {font-size:20px; font-family:Arial,sans-serif;} • Classes are indicated with a full stop . for application to a class of HTML page items .subheading {font-size:20px; font-family:serif;} 21 CSS: Common Properties • CSS has a number of common properties – text-align, for setting text alignment – font-family, for setting font family – font-size, for setting the font size – font-style, for setting font style – font-weight, for setting font weight – color, for setting the colour – background-color, for setting the background 22 CSS: Common Properties – top, for setting the topmost starting position – left, for setting the rightmost starting position – width, for setting the width – height, for setting the height 23 CSS: text-align and font-family • The text-align property is used to align text and has values left, right or center P.heading {text-align:center; font-size:16;} • The font-family property sets the text family has possible values “Times New Roman”, serif, Arial, sans-serif P.normal {font-family:Arial,sans-serif; font-size:12;} 24 CSS: font-size and font-style • The font-size property sets the font size and can be a reasonably sized integer P.heading {text-align:center; font-size:16;} • The font-style property sets the font style and can have values normal or italic P.spoken {font-size:12; font-style:italic;} • The font-weight property sets the font weight and can have values normal or bold P.emphasis {font-size:12; font-weight:bold;} 25 CSS: Colouring • CSS colours are set with color names – https://www.w3schools.com/colors/colors_names.asp or hexidecimal values of red, green, blue between 0 and 255, prefaced by a hash # • The color property sets the foreground color P.subheading{font-size:14;color:blue;} • The background-color sets the background colour .highlight{background-color:#993333;} 26 CSS Dimension • The default units for setting dimensions is pixels • The width property sets the width in pixels • The height property sets the height in pixels TABLE.data{width:400;height:300;} 27 CSS Positioning • CSS positioning references the top left corner of the screen as the 0,0 position • The default units for position is pixels • The position property sets the type of positioning • The left property sets the number of pixels from the left • The top property sets the number of pixels from the top DIV.sidebar{position:absolute;top:100;left:600;width:200;height:400;} 28 Javascript • Javascript is used for client-side scripting • It is similar to Java, particularly regarding syntax • Unlike Java, it is dynamically typed and can have standalone functions like Python • Javascript files have a *.js extension 29 Javascript • Many Javascript toolkits exist which add complex controls/widgets to a HTML page – menus, calendars, form validation • Javascript is used to access the Document Object Model (DOM) for manipulating the browser window and HTML document • Javascript programming is event-based <BUTTON type="button" value="Close" onclick="window.close()">Close</BUTTON> 30 Javascript • Javascript files are imported with the <SCRIPT> tag in the HTML page header <HEAD> <SCRIPT language="Javascript" src="menu.js"> </SCRIPT> </HEAD> • Javascript code is included in HTML page body with the <SCRIPT> tag <SCRIPT language="Javascript"> new menu (MENU_ITEMS, MENU_TPL); </SCRIPT> 31 HTML: Forms • HTML forms are used to gather information from the user • The <FORM> tag is used to define a form <FORM method=“post” action=“process_form.cgi”> <P>Student Number: <INPUT type=“text” name=“student_number”></P> <INPUT type=“submit” value=“Submit”> </FORM> 32 HTML: Forms • HTML forms can contain controls, e.g. – text edit, for entering text – combobox, for selecting from a drop down list – button, for clicking 33 HTML: Forms • The text edit is created using the <INPUT> tag and setting the type attribute to “text” • The name attribute should also set <INPUT type=“text” name=“student_number”> 34 HTML: Forms • The combobox is created using the <SELECT> tag with the name attribute also being set • Each combobox item is defined using the <OPTION> tag with its value attribute also being set <SELECT name=“faculty”> <OPTION value=“science”>Science</OPTION> <OPTION value=“law”>Law</OPTION> </SELECT> 35 HTML: Forms • Buttons are created using the <INPUT> tag and setting the type attribute to “button” <INPUT type=“button” value=“Click”> • HTML forms has a standard Reset button which is clicked to clear the form <INPUT type=“reset” value=“Reset”> • HTML forms has a standard Submit button which is clicked to process the form <INPUT type=“submit” value=“Submit”> 36 HTML: Form processing • Forms are processed by setting the method attribute to “post” • The action attribute is also specified, indicating which file will process the form <FORM method=“post” action=“process_form.cgi”> <P>Student Number: <INPUT type=“text” name=“student_number”></P> <INPUT type=“submit” value=“Submit”> </FORM> 37 Server Side Scripting • Server side scripting is used to dynamically create HTML pages • There are many programming tools for doing server side scripting, e.g. – PHP, ASP, JSP • Many of these involve mixing scripting language and HTML code • Python has many ways of doing server side scripting, the simplest being CGI 38 CGI • Common Gateway Interface (CGI) is a standard method for generate HTML pages with executable files • CGI files are programs written in scripting language which create HTML pages • CGI files usually have a *.cgi extension • The resulting content type must be set print('Content-type: text/html\n\n') #specify html content 39 Simple CGI # Filename: simple_cgi.cgi # generates simple HTML page def main(): print('Content-type: text/html\n\n') #specify html content head = '<HEAD><TITLE>Simple CGI</TITLE></HEAD>' body = '<BODY>Hello world</BODY>' print('<HTML>' + head + body + '</HTML>') main() 40 CGI: Templates • Python CGI can be simplified using basic templates • Basic templates can be created using the string format() method • This allows variable values to be inserted between HTML tags print(‘<P>Name:{0},Age:{1}</P>’.format(name,age)) 41 cgi module • The cgi module allows the creation of cgi scripts for processing forms import cgi • Create a FieldStorage object to access the form fields fields = cgi.FieldStorage() • Get each value by calling the getvalue() method and passing the form field name as a parameter name = fields.getvalue(‘name’) 42 Example <!-- word_form.html – creates simple form for saving a word to a file words.txt --> <HTML> <HEAD> <TITLE>Word Form</TITLE> <LINK rel="stylesheet" href="styles.css"> </HEAD> <BODY> <P class="heading">Save word to file</P> <DIV id="word_form"> <FORM method="post" action="save_word.cgi"> <TABLE> <TR><TD class="label">Word:</TD> <TD><INPUT type="text" name="word"></TD></TR> <TR><TD></TD> <TD><INPUT type="submit" value="Submit"></TD></TR> </TABLE> </FORM> </DIV> </BODY> </HTML> 43 Example /* styles.css - styles for word form */ #word_form{background-color:lightgray;} P.heading{font-family:Arial,sans-serif; font-size:16; color:blue;} .label{font-weight:bold; font-size:12; color:green;} 44 Example # save_word.cgi – processes form import cgi def write2file(word): # writes word to file words.txt and returns boolean try: f = open('words.txt','w') f.write(word) f.close() return True except: return False # continued on next page 45 Example def main(): fields = cgi.FieldStorage() word = fields.getvalue('word') written = write2file(word) # write word to file # generate results HTML page print('Content-type: text/html\n\n') #specify html content type print('<HTML><HEAD><TITLE>Save Word</TITLE></HEAD>') if written: print('<BODY>' + word + ' written.</BODY></HTML>') else: print('<BODY>' + word + ' not written.</BODY></HTML>') main() 46 Viewing HTML files • HTML files viewed in a browser from the file system have a file:// prefix in the address • HTML files viewed in a browser via a web server have a http:// prefix in the address – Although some browsers hide this http:// prefix • The web server run locally on a machine is referred to with address localhost http://localhost/ 47 Web Development Principles • Since web development is complex it is essential to follow good design principles • Create a good directory structure with separate folders for – images, containing all images – styles, containing CSS files – scripts, containing Javascript files – database, containing database files 48 Web Development Principles • Separate the content and style – content in HTML/CGI pages – style in CSS files • Ensuring minimal file sizes, allowing fast transfer • Ensuring that the interface looks good across different browsers • Ensuring good usability, user-friendliness 49 Resources • W3Schools – www.w3schools.com • Webmonkey – www.webmonkey.com • World Wide Web Consortium – www.w3.org 50