Web application development (part 2) Netzprogrammierung (Algorithmen und Programmierung V)

Similar documents
Client-side Web Engineering From HTML to AJAX

JavaScript By: A. Mousavi & P. Broomhead SERG, School of Engineering Design, Brunel University, UK

JavaScript Basics & HTML DOM. Sang Shin Java Technology Architect Sun Microsystems, Inc. sang.shin@sun.com

Short notes on webpage programming languages

Building Ajax Applications with GT.M and EWD. Rob Tweed M/Gateway Developments Ltd

AJAX The Future of Web Development?

Overview. In the beginning. Issues with Client Side Scripting What is JavaScript? Syntax and the Document Object Model Moving forward with JavaScript

Web Pages. Static Web Pages SHTML

Credits: Some of the slides are based on material adapted from

Script Handbook for Interactive Scientific Website Building

Real SQL Programming 1

Software Requirements Specification For Real Estate Web Site

MASTERTAG DEVELOPER GUIDE

PHP Tutorial From beginner to master

Example. Represent this as XML

Web Programming Step by Step

Performance Testing for Ajax Applications

WIRIS quizzes web services Getting started with PHP and Java

The Web Web page Links 16-3

«W3Schools Home Next Chapter» JavaScript is THE scripting language of the Web.

CSC 551: Web Programming. Spring 2004

Chapter 1 Programming Languages for Web Applications

LabVIEW Internet Toolkit User Guide

Further web design: HTML forms

Novell Identity Manager

SUBJECT CODE : 4074 PERIODS/WEEK : 4 PERIODS/ SEMESTER : 72 CREDIT : 4 TIME SCHEDULE UNIT TOPIC PERIODS 1. INTERNET FUNDAMENTALS & HTML Test 1

Term Paper. P r o f. D r. E d u a r d H e i n d l. H o c h s c h u l e F u r t w a n g e n U n i v e r s i t y. P r e s e n t e d T o :

Intell-a-Keeper Reporting System Technical Programming Guide. Tracking your Bookings without going Nuts!

Introduction to XHTML. 2010, Robert K. Moniot 1

HTML Forms and CONTROLS

WEB DEVELOPMENT COURSE (PHP/ MYSQL)

10CS73:Web Programming

Web Development. Owen Sacco. ICS2205/ICS2230 Web Intelligence

Rich Internet Applications

TATJA: A Test Automation Tool for Java Applets

Are AJAX Applications Vulnerable to Hack Attacks?

Web Development 1 A4 Project Description Web Architecture

The purpose of jquery is to make it much easier to use JavaScript on your website.

Design and Functional Specification

Chapter 12: Advanced topic Web 2.0

A Tale of the Weaknesses of Current Client-side XSS Filtering

Xtreeme Search Engine Studio Help Xtreeme

It is highly recommended that you are familiar with HTML and JavaScript before attempting this tutorial.

Web Development. Owen Sacco. ICS2205/ICS2230 Web Intelligence

Adding Panoramas to Google Maps Using Ajax

DESIGNING HTML HELPERS TO OPTIMIZE WEB APPLICATION DEVELOPMENT

Dynamic Web-Enabled Data Collection

Web. Services. Web Technologies. Today. Web. Technologies. Internet WWW. Protocols TCP/IP HTTP. Apache. Next Time. Lecture # Apache.

HTML Form Widgets. Review: HTML Forms. Review: CGI Programs

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

Building Rich Internet Applications with PHP and Zend Framework

Web Development CSE2WD Final Examination June (a) Which organisation is primarily responsible for HTML, CSS and DOM standards?

Web Development and Core Java Lab Manual V th Semester

Web Programming with PHP 5. The right tool for the right job.

07 Forms. 1 About Forms. 2 The FORM Tag. 1.1 Form Handlers

Web Hosting Prep Lab Homework #2 This week: Setup free web hosting for your project Pick domain name and check whether it is available Lots of free

HTML Basics(w3schools.com, 2013)

ASP.NET: THE NEW PARADIGM FOR WEB APPLICATION DEVELOPMENT

CSc 230 Software System Engineering FINAL REPORT. Project Management System. Prof.: Doan Nguyen. Submitted By: Parita Shah Ajinkya Ladkhedkar

Preface. Motivation for this Book

Developing XML Solutions with JavaServer Pages Technology

AJAX: Highly Interactive Web Applications. Jason Giglio.

Chapter 2: Interactive Web Applications

