Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
1 of 74 4/2/2008 12:14 PM
Table of Contents | All Slides | Link List | CSCI E-12
Web 2.0, Ajax, Dynamic SitesApril 2, 2008
Harvard University Division of Continuing Education
Extension School
Course Web Site: http://cscie12.dce.harvard.edu/
Copyright 1998-2008 David P. Heitmeyer
Instructor email: [email protected] Course staff email: [email protected]
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
2 of 74 4/2/2008 12:14 PM
Web 2.0
Suggested readings for Web 2.0:
What Is Web 2.0: Design Patterns and Business Models for the Next Generation of Software byTim O'Reilly
Web 2.0, article from Wikipedia
What is Web 2.0?
Not a technical standard or technology
Web 2.0 does have characteristics and features
There are some technologies commonly found in Web 2.0
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
3 of 74 4/2/2008 12:14 PM
Web 2.0 Features and Characteristics
What Is Web 2.0: Design Patterns and Business Models for the Next Generation of Software by TimO'Reilly
Principles, Characteristics, Features:
Services, not packaged software, with cost-effective scalability
Control over unique, hard-to-recreate data sources that get richer as more people use them
Amazon
Trusting users as co-developers
Harnessing collective intelligence
Wikipedia
Leveraging the long tail through customer self-service
Google AdSense
Software above the level of a single device
Lightweight user interfaces, development models, AND business models
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
4 of 74 4/2/2008 12:14 PM
Web 2.0 in Images
User-contributed data (active and passive)
Mashups - combining, remixing data
External Services and Functionality
Rich User Interfaces and Rich Internet Applications
Web 2.0 Meme Map by Tim O'Reilly
Visualizing Web 2.0 by Dion Hinchcliffe
Visualizing Web 2.0, Peter, blog.forret.com
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
5 of 74 4/2/2008 12:14 PM
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
6 of 74 4/2/2008 12:14 PM
Web 2.0 Examples
Zillow
www.zillow.com
Housingmaps.com
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
7 of 74 4/2/2008 12:14 PM
www.housingmaps.com
ChicagoCrime.org
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
8 of 74 4/2/2008 12:14 PM
www.chicagocrime.org
Del.icio.us
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
9 of 74 4/2/2008 12:14 PM
del.icio.us
Flickr
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
10 of 74 4/2/2008 12:14 PM
flickr.com
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
11 of 74 4/2/2008 12:14 PM
Encyclopedia of Life
Encyclopedia of Life, www.eol.org
WASHINGTON (May 9, 2007) – Many of the world’s leading scientific institutions today announced the launchof the Encyclopedia of Life, an unprecedented global effort to document all 1.8 million named species ofanimals, plants, and other forms of life on Earth. For the first time in the history of the planet, scientists,students, and citizens will have multi-media access to all known living species, even those that have just beendiscovered. more
6 cornerstone institutions
9 data partners (and growing)
thousands of "curators"
tens (hundreds or more?) of thousands of potential contributors
Falco peregrinus (Peregrine Falcon)
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
12 of 74 4/2/2008 12:14 PM
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
13 of 74 4/2/2008 12:14 PM
Google News
news?hl=en&ned=us&q=Harvard+University
news?hl=en&ned=us&q=Harvard+University&output=rss
news?hl=en&ned=us&q=Harvard+University&output=atom
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
14 of 74 4/2/2008 12:14 PM
Amazon Web Services
Amazon.com offers several different web services, including one for e-commerce.
Amazon Associates Web Service (formerly Amazon ECS)
Amazon Elastic Compute Cloud (Beta)
Amazon Flexible Payments Service (Beta)
Amazon Fulfillment Web Service
Amazon Mechanical Turk (Beta)
Amazon SimpleDB (Beta)
Amazon Simple Queue Service
Amazon Simple Storage Service
Alexa Site Thumbnail
Alexa Top Sites
Alexa Web Information Service
Alexa Web Search
Amazon Book Information
http://www.amazon.com/gp/product/006251587X%3ftag=webservices-20%26link_code=xm2%26camp=2025%26d
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
15 of 74 4/2/2008 12:14 PM
Yahoo! Developer Network
Yahoo! Developer Network. REST Web Services using XML and JSON.
Answers
Local
Maps
OpenID
Search
Shopping
Travel
Utilities
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
16 of 74 4/2/2008 12:14 PM
Rich Internet Applications
Rich Internet Applications (RIA)Rich User Experience
gmail.com
maps.google.com
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
17 of 74 4/2/2008 12:14 PM
calendar.google.com
docs.google.com
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
18 of 74 4/2/2008 12:14 PM
XHR, Ajax, AHAH
XHR: XMLHttpRequestObject
AJAX: Asynchronous JavaScript and XML
AHAH: Asynchronous HTTP and HTML
AJAX: A New Approach to Web Applications, from Adaptive Path. by Jesse James Garrett
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
19 of 74 4/2/2008 12:14 PM
Ajax Flow
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
20 of 74 4/2/2008 12:14 PM
Ajax Overview
Ajax: A New Approach to Web Applications
AJAX (Wikipedia)
Technologies Involved
XHTML
CSS
JavaScript
XMLHttpRequest (XHR) object
Document Object Model (DOM)
Possibly: XML, JSON, XSLT, XPath
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
21 of 74 4/2/2008 12:14 PM
Course Search with Ajax and jQuery
http://minerva.dce.harvard.edu/ajax/course_jquery.html
There is a URL that returns a list of courses given a course group (as an XHTML snippet):
http://minerva.dce.harvard.edu/ajax/course_search?description=protein will return a list of courses whose description contains "protein"
http://minerva.dce.harvard.edu/ajax/course_search?description=planet will return a list of courses whose description contains "planet"
http://minerva.dce.harvard.edu/ajax/course_search?title=neuro will return a list of courses whose title contains "neuro"
http://minerva.dce.harvard.edu/ajax/course_search?title=DNA will return a list of courses whose title contains "DNA"
Note that the search is case-insensitive.
What's involved:
jQuery Javascript library
Server-side process to generate course list markup (courselist_partial which take a course_group query parameter)
Custom Javascript function (getCourseList) to call server-side process
Javascript to invokee the custom getCourseList function.
Import jQuery
jQuery function:
view plain print ?
<script src="/jquery/jquery.js" type="text/javascript"> </script> 1.<script src="/jquery/jquery.form.js" type="text/javascript"> </script> 2.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
22 of 74 4/2/2008 12:14 PM
Form:
view plain print ?
function getCourseList() { 1. var search_term = $('#search_query').val(); 2. $('#courselist').load( 3. '/ajax/course_search', 4. {'description' : search_term } 5. ); 6.} 7.
view plain print ?
<form onsubmit="getCourseList(); return false;"> 1.<div> 2. <label for="course_search">Search for Courses by Description:</label> 3. <input type="text" id="search_query" name="search_query" size="30" /> 4. <br/> 5. <input type="button" name="submit" onclick="getCourseList()" value="Search" /> 6.</div> 7.<div id="courselist"> 8. Course Listings will be updated here. 9.</div> 10.</form> 11.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
23 of 74 4/2/2008 12:14 PM
Conferences: Loading with HTML
Example
Page
Markup
JS
Server
select-conference
search
Markup:
JS:
view plain print ?
<form id="search-form" action="http://minerva.dce.harvard.edu/cgi-bin/echo.cgi"> 1. <div id="select-conference"> </div> 2. <input type="submit"/> 3. </form> 4. <hr/> 5. <div id="results_section"> </div> 6.
view plain print ?
$(document).ready(function(){ 1. setConferenceOptions(); 2. $('#search-form').submit(function(e) { 3. updateResults(); 4. e.preventDefault(); 5. }); 6. }); 7. function setConferenceOptions() { 8. $('#select-conference').load('ajax/select-conference'); 9. } 10. function updateResults() { 11. var selectedconf = $('#conference').fieldValue(); 12. var loading = $('<p>Loading...<br/><img src="images/ajax-loader-bar.gif" alt="loading"13. $('#results_section').html(loading); 14. $('#results_section').load('ajax/search',{'conference':selectedconf}); 15. } 16.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
24 of 74 4/2/2008 12:14 PM
Conferences: JSON
Instead of returning HTML to be put into the page, our server-side process will return JSON (JavaScriptObject Notation). We can then process the JSON data into the page.
JSON data example:
And the JS to process it:
view plain print ?
{'schools':[ 1.{ 2. name:"Brown University", 3. href:"http://www.brown.edu", 4. division:"I", 5. conference:"Ivy Group", 6. conf_href:"http://www.ivyleaguesports.com/", 7. state:"Rhode Island" 8.}, 9.{ 10. name:"Harvard University", 11. href:"http://www.harvard.edu", 12. division:"I", 13. conference:"Ivy Group", 14. conf_href:"http://www.ivyleaguesports.com/", 15. state:"Massachusetts" 16.}, 17./* removed schools for clarity */ 18.]} 19.
view plain print ?
function updateResults() { 1. var selectedconf = $('#conference').fieldValue(); 2. var loading = $('<p>Loading...<br/><img src="images/ajax-loader-bar.gif" alt="loading"/>3. $.getJSON( 4. 'ajax/search-json', 5. {'conference':selectedconf}, 6. function(data){ 7. $('#results_section').html(''); 8. $.each(data.schools, function(i,school){ 9. $('<p>'+ school.name + '</p>').appendTo('#results_section'); 10. }); 11. }); 12.} 13.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
25 of 74 4/2/2008 12:14 PM
Conferences: XML
Return XML data:
And the JS changes slightly to process XML instead of JSON:
view plain print ?
function updateResults() { 1. $('#results_section').html(''); 2. var selectedconf = $('#conference').fieldValue(); 3. $.get( 4. 'ajax/search-xml', 5. {'conference':selectedconf}, 6. function(xml){ 7. $(xml).find('school').each(function(){ 8. $('<p>'+ $(this).attr('name') + '</p>').appendTo('#results_section'); 9. }) 10. }); 11.} 12.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
26 of 74 4/2/2008 12:14 PM
Mutliple Filter Criteria with Ajax
We create an interface that allows schools to be filtered by
Division
Conference
School
Pulldown menus created through jQuery and Ajax.
When a criteria is selected, we use Ajax to dynamically update the pulldown options as well as thetable of results.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
27 of 74 4/2/2008 12:14 PM
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
28 of 74 4/2/2008 12:14 PM
Data from a Third Party
You may wish to use data from third parties. You may wish to provide your data to others to use. Thisis where XML and JSON are extremely useful.
Yahoo! Web Services
Yahoo! News Search provides search results in XML and JSON formats.
Search for "Harvard University" - XML
Search for "Harvard University" - JSON
Security restrictions put limitations on cross-domain JSON requests.
proxy
use "callback" functions
dynamic script loading
JS
Create the URL
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
29 of 74 4/2/2008 12:14 PM
Get the JSON data from Yahoo!
Build HTML content from JSON data
Insert HTML onto page
Markup
view plain print ?
var query = 'Harvard%20University'; 1. var appid = 'yMIOotnV34HMbuKM5K0M7Mxk5XET_WRCmG2Wq38O9kU6QZDFWZFlY8V0F2y..5DDRmJ5I6M8'; 2. var results = 5; 3. var language = 'en'; 4. var output = 'json' 5. var urlbase = 'http://search.yahooapis.com/NewsSearchService/V1/newsSearch?'; 6. var url = urlbase; 7. url = url + 'appid=' + appid; 8. url = url + '&results=' + results; 9. url = url + '&language=' + language; 10. url = url + '&output=' + output; 11. url = url + '&query=' + query; 12. url = url + '&callback=' + '?'; 13. $(document).ready(function(){ 14. $.getJSON(url, function(data){ 15. $('<ul id="newslist"> </ul>').appendTo('#news'); 16. $.each(data.ResultSet.Result, function(i,item){ 17. pubdate = new Date(item.PublishDate*1000); 18. var newsitem = '<a href="' + item.Url + '" class="newstitle">' + item.Title + '</a>'; 19. newsitem += '<br/>' + '<span class="newssource">' + item.NewsSource + '</span>'; 20. newsitem += '<br/>' + '<span class="publishdate">' + pubdate.toUTCString() + '</span>';21. newsitem += '<div class="newssummary">' + item.Summary+ '</div>'; 22. newsitem = '<li>' + newsitem + '</li>'; 23. $(newsitem).appendTo('#newslist'); 24. }); 25. }); 26.}); 27.
view plain print ?
<body> 1. <h1>Harvard University</h1> 2. <div id="news"> 3. <p><strong>Harvard in the News</strong></p> 4. </div> 5. <div id="main"> 6. <p> 7. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed ... 8. </p> 9. ... 10.</body> 11.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
30 of 74 4/2/2008 12:14 PM
Google Maps: Ivy Group
Javascript Application that uses Ajax to pull in map marker data.
Load Google Map JS from Google
Provide our data through Ajax
Create "markers" for map according to Google Map API
Place "markers" and information on maps via XML data.
Live Example: Ivy Group Map
Markup:
Data (ivy.xml)
view plain print ?
<html> 1. <head> 2. <script src="http://maps.google.com/maps?t=h&file=api&v=2&key=YOUR_GOOGLE_MA3. <!-- removed additional script that processes map data for clarity --> 4. </head> 5. <body onload="load()" onunload="GUnload()"> 6. <h1>Google Map of "Ivy Group" Schools</h1> 7. <div id="map" style="width: 650px; height: 450px"> </div> 8. </body> 9.</html> 10.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
31 of 74 4/2/2008 12:14 PM
JS to process Data
view plain print ?
<markers xmlns:h="http://www.w3.org/1999/xhtml"> 1. <marker lat="41.827763" lng="-71.404803" label="Brown University"/> 2. <marker lat="40.808352" lng="-73.963609" 3. label="Columbia University-Barnard College"/> 4. <marker lat="42.446483" lng="-76.482825" label="Cornell University"/> 5. <marker lat="43.707718" lng="-72.288322" label="Dartmouth College"/> 6. <marker lat="42.374438" lng="-71.117254" label="Harvard University"/> 7. <marker lat="39.95028" lng="-75.195065" label="University of Pennsylvania"/> 8. <marker lat="40.346544" lng="-74.65682" label="Princeton University"/> 9. <marker lat="41.311082" lng="-72.962952" label="Yale University"/> 10.</markers> 11.
view plain print ?
function load() { 1. if (GBrowserIsCompatible()) { 2. var map = new GMap2(document.getElementById("map")); 3. map.addControl(new GSmallMapControl()); 4. map.addControl(new GMapTypeControl()); 5. map.addControl(new GOverviewMapControl()); 6. map.setCenter(new GLatLng(41,-74), 6); 7. map.setMapType(G_MAP_TYPE); 8. // Download the data in data.xml and load it on the map. The format we 9. GDownloadUrl("ivy.xml", function(data) { 10. var xml = GXml.parse(data); 11. var markers = xml.documentElement.getElementsByTagName("marker"); 12. for (var i = 0; i < markers.length; i++) { 13. var elem = markers[i]; 14. var point = new GLatLng(parseFloat(elem.getAttribute("lat")), 15. parseFloat(elem.getAttribute("lng"))); 16. gmarker = createMarker(point,elem); 17. map.addOverlay(gmarker); 18. } 19. }); 20. } 21.} 22.function createMarker(point,elem) { 23. var gmarker = new GMarker(point); 24. var label = elem.getAttribute("label"); 25. GEvent.addListener(gmarker, "click", function() { 26. gmarker.openInfoWindow(label); 27. }); 28. return gmarker; 29.} 30.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
32 of 74 4/2/2008 12:14 PM
Google Maps: CSCI E-12
Javascript Application that uses Ajax to pull in map marker data.
Load Google Map JS from Google
Provide our data through Ajax
Create "markers" for map according to Google Map API
Place "markers" and information on maps via XML data.
CSCI E-12 Campus Map
Markup:
view plain print ?
<body onload="load()" onunload="GUnload()"> 1. <div id="map" style="width: 650px; height: 450px"></div> 2.</body> 3.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
33 of 74 4/2/2008 12:14 PM
Marker Data
campus_data_spring2008.xml
Javascript createMarker function:
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
34 of 74 4/2/2008 12:14 PM
view plain print ?
function createMarker(point, elem) { 1. // create tabs 2. var infoTabs = []; 3. var tabs = elem.getElementsByTagName("tab"); 4. for (var i = 0; i < tabs.length; i++) { 5. var tab = new GInfoWindowTab( 6. tabs[i].getAttribute("label"), 7. tabs[i].getElementsByTagName("content")[0].textContent 8. ); 9. infoTabs.push(tab); 10. } 11. // create marker, add tabs 12. var marker = new GMarker(point); 13. GEvent.addListener(marker, "click", function() { 14. marker.openInfoWindowTabsHtml(infoTabs); 15. }); 16. return marker; 17.} 18. 19.// load function 20.function load() { 21. if (GBrowserIsCompatible()) { 22. var map = new GMap2(document.getElementById("map")); 23. // configure map properties 24. map.addControl(new GSmallMapControl()); 25. map.addControl(new GMapTypeControl()); 26. map.addControl(new GOverviewMapControl()); 27. map.setCenter(new GLatLng(42.375492,-71.117613), 16); 28. map.setMapType(G_HYBRID_TYPE); 29. // Download the data in data.xml and load it on the map. 30. GDownloadUrl("campus_data.xml", function(data) { 31. var xml = GXml.parse(data); 32. var markers = xml.documentElement.getElementsByTagName("marker"); 33. /* iterate through "marker" data, creating 34. for each a Google Map Marker */ 35. for (var i = 0; i < markers.length; i++) { 36. var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), 37. parseFloat(markers[i].getAttribute("lng"))); 38. var marker = createMarker(point, markers[i]); 39. map.addOverlay(marker); 40. } 41. }); 42. } 43.} 44.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
35 of 74 4/2/2008 12:14 PM
JavaScript Applications
The SIMILE project from MIT has some great examples of JS applications
Exhibit
Timeline
US Congress and Exhibit
Provide the data and the template, and Exhibit provides the functionality: different views, timelineaccording to birth date, filtering, sorting, and grouping.
Congress Exhibit Template
Congress People Data (JSON)
Tiles View
Table View (columns are sortable)
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
36 of 74 4/2/2008 12:14 PM
Thumbnails View (Filters applied: California, Democrat)
Timeline ViewVisible are those with birthdays in 1969-1972. Timeline is scrollable.
Congress data used with permission from GovTrack.US.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
37 of 74 4/2/2008 12:14 PM
Dynamically Created Documents
Content is created at the time of the request
Content created from dynamic process "off-line"
Note that can content is typically XHTML, but could be any type of media (e.g. CSS, PDF, PNG, JPG,GIF, Excel, Word, etc.)
Things to consider...
There's no single best way to produce dynamic documents, but depending upon the situation, somesolutions will be better than others.
Application Scope
"pages"
on-the-fly
created in "batch"
application
Server-side Architecture
external
internal
external, persistent
Development Structure
Program that outputs Web content
Web content that has embedded programming
Framework
MVC, Model-View-Controller
Language
Java, PHP, Python, Perl, Ruby, C#, .NET, ColdFusion, C/C++, Smalltalk, Tcl, etc.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
38 of 74 4/2/2008 12:14 PM
Web Development Languages & Frameworks
Part of Apache:
Apache SSI and XSSI
Non-Java
PHP, CakePHP (MVC), Drupal (CMS), Joomla (CMS)
Perl: Catalyst (MVC), Jifty, Template Toolkit, ...
Ruby: Ruby (MVC)
Python: Django (MVC), Zope, Plone (CMS)
ColdFusion
Java
JSP/Servlets, Apache Struts (MVC), JavaServer Faces (JSF)
Microsoft
Active Server Pages, ASP.NET
Browser Plugins
Microsoft Silverlight
Adobe SWF - Flash and Flex
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
39 of 74 4/2/2008 12:14 PM
Server-side Architecture
HTTP Client and Server
CGI Process
Examples: CGI
External Process
Examples: FastCGI (language neutral), Servlet/JSP, ColdFusion
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
40 of 74 4/2/2008 12:14 PM
Internal
Examples: PHP, Perl under Apache mod_perl, Servlet/JSP, ColdFusion
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
41 of 74 4/2/2008 12:14 PM
Development Structure
program that outputs Web content programs with XHTML embedded
Web content that has embedded programming XHTML with programs embedded
Separation of Concerns (SOC) MVC, Model-View-Controller.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
42 of 74 4/2/2008 12:14 PM
"XHTML within a Program" Examples
Markup or content is embedded within a program.
first.cgi
first.cgi
second.cgi
second.cgi
Here the "CGI.pm" Perl module creates tags with subroutine calls.
Perl code: h1("Hello, World!")
Becomes: <h1>Hello World!</h1>
view plain print ?
#!/usr/local/bin/perl 1.print "Content-type: text/html\n\n"; 2.print "<html><body><h1>Hello, World!</h1></body></html>"; 3.
view plain print ?
#!/usr/local/bin/perl 1.use CGI qw(:all); # CGI.pm module is very useful! 2.print 3. header, 4. start_html, 5. h1("Hello, World!"), 6. end_html; 7.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
43 of 74 4/2/2008 12:14 PM
CGI Examples: third.cgi
third.cgi
third.cgi?name=David%20Heitmeyer
view plain print ?
#!/usr/local/bin/perl 1.use CGI qw(:all); # CGI.pm module is very useful! 2.my $q = new CGI; # create a new CGI object 3.my $name = $q->param('name'); 4.print header, 5. start_html, 6. h1("Hello, $name!"), 7. end_html; 8.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
44 of 74 4/2/2008 12:14 PM
CGI Examples: fourth.cgi
Without a "name", present the user a form. With a name, provide a greeting.
fourth.cgi
fourth.cgi?name=David%20Heitmeyer
view plain print ?
#!/usr/local/bin/perl 1.use CGI qw(:all); # CGI.pm module is very useful! 2.my $q = new CGI; # create a new CGI object 3.my $name = $q->param('name'); 4.if ($name) { 5. print header, 6. start_html, 7. h1("Hello, $name!"), 8. end_html; 9.} else { 10. print header, 11. h1("Enter name:"), 12. start_form, 13. textfield(-name=>"name"), 14. br, 15. submit, 16. br, 17. reset, 18. end_form, 19. end_html; 20.} 21. 22.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
45 of 74 4/2/2008 12:14 PM
Simple Servlet Example
view plain print ?
package simple; 1.import java.io.*; 2.import javax.servlet.*; 3.import javax.servlet.http.*; 4./** Very simplistic servlet. 5. */ 6.public class HelloWorld extends HttpServlet { 7. public void doGet(HttpServletRequest request, 8. HttpServletResponse response) 9. throws ServletException, IOException { 10. PrintWriter out = response.getWriter(); 11. out.println("<html>"); 12. out.println("<body>"); 13. out.println("<h1>"); 14. out.println("hello"); 15. out.println("</h1>"); 16. out.println("</body>"); 17. out.println("</html>"); 18. } 19.} 20.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
46 of 74 4/2/2008 12:14 PM
"XHTML with Programs" Examples
Examples include: SSI, PHP, JSP, ASP, some Perl template systems
JSP example:
view plain print ?
<html> 1. <body> 2. <h1> Some dynamic content using JSP:</h1> 3. <ul> 4. <li><strong>Expression.</strong><br> Your hostname: 5. <%= request.getRemoteHost() %> 6. <li><strong>Scriptlet.</strong><br/> 7. <% out.println("Attached GET data: " + request.getQueryString()); %> 8. <li><strong>Declaration (plus 9. expression).</strong><br/> 10. <%! private int accessCount = 0; %> 11. Accesses to page since server restart: 12. <%= ++accessCount %> 13. <li><strong>Directive (plus expression).</strong><br/> 14. <%@ page import = "java.util.*" %> 15. Current date: <%= new Date() %> 16. </ul> 17. </body> 18.</html> 19.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
47 of 74 4/2/2008 12:14 PM
PHP: Hypertext Processor
PHP: Hypertext Processor
From the PHP manual:
PHP, which stands for "PHP: Hypertext Preprocessor" is a widely-used Open Source general-purpose scripting language that is especially suited for Web development and can be embedded into HTML. Its syntax draws upon C, Java, and Perl, and is easy to learn. The main goal of the language is to allow web developers to write dynamically generated web pages quickly, but you can do much more withPHP.
Example
http://cscie12.dce.harvard.edu/cgi/hello.php
view plain print ?
<?php 1. $greeting = "Hello, World!"; 2.?> 3.<html> 4.<head><title>Hello</title></head> 5.<body> 6.<h1><?php echo($greeting) ?></h1> 7.</body> 8.</html> 9.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
48 of 74 4/2/2008 12:14 PM
Model, View, Controller (MVC) Design Pattern
MVC design pattern separates:
Model. data model
View. user interface
Controller. control and flow logic
You can adopt this design pattern regardless of language or server-architecture (CGI, internal process,external process). Some frameworks make using MVC possible, some hard, some easy, some insiston it.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
49 of 74 4/2/2008 12:14 PM
Java Expression Language (EL)
e.g.ivy/list.html
Template uses an "expression" language to produce content, not Java. There is a Java process("Controller" and "Model") that gets the data, and then forwards the data to the "View" component for processing on the server before it is sent to the browser.
In this example, an array of "schools" is available to the view. The schools are essentially a map thatcould be represented like:
Sample Data from "Model"
EL Page ("View")
The result:
view plain print ?
{ 1. name:"Harvard University", 2. href:"http://www.harvard.edu", 3. division:"I", 4. conference:"Ivy Group", 5. conf_href:"http://www.ivyleaguesports.com/", 6. image_seal:"http://upload.wikimedia.org/wikipedia/en/thumb/8/8e/Harvard_shield-University.7. lat:"42.374438", 8. lng:"-71.117254", 9. state:"Massachusetts" 10.} 11.
view plain print ?
<html xmlns:jx="http://apache.org/cocoon/templates/jx/1.0"> 1. <head> 2. <title>${title}</title> 3. </head> 4. <body> 5. <h1>${title}</h1> 6. <ul> 7. <jx:forEach var="school" items="${schoolList}"> 8. <li><a href="${school.href}">${school.name}</a></li> 9. </jx:forEach> 10. </ul> 11. </body> 12.</html> 13.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
50 of 74 4/2/2008 12:14 PM
Producing a Different View
e.g.ivy/seals.html
Based upon the URL pattern, the "Controller" can call a different view. The "Model" provides the samedata in this case. Our template produces a display of the schools' seals.
The result:
view plain print ?
<html xmlns:jx="http://apache.org/cocoon/templates/jx/1.0"> 1. <head> 2. <title>${title}</title> 3. <style type="text/css"> 4. div.school { text-align: center; float: left; height: 225px; width: 200px; border: thi5. img.seal { height: 144px; margin-bottom: 5px; } 6. </style> 7. </head> 8. <body> 9. <h1>${title}</h1> 10. <jx:forEach var="school" items="${schoolList}"> 11. <div class="school"> <img class="seal" src="${school.image_seal}" 12. alt="${school.name}"/> 13. <br/> ${school.name} </div> 14. </jx:forEach> 15. </body> 16.</html> 17.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
51 of 74 4/2/2008 12:14 PM
EL to Produce Data for Google Maps
e.g.ivy/markers.xml
Here we use a different template to produce "marker" data for Google Maps. Note that the data sent isthe same ("Model" is doing the same thing). The "Controller" would be calling a different view basedupon a URL pattern.
The result:
view plain print ?
<markers xmlns:jx="http://apache.org/cocoon/templates/jx/1.0"> 1. <jx:forEach var="school" items="${schoolList}"> 2. <marker lat="${school.lat}" lng="${school.lng}" label="${school.name}"/> 3. </jx:forEach> 4.</markers> 5.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
52 of 74 4/2/2008 12:14 PM
Template Toolkit (Perl and Python)
Template Toolkit
The Template Toolkit is a fast, powerful and easily extensible template processing system.
Dynamic
Build
HTTP Request is made1.Data is retrieved2.Data given to Toolkit Template template for processing3.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
53 of 74 4/2/2008 12:14 PM
Template Toolkit Example
view plain print ?
<table id="result-table" cellspacing="0"> 1. <tr id="col-heads"> 2. <th [%sorting_on.title%]><a href="[% sort_links.title %]">Title</a></th> 3. <th [%sorting_on.description%]><a href="[% sort_links.description %]">Description</a></4. <th [%sorting_on.eligibility%]><a href="[% sort_links.eligibility %]">Eligibility</a></5. <th [%sorting_on.award%]><a href="[% sort_links.award %]">Award</a></th> 6. <th [%sorting_on.location%]><a href="[% sort_links.location %]">[% column_location %]</7. <th [%sorting_on.sponsor%]><a href="[% sort_links.sponsor %]">Sponsor</a></th> 8. <th [%sorting_on.deadline%]><a href="[% sort_links.deadline %]">Deadline</a></th> 9. <th [%sorting_on.score%] class="minwidth"><a href="[% sort_links.score %]"> Rel.&n10. </tr> 11. [% FOREACH funding_sources %] 12. <tr> 13. <td><a href="search.cgi?action=view_detail&funding_id=[% FUNDING_ID %]&back_li14. <td class="desc"> 15. [% BRIEF_DESC | truncate_words | ucfirst %] 16. <a href="search.cgi?action=view_detail&funding_id=[% FUNDING_ID %]&back_li17. </td> 18. <td>[% CITIZENSHIP; "<br/>" IF CITIZENSHIP; STUDENT_STATUS %]</td> 19. <td>[% AWARD_TYPE IF AWARD_TYPE != 'fixed' %] 20. [% IF AWARD_AMOUNT %] 21. [% '$' _ AWARD_AMOUNT | num_comma %] 22. [% END %]</td> 23. <td> 24. [% INCLUDE location.html mode = 'search_results_list' %] 25. </td> 26. <td>[% INCLUDE sponsoring_dept.html mode = 'search_results_list' %]</td> 27. <td>[% DEADLINE %]</td> 28. <td>[% SCORE %]</td> 29. </tr> 30. [% END %] 31.</table> 32.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
54 of 74 4/2/2008 12:14 PM
Data for our Dynamic Site
Relational Database
XML
YAML (YAML Ain't Markup Language)
Some other format (CSV, tab-delimited, etc.)
A Web Service
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
55 of 74 4/2/2008 12:14 PM
Conferences
list.cgi
Process reads in YAML data
Template is processed
The template that will display the data.
view plain print ?
<div> 1.[% META title = 'Conferences' %] 2.<div> 3. <ul> 4. [% FOREACH conference = conferences.keys.sort %] 5. <li>[% conference %]</li> 6. [% END %] 7. </ul> 8.</div> 9.</div> 10.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
56 of 74 4/2/2008 12:14 PM
Getting the Data: CGI
list.cgi
view plain print ?
#!/usr/bin/perl 1. 2.# import Perl libraries 3.use Template; 4.use YAML; 5.use Data::Dumper; 6. 7.my $context; 8. 9.# call the routine that gets the data 10.$data = get_conferences_data(); 11. 12.# put the data in the "context", which will be 13.# made avaialble to the template 14.$context->{'conferences'} = $data; 15. 16.my $file = 'conference_list.tt2'; 17.# create the template object 18.my $template = template(); 19. 20.print "Content-type: text/html\n\n"; 21.# process the template 22.# passing in 'context' 23.$template->process($file, $context) || die $template->error(); 24. 25. 26.sub get_conferences_data { 27. my $file = 'data/conferences.yml'; 28. my $data = YAML::LoadFile($file); 29. return $data; 30.} 31. 32.# routine that creates a template object 33.# that has the configurations for our project 34.sub template { 35. $TT = Template->new({ 36. INCLUDE_PATH => [ 37. 'root/src/', 38. 'root/lib/' 39. ], 40. PRE_PROCESS => 'config/main', 41. WRAPPER => 'site/wrapper', 42. ERROR => 'error.tt2', 43. POST_CHOMP => 2, 44. TRIM => 2, 45. COMPILE_EXT => '.ttc', 46. COMPILE_DIR => '/tmp/ttc' 47. }); 48. return $TT; 49.} 50.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
57 of 74 4/2/2008 12:14 PM
Wrapping the Template
Where did everything else come from? The files that our part of out Template Toolkit site are:
root/lib/config/* files contain definitions and configuration values
root/lib/site/* files define the page structure
root/src/* are the template files
Note that ttsite.css is a template file. Color and other definitions come from the config files.
site/wrapper
site/html
site/layout
-- lib 1.| |-- config 2.| | |-- col 3.| | `-- main 4.| `-- site 5.| |-- footer 6.| |-- header 7.| |-- html 8.| |-- layout 9.| `-- wrapper 10.`-- src 11. |-- conference_list.tt2 12. |-- conferences.tt2 13. |-- error.tt2 14. |-- schools_thumbshots.tt2 15. `-- ttsite.css 16.
[% IF template.name.match('\.(css|js|txt)'); 1. debug("Passing page through as text: $template.name"); 2. content; 3. ELSE; 4. debug("Applying HTML page layout wrappers to $template.name\n"); 5. content WRAPPER site/html + site/layout; 6. END; 7.-%] 8.
view plain print ?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 1. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2.<html xmlns="http://www.w3.org/1999/xhtml"> 3. <head> 4. <title>[% template.title or site.title %]</title> 5. <style type="text/css"> 6. [% PROCESS ttsite.css %] 7. </style> 8. </head> 9. <body> 10. [% content %] 11. </body> 12.</html> 13.
view plain print ?
<div id="header">[% PROCESS site/header %]</div> 1.<div id="content"> 2.[% content %] 3.</div> 4.<div id="footer">[% PROCESS site/footer %]</div> 5.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
58 of 74 4/2/2008 12:14 PM
Conferences
Alter the CGI so that it takes a template argument from PATH_INFO:
http://cscie12.dce.harvard.edu/cgi/conferences/list.cgi/conferences
And now, let's list the schools:
view plain print ?
<div> 1.[% META title = 'Conferences and Schools' %] 2.<div> 3. <ul> 4. [% FOREACH conference = conferences.keys.sort %] 5. <li><strong>[% conference %]</strong> 6. <ul> 7. [%- FOREACH school = conferences.$conference %] 8. <li><a href="[% school.url %]"> 9. [%- school.name %]</a> 10. </li> 11. [%- END %] 12. </ul> 13. </li> 14. [% END %] 15. </ul> 16.</div> 17.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
59 of 74 4/2/2008 12:14 PM
Conferences [fun]
Alter the CGI so that it takes a template argument from PATH_INFO:
http://cscie12.dce.harvard.edu/cgi/conferences/list.cgi/schools_thumbshots
The [% INCLUDE site/thumbshots %] includes the file root/lib/site/thumbshots
view plain print ?
<div> 1.[% META title = 'Conferences and Schools' %] 2.<div> 3. <ul> 4. [% FOREACH conference = conferences.keys.sort %] 5. <li><strong>[% conference %]</strong> 6. <ul> 7. [% FOREACH school = conferences.$conference %] 8. <li><a href="[% school.url %]"> 9. [% school.name %]</a> 10. <br/><img src="http://open.thumbshots.org/image.pxf?url=[% school.url %]" 11. alt="school home page"/> 12. </li> 13. [% END %] 14. </ul> 15. </li> 16. [% END %] 17. </ul> 18.</div> 19.[% INCLUDE site/thumbshots %] 20.</div> 21.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
60 of 74 4/2/2008 12:14 PM
view plain print ?
<div 1.style="border: thin dotted black; background-color: #ff9; padding: 0.25em; margin: 5px 50px;2. <a href="http://www.thumbshots.com" target="_blank" 3. title="This site uses Thumbshots previews">This site uses 4. Thumbshots previews</a> 5.</div> 6.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
61 of 74 4/2/2008 12:14 PM
Template Toolkit Build
Building a static site with Template Toolkit.
The templates (*.html) files in the "src" directory will be processed and new files will be created in the"html" directory.
Directory and file structure:
TT 'ttree'
ttree
|-- data 1.| `-- menu.txt 2.|-- src 3.| |-- contact.html 4.| |-- directions.html 5.| |-- hours.html 6.| |-- images 7.| | |-- building.gif 8.| | |-- building.jpg 9.| | |-- building2.jpg 10.| | |-- building3.jpg 11.| | |-- map.gif 12.| | |-- pinocchio1.jpg 13.| | |-- pinocchio_216.gif 14.| | |-- pinocchio_72.gif 15.| | `-- sign.jpg 16.| |-- index.html 17.| |-- menu.html 18.| |-- sicilian_vs_regular.html 19.| `-- site.css 20.`-- tt 21. |-- footer 22. |-- head 23. |-- header 24. `-- navmenu 25.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
62 of 74 4/2/2008 12:14 PM
is the program that will recursively go through a directory and process templates. The resulting contentis saved to a file in another directory.
And now look in the "html" directory:
view plain print ?
minerva$ ttree --accept .html$ \ 1.> -s src -d html -l tt \ 2.> --copy .png$ --copy .gif$ \ 3.> --copy .jpg$ --copy .css$ \ 4.> --pre_chomp --post_chomp --trim \ 5.> -a 6.ttree 2.75 (Template Toolkit version 2.13) 7. 8. Source: src 9. Destination: html 10.Include Path: [ tt ] 11. Ignore: [ \b(CVS|RCS)\b, ^# ] 12. Copy: [ \.png$, \.gif$, .png$, .gif$, .jpg$, .css$ ] 13. Accept: [ .html$ ] 14. Suffix: [ ] 15. 16. + contact.html 17. + directions.html 18. + hours.html 19. > images/building.gif (copied, matches //) 20. > images/building.jpg (copied, matches //) 21. > images/building2.jpg (copied, matches //) 22. > images/building3.jpg (copied, matches //) 23. > images/map.gif (copied, matches //) 24. > images/pinocchio1.jpg (copied, matches //) 25. > images/pinocchio_216.gif (copied, matches //) 26. > images/pinocchio_72.gif (copied, matches //) 27. > images/sign.jpg (copied, matches //) 28. + index.html 29. + menu.html 30. + sicilian_vs_regular.html 31. > site.css (copied, matches //) 32.
html 1.|-- contact.html 2.|-- directions.html 3.|-- hours.html 4.|-- images 5.| |-- building.gif 6.| |-- building.jpg 7.| |-- building2.jpg 8.| |-- building3.jpg 9.| |-- map.gif 10.| |-- pinocchio1.jpg 11.| |-- pinocchio_216.gif 12.| |-- pinocchio_72.gif 13.| `-- sign.jpg 14.|-- index.html 15.|-- menu.html 16.|-- sicilian_vs_regular.html 17.`-- site.css 18.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
63 of 74 4/2/2008 12:14 PM
Template Toolkit: Datafiles
Can process data as well.
Menu data is:
And the menu.html template is:
subs|Cheese|4.50|5.60subs|Italian|4.75|5.90subs|Ham + Cheese|4.75|5.90subs|Meatball|4.75|5.90subs|Tuna|4.75|5.90subs|Turkey|5.50|6.50subs|Chicken Parmigiana|5.50|6.50subs|Roast Beef|5.50|6.50subs|Eggplant Parmigiana|4.75|5.90subs|Steak|5.00|6.00subs|Steak + Cheese|5.50|6.50subs| + Mushrooms|+0.50|+0.50subs| + Green Peppers|+0.50|+0.50subs| + Onions|+0.50|+0.50subs|Sausage, Peppers & Onions||6.50subs|Hamburger|3.60|5.40subs|Cheeseburger|4.10|5.90subs|Fried Chicken|5.75|6.75subs|Veggie|5.60|6.50subs|Extra Cheese on any sub|+0.50|+0.50
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
64 of 74 4/2/2008 12:14 PM
view plain print ?
[% INCLUDE header title = 'Menu' %] 1.[% USE menudata = datafile('data/menu.txt', delim = '|')%] 2.<table width="100%"> 3. <tbody> 4. <tr> 5. <td width="50%"> 6. <div class="callout"> 7. <h2>Our Menu</h2> 8. <table width="100%" class="foodmenu"> 9. <tbody> 10. <tr> 11. <th colspan="3"><a name="subs">Subs</a></th> 12. </tr> 13. <tr> 14. <td></td> 15. <td>Small</td> 16. <td>Large</td> 17. </tr> 18. [% FOREACH item = menudata %] 19. [% IF item.type == 'subs' %] 20. <tr> 21. <td style="text-align: left;" width="50%">[% item.item %]</td> 22. <td width="25%">[% item.small %]</td> 23. <td width="25">[% item.large %]</td> 24. </tr> 25. [% END %] 26. [% END %] 27. </tbody> 28. </table> 29. </div> 30. </td> 31. </tr> 32. </tbody> 33.</table> 34.[% INCLUDE footer %] 35.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
65 of 74 4/2/2008 12:14 PM
PHP Example
http://cscie12.dce.harvard.edu/cgi/courses/departments.php
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
66 of 74 4/2/2008 12:14 PM
FAS Course Data
Course data for Faculty of Arts & Sciences is in a mysql database on minerva (username: class; database name: coursecatalog)
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
67 of 74 4/2/2008 12:14 PM
view plain print ?
minerva$ mysql -u class coursecatalog 1.Reading table information for completion of table and column names 2.You can turn off this feature to get a quicker startup with -A 3. 4.Welcome to the MySQL monitor. Commands end with ; or \g. 5.Your MySQL connection id is 515 to server version: 3.23.58 6. 7.Type 'help;' or '\h' for help. Type '\c' to clear the buffer. 8. 9.mysql> describe courses; 10.+------------------------------+--------------+------+-----+---------+-------+ 11.| Field | Type | Null | Key | Default | Extra | 12.+------------------------------+--------------+------+-----+---------+-------+ 13.| acad_year | year(4) | YES | | NULL | | 14.| cat_num | int(9) | YES | | NULL | | 15.| offered | char(1) | YES | | NULL | | 16.| department_code | varchar(15) | YES | | NULL | | 17.| department_short | varchar(80) | YES | | NULL | | 18.| department_long | varchar(200) | YES | | NULL | | 19.| course_group_code | varchar(10) | YES | | NULL | | 20.| course_group_long | varchar(200) | YES | | NULL | | 21.| num_int | int(9) | YES | | NULL | | 22.| num_char | varchar(15) | YES | | NULL | | 23.| term_pattern_code | int(5) | YES | | NULL | | 24.| fall_term | char(1) | YES | | NULL | | 25.| spring_term | char(1) | YES | | NULL | | 26.| term | varchar(100) | YES | | NULL | | 27.| title | text | YES | | NULL | | 28.| course_type | varchar(100) | YES | | NULL | | 29.| course_level_code | char(1) | YES | | NULL | | 30.| course_level | varchar(200) | YES | | NULL | | 31.| credit_code | int(5) | YES | | NULL | | 32.| credit | varchar(50) | YES | | NULL | | 33.| instructor_approval_required | char(1) | YES | | NULL | | 34.| meeting_time | text | YES | | NULL | | 35.| faculty_text | text | YES | | NULL | | 36.| description | text | YES | | NULL | | 37.| prerequisites | text | YES | | NULL | | 38.| notes | text | YES | | NULL | | 39.+------------------------------+--------------+------+-----+---------+-------+ 40.26 rows in set (0.00 sec) 41. 42.mysql> select distinct department_short from courses; 43.+----------------------------------------------------------+ 44.| department_short | 45.+----------------------------------------------------------+ 46.| African and African American Studies | 47.| Anthropology | 48.| Architecture, Landscape Architecture, and Urban Planning | 49.| Asian Studies Program | 50.| Astronomy | 51.| Biological Sciences in Dental Medicine | 52.| Biological Sciences in Public Health | 53.| Biophysics | 54.| Biostatistics | 55.| Celtic Languages and Literatures | 56.| Chemical Biology | 57.| Chemical and Physical Biology | 58.| Chemistry | 59.| Comparative Literature | 60.| Core Curriculum | 61.| Dramatic Arts | 62.| Earth and Planetary Sciences | 63.| East Asian Languages and Civilizations | 64.| Economics | 65.| Engineering and Applied Sciences | 66.| English and American Literature and Language | 67.| Environmental Science and Public Policy | 68.| Expository Writing | 69.| Folklore and Mythology | 70.| Freshman Seminars | 71.| Germanic Languages and Literatures | 72.| Government | 73.| Health Policy | 74.| History | 75.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
68 of 74 4/2/2008 12:14 PM
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
69 of 74 4/2/2008 12:14 PM
Mixing of Concerns instead of SOC
Mixing of concerns instead of SOC.This particular example is with PHP, but you can easily achieve "entangling of concerns" with Java(JSP), ASP, Python, or Perl. The problem is not with the language, but with the structure.
departments.php
http://cscie12.dce.harvard.edu/cgi/courses/departments.php
courses.php
http://cscie12.dce.harvard.edu/cgi/courses/courses.php?department_code=CHEM
view plain print ?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 1. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2.<html xmlns="http://www.w3.org/1999/xhtml"> 3. <head> 4. <title>Departments</title> 5. <link rel="stylesheet" href="site.css" type="text/css"/> 6. </head> 7. <body> 8.<h1>Faculty of Arts & Sciences</h1> 9.<h2>Departments</h2> 10.<?php 11. // Connecting, selecting database 12. $link = mysql_connect('localhost', 'class', '') 13. or die('Could not connect: ' . mysql_error()); 14. mysql_select_db('coursecatalog') or die('Could not select database'); 15. 16. // Performing SQL query 17. $query = 'SELECT distinct department_short, department_code FROM courses order by depar18. $result = mysql_query($query) or die('Query failed: ' . mysql_error()); 19. 20. // Printing results in HTML 21. echo "<table>\n"; 22. while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { 23. echo "\t<tr>\n"; 24. echo "<td><a href=\"courses.php?department_code=$row[department_code]\">$row[departme25. echo "\t</tr>\n"; 26. } 27.echo "</table>\n"; 28. 29.// Free resultset 30.mysql_free_result($result); 31. 32.// Closing connection 33.mysql_close($link); 34.?> 35. </body> 36.</html> 37.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
70 of 74 4/2/2008 12:14 PM
view plain print ?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 1. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2.<html xmlns="http://www.w3.org/1999/xhtml"> 3. <head> 4. <title>Departments</title> 5. <link rel="stylesheet" href="site.css" type="text/css"/> 6. </head> 7. <body> 8.<h1>Faculty of Arts & Sciences</h1> 9.<p><a href="departments.php">Return to Department List</a></p> 10.<h2>Department <?php echo $_GET[department_code] ?></h2> 11.<?php 12.// Connecting, selecting database 13.$link = mysql_connect('localhost', 'class', '') 14. or die('Could not connect: ' . mysql_error()); 15. mysql_select_db('coursecatalog') or die('Could not select database'); 16. 17. // Performing SQL query 18. $query = 'SELECT course_group_long, num_int, num_char, term, title, description'; 19. $query .= ' from courses where department_code = '; 20. $query .= "'".mysql_escape_string($_GET['department_code'])."'"; 21. $query .= ' order by course_group_long, num_int, num_char, title'; 22. 23. $result = mysql_query($query) or die('Query failed: ' . mysql_error()); 24. // Printing results in HTML 25. echo "<table cellspacing='0' cellpadding='0'>\n"; 26. $i = 0; 27. while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { 28. $class = $i++ % 2 ? 'evenrow' : 'oddrow' ; 29. echo "\t<tr class='$class'>\n"; 30. echo "<td class='abbrev'>$row[course_group_long] $row[num_int] $row[num_char]</td>"; 31. echo "<td class='long'><strong>$row[title]</strong>"; 32. echo "<p class='description'>$row[description]</p></td>"; 33. echo "\t</tr>\n"; 34. } 35.echo "</table>\n"; 36. 37.// Free resultset 38.mysql_free_result($result); 39. 40.// Closing connection 41.mysql_close($link); 42.?> 43. 44. </body> 45.</html> 46.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
71 of 74 4/2/2008 12:14 PM
PHP Smarty Templates
Smarty is a Template Engine for PHP, which allows you to write Templates for your PHP data (similar toPerl's Template Toolkit)
The template (departments.tpl):
Get the departments: smarty-dept.php
view plain print ?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 1. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2.<html xmlns="http://www.w3.org/1999/xhtml"> 3. <head> 4. <title>Departments</title> 5. <link rel="stylesheet" href="site.css" type="text/css"/> 6. </head> 7.<body> 8.<h1>Faculty of Arts & Sciences</h1> 9.<h2>Departments</h2> 10. <table> 11. {foreach from=$dept item=d} 12. <tr> 13. <td> 14. <a href="smarty-courses.php?department_code={$d.department_code}">{$d.department_shor15. </td> 16. </tr> 17. {/foreach} 18. </table> 19.</body> 20.</html> 21.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
72 of 74 4/2/2008 12:14 PM
view plain print ?
<?php 1.// Connecting, selecting database 2.$link = mysql_connect('localhost', 'class', '') 3. or die('Could not connect: ' . mysql_error()); 4. 5.mysql_select_db('coursecatalog') or die('Could not select database'); 6.// Performing SQL query 7. $query = 'SELECT distinct department_short, department_code FROM courses order by departmen8.$res = mysql_query($query) or die('Query failed: ' . mysql_error()); 9.$i=0; 10.while ($row = mysql_fetch_array($res, MYSQL_ASSOC)) { 11. $results[$i++] = $row; 12.} 13. 14.require('/usr/local/lib/php/Smarty/Smarty.class.php'); 15.// create object 16.$smarty = new Smarty; 17.$smarty->template_dir = './smarty_templates'; 18.$smarty->compile_dir = '/tmp/smarty/templates_c'; 19.$smarty->cache_dir = '/tmp/smarty/cache'; 20.$smarty->config_dir = './smarty_configs'; 21. 22.$smarty->assign('dept', $results); 23. 24.// display it 25.$smarty->display('departments.tpl'); 26. 27.// Free resultset 28.mysql_free_result($res); 29.// Closing connection 30.mysql_close($link); 31.?> 32.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
73 of 74 4/2/2008 12:14 PM
Smarty Template for Courses
The template (courses.tpl):
Get the Courses for the CHEM department: smarty-courses.php?department_code=CHEM
view plain print ?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 1. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2.<html xmlns="http://www.w3.org/1999/xhtml"> 3. <head> 4. <title>Departments</title> 5. <link rel="stylesheet" href="site.css" type="text/css"/> 6. </head> 7. <body> 8.<h1>Faculty of Arts & Sciences</h1> 9.<p><a href="smarty-dept.php">Return to Department List</a></p> 10.<h2>Department {$department_code}</h2> 11.<table cellspacing="0" cellpadding="0"> 12.{foreach from=$courses item=course name=courses} 13.<tr class="{cycle values="row1,row2,row3,row4"}"> 14.<td class="abbrev">{$course.course_group_long} {$course.num_int}{$course.num_char}</td> 15.<td class="long"> 16. <strong>{$course.title}</strong> 17. <p class="description"> 18. {$course.description} 19. </p> 20.</td> 21.</tr> 22.{/foreach} 23.</table> 24.</body> 25.</html> 26.
Web 2.0, Ajax, Dynamic Sites http://localhost:8080/cocoon/projects/cscie12/slides/20080402/handout.html
74 of 74 4/2/2008 12:14 PM
Table of Contents | All Slides | Link List | CSCI E-12
view plain print ?
<?php 1.// Connecting, selecting database 2.$link = mysql_connect('localhost', 'class', '') 3. or die('Could not connect: ' . mysql_error()); 4.mysql_select_db('coursecatalog') or die('Could not select database'); 5. 6.// Performing SQL query 7.$query = 'SELECT course_group_long, num_int, num_char, term, title, description'; 8.$query .= ' from courses where department_code = '; 9.$query .= "'".mysql_escape_string($_GET['department_code'])."'"; 10.$query .= ' order by course_group_long, num_int, num_char, title'; 11.$res = mysql_query($query) or die('Query failed: ' . mysql_error()); 12.$i = 0; 13.while ($row = mysql_fetch_array($res, MYSQL_ASSOC)) { 14. $results[$i++] = $row; 15.} 16.require('/usr/local/lib/php/Smarty/Smarty.class.php'); 17. 18.// create object 19.$smarty = new Smarty; 20.// pass the results to the template 21.$smarty->assign('courses', $results); 22.$smarty->assign('department_code', $_GET['department_code']); 23. 24.$smarty->template_dir = './smarty_templates'; 25.$smarty->compile_dir = '/tmp/smarty/templates_c'; 26.$smarty->cache_dir = '/tmp/smarty/cache'; 27.$smarty->config_dir = './smarty_configs'; 28. 29.// display it 30.$smarty->display('courses.tpl'); 31. 32.// Free resultset 33.mysql_free_result($res); 34.// Closing connection 35.mysql_close($link); 36.?> 37.