JISIS and Web Technologies

Introducing Apache Pivot. Greg Brown, Todd Volkert 6/10/2010

Outline. CIW Web Design Specialist. Course Content

CSCI110: Examination information.

Web Design Specialist

JavaScript: Client-Side Scripting. Chapter 6

AJAX and JSON Lessons Learned. Jim Riecken, Senior Software Engineer, Blackboard Inc.

Fig (1) (a) Server-side scripting with PHP. (b) Client-side scripting with JavaScript.

Web-JISIS Reference Manual

Team Members: Christopher Copper Philip Eittreim Jeremiah Jekich Andrew Reisdorph. Client: Brian Krzys

Visualizing a Neo4j Graph Database with KeyLines

InPost UK Limited GeoWidget Integration Guide Version 1.1

Web Design Basics. Cindy Royal, Ph.D. Associate Professor Texas State University

ACCESSING THE PROGRESS OPENEDGE APPSERVER FROM PROGRESS ROLLBASE USING JSDO CODE

CS412 Interactive Lab Creating a Simple Web Form

Designing and Implementing an Online Bookstore Website

Chapter 13 Computer Programs and Programming Languages. Discovering Computers Your Interactive Guide to the Digital World

WEB PROGRAMMING DESKTOP INTERACTIVITY AND PROCESSING

Government Girls Polytechnic, Bilaspur

Instructions for Embedding a Kudos Display within Your Website

An introduction to creating JSF applications in Rational Application Developer Version 8.0

Asset Management. By: Brian Johnson

Enabling AJAX in ASP.NET with No Code

Efficiency of Web Based SAX XML Distributed Processing

Three Approaches to Web. with RPG

WEB PROGRAMMING LAB (Common to CSE & IT)

Website Planning Checklist

If your organization is not already

Attacks on Clients: Dynamic Content & XSS

Java Application Developer Certificate Program Competencies

Topics in Website Testing. [Reading assignment: Chapter 14, pp ]

XML Processing and Web Services. Chapter 17

How To Build A Web App

Mobile Web Design with HTML5, CSS3, JavaScript and JQuery Mobile Training BSP-2256 Length: 5 days Price: $ 2,895.00

AJAX. Gregorio López López Juan Francisco López Panea

THE CHALLENGE OF ADMINISTERING WEBSITES OR APPLICATIONS THAT REQUIRE 24/7 ACCESSIBILITY

HTML Tables. IT 3203 Introduction to Web Development

Transcription:

Web application development (part 2) Netzprogrammierung (Algorithmen und Programmierung V)

Our topics today Server Sided Approaches - PHP and JSPs Client Sided Approaches JavaScript Some basics The Document Object Model (DOM) JavaScript Frameworks (e.g., jquery, Processing.js) Asynchronous Java and XML (AJAX) Synchronous vs. asynchronous interaction pattern Web application request flow vs. AJAX request flow Core AJAX concepts (esp. XMLHttpRequest) Discussion of a simple AJAX example Applets - Web Sockets 2

Model-View-Controller (Design Pattern) Servlet Container WWW- Browser (Client) HTTP Request HTTP Response Controller Controller (Servlet) View View (JSP) Model (Java- Model Beans) 3

Server-Side Scripting Additional HTML generated sources embedded in HTML pages Typical representatives: - JSP - Java Server Pages - PHP - Personal Home Page - ASP - Active Server Pages (Microsoft IIS) - HTML HTML Database Scripting Scripting Application Logic 4

Two Variants Develop Application <HTML> <xsp:...> Develop Application <HTML> <xsp:...> </HTML> </HTML> Runtime Interpreter Compile Time (only once) Compiler Executable Program Runtime HTML- Document HTML- Document 5

Web application development Java Server Pages (JSP) 6

Variant 2, JSP Sequence HTTP- Server Servlet generation from JSP (HTML + Scripting) JSPpage Client Database Request Response Servlet Start connection SQL queries Results State 7

Java Server Pages (JSPs) JSPs have a different syntax then Servlets: Servlets produce HTML code within the Java code JSPs embed Java code in HTML code JSPs are translated internally into Servlets by the Web container Advantage of JSPs: Separation of responsibilities programming of application logic can be done in Java by programmer; Design of pages can be done by Web designer Component based Structure is normal HTML with additional basic tags: Scriptlets, Expressions, Declarations, Directives 8

Scriptlets Scriptlet Tag <% code %> Embed Java code in JSP document The code will be executed when the JSP is called <html> <body> <% for (int i = 0; i < 2; i++) { %> <p>hello World!</p> <% } %> </body> </html> <html> <body> </body> </html> <p>hello World!</p> <p>hello World!</p> 9

Expressions Expression Tag - <%= expression %> - Embed a Java expression which will be executed every time when the JSP is loaded - Note: no ; after the Java expression! - Otherwise syntax failure <html> <body> <p><%= Integer.toString( 5 * 5 ) %></p> </body> </html> <html> <body> <p>25</p> </body> </html> 10

Declaration Declaration Tag - <%! declaration %> - Embed Java declaration in JSP - e.g. Method declaration: <html> <body> <%! public boolean ispositive(int x) { if (x < 0) { return false; } else { return true; } } %> </body> </html> 11

URL-encoded Parameter JSP provides an object request which stores attributes and transfers them to the request on the JSP page Parameter can set the URL-encoding: Example: http://localhost/example.jsp?param1=hello&param2=world example.jsp: <html> <body> <p><%= request.getparameter( param1 ) %></p> <p><%= request.getparameter( param2 ) %></p> </body> </html> <html> <body> <p>hello</p> <p>world</p> </body> </html> 13

JSP Action Tags JSP Action Tags - <jsp:property /> - property defined in Tag Library Definition files - JSP Tag reference: http://java.sun.com/products/jsp/syntax/1.2/syntaxref12.html <html> <body> <jsp:usebean id= user class= mypackage.user /> <jsp:setproperty name= user property= username value= APaschke /> <p>user Name: <jsp:getproperty name= user property= username /></p> </body> </html> 14

JSP and Sessions Problem: HTTP is stateless Solution for JSPs: support for Sessions. - Sessions store attributes. - Session attribute are persistent by using Cookies or request parameter are transferred - The Session object implements the methods of the interface javax.servlet.http.httpsession. Method getid() getcreationt ime() isnew() Description Returns the session ID. Returns the time at which the session was created Returns true if user s browser has not yet confirmed the session id. invalidate() Discards the session, releasing any objects stored as attributes. getattribute (String key) setattribute (String key, String value) Returns an attribute that is stored in the session. Stores an attribute in the sessions. 15

Web application development Hypertext Preprocessor (PHP) 17

Example: Printing a dynamic date Using CGI HTML is embedded within the script-code Problem is that it becomes unreadable if there is more HTML than code print("<html>"); print("<h1>sample</h1>"); var now = new Date(); print("it is now <strong>"+ now + "</strong>"); print("</html>"); Using PHP Script-code is embedded in HTML instead of other way around! Inside-out programming <HTML> <H1>Sample</H1> It is now <strong> <?php echo date?> </strong> </HTML> 18

PHP basics Interpreted Approach In 1995 developed by Rasmus Lerdorf (member of the Apache Group) Originally designed as a tool for tracking visitors at Lerdorf's Web site Within 2 years, widely used in conjunction with the Apache server Developed into full-featured, scripting language for server-side programming Free, open-source, New to PHP? Then go to this http://de.php.net/. 19

Three basic application areas Server-side scripting Most traditional and main target field Ingredients: PHP parser (e.g., CGI), a web server and a web browser Command line scripting Use a PHP script to run it without any server or browser Ingredients: PHP parser Writing desktop applications Well, is not the very best language to create a desktop application with a graphical user interface Ingredients: you know PHP very well, and if you need some advanced PHP features in your client-side applications use PHP-GTK 20

Basic PHP syntax A PHP scripting block always starts with <?php and ends with?>. A PHP scripting block can be placed (almost) anywhere in an HTML document. <html> <!-- hello.php --> <head><title>hello World</title></head> <body> <p>this is going to be ignored by the PHP interpreter.</p> <?php echo <p>while this is going to be parsed.</p> ;?> <p>this will also be ignored by the PHP preprocessor.</p> <?php print( <p>hello and welcome to <i>my</i> page!</p>');?> </body> </html> print and echo for output a semicolon (;) at the end of each statement 21

Variables and arrays All variables in PHP start with a $ sign symbol. A variable's type is determined by the context in which that variable is used (i.e. there is no strong-typing in PHP). $dutch_dessert = Vanillevla ; // string $x = 28; // integer $pi = 3.1415; // double $whatever = TRUE; // boolean Variables are case-sensitive, beware! $alp5!= $ALP5 An array in PHP is actually an ordered map. A map is a type that maps values to keys. <?php $arr = array("foo" => "bar", 12 => true); echo $arr["foo"]; // bar array() = creates arrays echo $arr[12]; // 1?> key = either an integer or a string. value = any PHP type. 22

Functions in PHP The PHP function reference is available on http://php.net/quickref.php. It shows the impressive list of functions within PHP. For example: date() is a built-in PHP function that can be called with many different parameters to return the date (and/or local time) in various formats But you also can create your own functions. If you recreate one of the built-in functions, your own function will have no effect. 23

File Open The fopen("file_name","mode") function is used to open files in PHP. r Read only. r+ Read/Write. w Write only. w+ Read/Write. a Append. a+ Read/Append. x Create and open for write only. x+ Create and open for read/write. <?php $fh=fopen("welcome.txt","r");?> For w, and a, if no file exists, it tries to create it (use with caution, i.e. check that this is the case, otherwise you will overwrite an existing file). <?php if (!($fh=fopen("welcome.txt","r")) ) exit("unable to open file!");?> For x if a file exists, this function fails (and returns 0). If the fopen() function is unable to open the specified file, it returns 0 (false). 24

Form handling Any form element is automatically available via one of the built-in PHP variables (provided that element has a name defined with it). <html> <-- form.html --> <body> <form action="welcome.php" method="post"> Enter your name: <input type="text" name="name" /> <br/> Enter your age: <input type="text" name="age" /> <br/> <input type="submit" /> <input type="reset" /> </form> </body> </html> <html> <! - welcome.php --> <body> Welcome <?php echo $_POST["name"].. ;?><br /> You are <?php echo $_POST["age"];?> years old! $_POST contains all POST data. $_GET contains all GET data. </body> </html> 25

Web application development (part 2) Client-Sided Approaches 26

Client Sided WWW Applications Many tasks can be done by the clients (better load balancing) - Check user input - Create graphics - Manipulation of WWW-Documents - Additional possibilities for the user interface Client sided approaches - Browser Plug-Ins (e.g. Macromedia Flash, ) - Script languages (JavaScript, ) - Mobile Code (Java Applets) - Microsoft ActiveX Security problem!!! 27

Web application development JavaScript 29

JavaScript (!= Java) Scripting language, e.g., for - Authentification - Automated (partial) reloads of sites Embedded in HTML - <script type="text/javascript" > </script> - or external file - <script type="text/javascript" src= a.js"></script>

What can JavaScript do? JavaScript gives HTML designers a programming tool - HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages JavaScript can react to events - A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element JavaScript can read and write HTML elements - A JavaScript can read and change the content of an HTML element JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve information on the visitor's computer 32

JavaScript object hierarchy Browser Object Model (BOM) http://www.comptechdoc.org/independent/web/cgi/javamanual/javaobjheir.html 34

JavaScript basics Declaration Explicit: var i = 12; Implicit: i = 12; Tutorial at http://www.w3schools.com/js/ Variable scope Global: Declared outside functions and any variable that is implicitly defined Local: Explicit declarations inside functions Control and looping if, switch statement while, and do-while loops (break and continue keywords) Not object-oriented but object-based function Student(studentName, studentage) { this.name = studentname; this.age = studentage; } var somestudent = new Student( Michael, 21); 35

JavaScript output The document objects allow printing directly into the browser page (amongst other things) The window object is implied. Example: Writing in text or HTML with script or without line-break document.write( I am <B>BOLD</B> ); document.writeln( I am <U>underlined</U> ); What is the window object? It is part of the Browser Object Model (BOM) BOM is a a collection of objects that represent the browser and the computer screen Objects are accessible through the global objects window and window.screen The window object is global to the extent that it represents the very host environment of all other JavaScript objects 36

Browser Window Object window object is a JavaScript representation of a browser window closed - A boolean value that indicates whether the window is closed defaultstatus - This is the default message that is loaded into the status bar when the window loads Example: window.defaultstatus = This is the status bar ; Selected build in functions alert("message ) - string passed to the alert function is displayed in an alert dialog box. window.close() - function will close the current window or the named window. confirm("message") - string passed to the confirm function is displayed in the confirm dialog box. focus() - function will give the focus to the window. open("urlname","windowname",["options"]) - new window is opened with the name specified by the second parameter. 37

Form object The Form object is a property of the document object. This corresponds to an HTML input form constructed with the FORM tag. A form can be submitted by calling the JavaScript submit method or clicking the form submit button. Form objects can be accessed by window.document.myform OR window.document.forms[0] Selected properties action - This specifies the URL and CGI script file name the form is to be submitted to. It allows reading or changing the ACTION attribute of the HTML FORM tag. target - The name of the frame or window the form submission response is sent to by the server. Corresponds to the FORM TARGET attribute. length - The number of fields in the elements array, i.e. the length of the elements array. method - This is a read or write string. It has the value "GET" or "POST". 38

Form object objects and methods Form Objects (one example) text - A GUI text field object. Methods are blur(), focus(), and select() Attributes defaultvalue - The text default value of the text field name - The name of the text field type - Type is "text value - The text that is entered and appears in the text field. It is sent to the server when the form is submitted Example accessing form field values : window.document.myform.firstname.value Form object methods reset() - Used to reset the form elements to their default values Example window.document.myform.reset(); submit() - Submits the form as though the submit button were pressed by the user Example window.document.myform.submit(); 39

Event handlers Events are actions that occur usually as a result of something the user does. For example, clicking a button is an event, as is changing a text field or moving the mouse over a hyperlink. Other events are click, change, focus, load, mouseover, mouseout, reset, submit, select You can use event handlers, such as onchange and onclick, to make your script react to events. Examples <input type= button onclick= javascript:dobutton()> <select onchange= javascript:dochange() > <a onclick= javascript:dosomething() > </a> <form onsubmit= javascript:validate() > 40

JavaScript principle Contents Behavior Presentation HTML JavaScript CSS (event handling) <head> myjs.js mycss.css <script src="myjs.js"> <link rel="stylesheet" type="text/css" href="mycss.css">... 41

From HTML to DOM HTML is a representation for hypermedia documents A representation is required to store and transmit the document HTML uses markup for representing the document structure Browsers must render HTML documents (i.e., apply CSS and execute JavaScript) 1. GET HTML from server and receive as text/html document 2. Parse document and deal with any errors by fixing them 3. Interpret document as if it had been error-free 4. GET all additional resources (CSS, images, JavaScript, ) 5. Build internal model (DOM) based on error-free interpretation 6. Apply CSS rules to determine styling of document (e.g., margins and font sizes) 7. Render into visual structure 8. Start executing JavaScript code 9. Listen for events (keyboard, mouse, timer) and execute code 42

DOM representation of an HTML page Each HTML document loaded into a browser window becomes a Document object Provides access to all HTML elements in a page, from within a script. Is also part of the Window object, and can be accessed through the window.document property. DOM describes how all elements in an HTML page are related to the topmost structure: the document itself. Example <html> <head> <title>dom</title> </head> <body> <p>lorem ipsum...</p> <p>lorem ipsum...</p> <p>link <a href="http://html.net">html.net</a></p </body> </html> 44

Accessing elements By name document.getelementsbytagname( td )[indexofcolumn] By ID document.getelementbyid( mytable ) <table id= mytable > <tr> <td width= 300 > I am text in a <BR> column </td> </tr> <tr> <td>... </td> </tr> <table> Walk the DOM Tree document.childnodes[0].childnodes[1].childnodes[4] 45

JavaScript Frameworks Different needs produce different frameworks Dojo (http://dojotoolkit.org/) Ext JS (http://www.sencha.com/products/extjs/) jquery (http://jquery.com/) Processing.js (http://processingjs.org/) More comprehensive list is on Wikipedia: http://en.wikipedia.org/wiki/list_of_javascript_libraries There is no such thing as the best JavaScript framework For any given project, decide on the support you need Evaluate frameworks for the support they provide Evaluate for functional requirements ( is there a collapse/expand folder view? ) Evaluate for non-functional requirements ( is the framework openly licensed ) 47

Web application development Asynchronous Javascript and XML (AJAX) 56

Conventional Web Applications Client Browser (State A) HTTP REQUEST (state A) HTTP Server Client Browser (State B)

AJAX basics Asynchronous Javascript and XML (AJAX) is a technology which allows client-side JavaScript to make requests to a server without causing a reload of the current page in the browser. Using AJAX and standard DOM methods, client-side JavaScript can request, receive, and visualize information in the context of a single Web page. The advantage of AJAX over more traditional Web pages is that they better resemble the behavior of desktop applications, providing enhanced features and usability for the user. The basic idea is, when you work with a web page, the web page itself can be interacting with the server, but without reloading the (whole) page you are on. The result is an uninterrupted user experience, with full server-side capabilities. AJAX is not a technology per se, but a web development method and its aim is to increase the interactivity of a website. 58

AJAX - Asynchronous JavaScript And XML AJAX combines JavaScript, HTML, DHTML, DOM und XML, in order to facilitate programming of interactive websites AJAX communicates via JavaScript code and XMLHttpRequest object asynchronously with the server. After sending request the client can proceed execution. If the response from the server arrives, the XMLHttpRequest object executes a client-site call back method which e.g. updates the website. Supported by most modern Web browsers. Examples which use Ajax: Google Maps, Gmail, Google Docs, Flickr, Facebook, etc. (see e.g. RSS Tec. (Really Simple Syndication, Weblogs, Ticker, )

Core AJAX concepts JavaScript includes an XMLHttpRequest object that can fetch files from a web server. XMLHttpRequest can load HTTP requests Synchronously: The browser will wait for the response. This is a simpler model for the developer, but the resulting blocking is not acceptable. Asynchronously: The browser will not wait, but the object will call an event handler when the loading status changes. This is what you would use in practice The contents of the fetched file can be put into current web page using the DOM. 61

Usage of XMLHttpRequest Client Browser (State A) REQUEST HTTP Server Client Browser (State Client B) Browser (State Client C) Browser (State D)

A typical Ajax request 1. User clicks, invoking event handler 2. Handler's JS code creates an XMLHttpRequest object 3. XMLHttpRequest object requests a document from a web server browser client User interface 1 JavaScript call HTML+CSS data 6 2 XMLHttpRequest callback() 5 XMLHttpRequest 4. Server retrieves appropriate data, sends it back 5. XMLHttpRequest fires event to say that the data has arrived (this is often called a callback; you can attach a handler to be notified when the data has arrived) HTTP Request 3 Web server data exchange 4 Data 6. Your callback event handler processes the data and displays it Datastores, backend processing server-side systems 63

XMLHttpRequest Methods abort() getallresponseheaders() Stops the current request Returns all headers (name and value) as a string getresponseheader(<headername>) open( GET / POST, URL [, true/false [, <username>,<password>]]) send(content) setrequestheader(<name>, <value>) Returns the value of the specified header Opens a connection and retrieves response from the specified URL. Can also specify optional values method (GET/POST), username and password for secured sites Transmits request (can include postable string or DOM object data) Assigns values to the specified header 66

Simple AJAX example <script type="text/javascript" language="javascript"> function sndreq() { var resobject = new XMLHttpRequest(); resobject.open('get', 'laender.php?wo=1',true); resobject.onreadystatechange= handleresponse; resobject.send(null); } function handleresponse() { if(resobject.readystate == 4 { document.getelementbyid( hs ).innerhtml= resobject.responsetext; } } </script> <span style="cursor: pointer; text-decoration: underline onclick="sndreq() > Einen Request absetzen. </span> <span id= hs > </span> 68

Simple AJAX example (cont.) <script type="text/javascript" language="javascript"> function sndreq() { var resobject = new XMLHttpRequest(); resobject.open('get', 'laender.php?wo=1',true); resobject.onreadystatechange= handleresponse; resobject.send(null); } function handleresponse() { if(resobject.readystate == 4 { document.getelementbyid( hs ).innerhtml= resobject.responsetext; } } </script> <span style="cursor: pointer; text-decoration: underline onclick="sndreq() > Einen Request absetzen. </span> <span id= hs > </span> 69

Simple AJAX example (cont.) <script type="text/javascript" language="javascript"> function sndreq() { var resobject = new XMLHttpRequest(); resobject.open('get', 'laender.php?wo=1',true); resobject.onreadystatechange= handleresponse; resobject.send(null); } function handleresponse() { if(resobject.readystate == 4 { document.getelementbyid( hs ).innerhtml= resobject.responsetext; } } </script> <span style="cursor: pointer; text-decoration: underline onclick="sndreq() > Einen Request absetzen. </span> <span id= hs > </span> 70

Simple AJAX example (cont.) <script type="text/javascript" language="javascript"> function sndreq() { var resobject = new XMLHttpRequest(); resobject.open('get', 'laender.php?wo=1',true); resobject.onreadystatechange= handleresponse; resobject.send(null); } function handleresponse() { if(resobject.readystate == 4 { document.getelementbyid( hs ).innerhtml= resobject.responsetext; } } </script> <span style="cursor: pointer; text-decoration: underline onclick="sndreq() > Einen Request absetzen. </span> <span id= hs > </span> 71

Simple AJAX example (cont.) <script type="text/javascript" language="javascript"> function sndreq() { var resobject = new XMLHttpRequest(); resobject.open('get', 'laender.php?wo=1',true); resobject.onreadystatechange= handleresponse; resobject.send(null); } if (resobject.status == 200) { do something with resobject.responsetext; } else { code to handle the error; } function handleresponse() { if(resobject.readystate == 4 { document.getelementbyid( hs ).innerhtml= resobject.responsetext; } } </script> <span style="cursor: pointer; text-decoration: underline onclick="sndreq() > Einen Request absetzen. </span> <span id= hs > </span> 72

AJAX examples This is a very simple idea, but it can have very nice results, such as: Google Maps (and A9 Maps) An image displaying a map of a specified region is inserted into a web page The user clicks the scroll left button The JavaScript module loads a new image and inserts it into the current document Google Suggest (and Amazon Suggest): The user types in part of a keyword The JavaScript module sends the partial keyword to the server, and gets back a list of matches, which are shown to the user 73

Using AJAX - Pros and Cons PROS [+] Enhanced User Experience [+] Reduced Bandwidth Usage [+] Increased User Productivity [+] Increased Compatibility [+] Faster & Enhanced Application Development CONS [-] Learning Curve For Developers [-] Effects On End Users [-] Not Search Engine Friendly [-] Dependency Of Browser Settings 74

Web application development Java Applets (Mobile Code) 75

Java-Applet import java.applet.*; import java.awt.*; public class FirstApplet extends Applet { //The methode paint implements the Applet public void paint(graphics g) { g.drawstring( Hello World!, 25, 50); } Java Browser (Windows XP) } /* Class FirstApplet */ 0efc345f6b7723ba83f2d90ca4 (...) Java Browser (Linux) 76

Example: Client Sided Application Presentation/ Interaction (e.g. Applet) Server-Prozess Application Logic Database Data 77

WWW and Java Applets An appropriate Browser (with Java interpreter) can execute Applets - Animations, Presentation of Graphics, Audio functionality - Local Interaction (Mouse, Keyboard) - TCP/IP-Connections to Server sided applications Problem: Security - No pointer - Validation at compile time - Verification of byte codes by the Bytecode verifier - Applets have no access to local file system (except trusted applets!) - Usual browser policy: Network connections from applets only to the Host from which the applet was loaded! 78

Web application development (part 2) Summary 82

What have we discussed today? We looked at server sided scripting approaches (JSP and PHP). We discussed the client side scripting (run in the browser) based on JavaScript (another example is e.g. VB script). Motivated by the JavaScript principle we talked about the Document Object Model; why it is useful and how can it be used? We introduced the Asynchronous Java and XML (AJAX) which allows client-side JavaScript to make requests to a server without causing a reload of the current page in the browser. We discussed the interaction patterns and the request flows and compared it to a typical web application. You should know the steps of a typical Ajax request. We briefly talked about client side application programs that are mobile programs that run as an independent program in the client machine. The typical example are Java Applets. We also shortly introduced Websockets, an approach for full-duplex single socket connection. 83

Questions How does Server-sided Scripting work and explain it on the example of JSP (or another technology)? What are the benefits? What is the difference between interpreted and compiled (server-sided) scripting? Name two client-sided approaches for dynamic web application programming. What is JavaScript and how does it work? What are the differences to server-sided scripting? How does Ajax work and what are the benefits and drawbacks? 84

References Marty Stepp (2007): Web Programming. Computer Science & Engineering, University of Washington. http://www.cs.washington.edu/education/courses/cse190m/ Erik Wilde and Dilan Mahendran (2011): Web Architecture and Information Management. School of Information, UC Berkeley. http://dret.net/lectures/web-spring11/ Gregory V. Wilson (2005) CSC309: Web Programming. Computer Science - University of Toronto. http://www.cdf.toronto.edu/~csc309h/summer Additional resources: http://www.adaptivepath.com/ideas/ajax-new-approach-web-applications http://www.comptechdoc.org/independent/web/cgi/javamanual http://www.quirksmode.org/dom/intro.html http://www.w3schools.com/js/default.asp http://www.html.net/tutorials/javascript/lesson14.php 85