WEB Basics Contents q How the web works
WEB Basics
Contents q How the web works q Fundamental Web Technologies q Client Side Coding q Server Side Coding 3/3/2021 Web Technologies 2
Client-Server Architecture Client Request Server Response 3/3/2021 Web Technologies 3
Accessing a Web Page DNS Server google. com 192. 168. 1. 4 tuc. gr 147. 27. 15. 134. . domain. Name server IP 2 google. com 192. 168. 1. 4 3 1 192. 168. 1. 4 Server Response Client 3/3/2021 Browser Web Technologies 4 Server 4
URL Analysis Protocol Domain Name http: //www. tuc. gr/students. html World Wide Web 3/3/2021 Web Technologies File (web page) 5
DNS server q Domain Name System (DNS) manages public names of Web sites and transforms them to IPs (data base of Web site names and IPs) q A DNS server is registered to join the Domain Name System q DNS servers are organized in hierarchy q 13 Root servers (named A, B, C … M) q. Lower level DNS Servers maintain only pieces of this information, public providers and others q. Local DNS servers are maintained by the ISPs, primary and back-up DNS servers, gateways, manually or by DHCPs. q Queries are propagated upwards in hierarchy 3/3/2021 https: //www. techradar. com/news/bestdns-server 6
3/3/2021 Web Technologies 7
Protocols Define rules to govern the request-response process Define the structure of the request-response messages so they can be machine understandable. Common protocols: 'http: //‘ , 'https: //' , 'ftp: //' 3/3/2021 Web Technologies 8
HTTP Protocol Hyper. Text Transfer Protocol Text based 2 Types of messages: Requests & Responses Status Line Headers Blank Line Body 3/3/2021 Web Technologies 9
Request Method Request URI HTTP-version Headers Body 3/3/2021 Web Technologies 10
Response HTTP-version Response Code Headers Body 3/3/2021 Web Technologies 11
Request - Response Http Request Example: GET /people/students. html HTTP/1. 1 Host: www. tuc. gr User-agent: Mozilla/4. 0 Connection: close Accept-language: gr Http Response Example: HTTP/1. 1 200 OK Content-Type: text/html Content-Length: 6827 Connection: close Server: Apache Tomcat/4. 0. 2 Last-Modified: Tue, 12 Feb 2002 18: 24: 48. . . <body> Response Codes: 401 (Not found) 200 (Ok) etc 3/3/2021 Web Technologies 12
PUT - POST q. Typically PUT to create resources, POST to update resources but this isn’t exactly the way they are meant to work q. PUT to create and update resources when their exact location is known – idempotent method q. POST when their exact location is not known and is decided by the server – not idempotent or safe q. Idempotent method: can be called many times and the outcome is always the same, safe method 3/3/2021 Web Technologies 13
PUT - POST Will be created at this location Created at this location, Decided by server 3/3/2021 Web Technologies 14
HTTP Protocol – Response Codes 100– 199 Informational (101 switch protocol) 200– 299 Successful page access 300– 399 Redirect the request 400– 499 Client errors 500– 599 Server errors 3/3/2021 Web Technologies 15
HTML Hyper. Text Markup Language The language to create web pages Not a programming language. Used to visualize Content. Has pre-defined presentation semantics that denote how the structured data is to be presented. 3/3/2021 Web Technologies 16
HTML Document Structure <HTML> <HEAD> </HEAD> <BODY> </BODY> </HTML> 3/3/2021 Beginning of HTML Document Head Content Only the Body is displayed!!! Body Content End of HTML Document https: //www. w 3 schools. com 17
HEAD Elements <title> Web Page Title </title> <style> Title: Adds a title to the web page. (Displayed in the browser tab, On bookmarks, on search engines, etc) body {background: #000; } a{ color: red; font-weight: bold; } </style> Style: Adds css rules to a page <link rel="stylesheet" type="text/css" href="style. css"> Link: Defines the relationship between a document and an external resource (css file – formatting instructions). 3/3/2021 Web Technologies 18
HTML Based on HTML element tags ( <h 1> , </h 1>, <img> etc. ) Browsers read HTML files to compose visible or audible web pages. HTML tags are not displayed. They are used to interpret the content of pages. HTML BROWSER <H 1> This is a title </H 1> First line. Second line. <br/> <b> Third Line </b> 3/3/2021 This is a title First line. Second line. Third Line Web Technologies 19
Divs In HTML we have BLOCK and INLINE elements BLOCK elements: Start and end with a new line. Examples: <h 1> - <h 6>, <p>, <ul>/<li>, <uo>/<li>, <table> INLINE elements: Start and end with a new line Examples: <b>, <em>, <td>, <a>, <img> Divs are BLOCK elements! 3/3/2021 Web Technologies 20
HTML <a> q. A link to W 3 CSchools q<a href="http: //www. w 3 schools. com">Visit W 3 Schools. com!</a> q. Will produce q. Visit W 3 Schools. com! q. If clicked will open : http: //www. w 3 schools. com 3/3/2021 Web Technologies 21
HTML Attributes: Name-Value Pairs E. g. , width = “ 100” , Border = “ 2” etc. The image is a link – you can click on it. <a href=‘http: //example. org’ > <img src=“dog. png" width="50" height="50" border=“ 0“ > </a> In BROWSER you see: 3/3/2021 Web Technologies 22
CSS Cascading Style Sheets A set of rules used to describe the look and formatting of an HTML document Designed to enable the separation of content from presentation <div> groups elements to format them with CSS Internal (inline) or External (Separate file) CSS Inline CSS Browser <h 1 style="color: red"> Styles in HTML. </h 1> Styles in HTML. 3/3/2021 Web Technologies 23
CSS Example 1 3/3/2021 Web Technologies 24
CSS Example 2 3/3/2021 Web Technologies 25
HTML DOM q. When a page is loaded the browser creates a Document Object Model of the page 3/3/2021 Web Technologies 26
Javascript Client Side Scripts Interact with user (e. g. , dialogue box, confirm box, button) Control browser behavior (e. g. , Don’t allow right click) Alter the document content dynamically (e. g. , use events) Communicate asynchronously (Ajax) with the server Can be placed in the <body> and the <head> sections 3/3/2021 Web Technologies 27
Javascript Example Any number of <script>s within <body> or <head> Define Functions Inside “scripts” 3/3/2021 Web Technologies 28
get. Element. By. Id( ) q. The main Javascript method qdocument. get. Element. By. Id("demo"). inner. HT ML = "Hello” will search for element with id=“demo” and change its content to “Hello” qdocument. get. Element. By. Id("demo"). style. font Size = "25 px” will change font size of element with id=“demo” qdocument. get. Element. By. Id("demo"). style. disp lay="block” will hide element with id=“demo” 3/3/2021 Web Technologies 29
Output q. Java. Script can "display" data in different ways: q. Writing into an alert box, using window. alert( ) q. Writing into the HTML output using document. write( ) q. Writing into an HTML element, using inner. HTML q. Writing into the browser console, using console. log( ) 3/3/2021 Web Technologies 30
Document. write() Will replace all existing HTML with the value in (. . ) 3/3/2021 Web Technologies If button is pressed, 11 will replace html content on screen 31
inner. HTML Will replace content of id=“demo” with 11 3/3/2021 11 will appear in existing HTML Web Technologies 32
inner. HTML Javascript code: Before button is clicked: After button is clicked: 3/3/2021 Web Technologies 33
Javascript Functions Javascript with function declared Before button is clicked After button is clicked 3/3/2021 Web Technologies 34
Javascript Forms If you click 3/3/2021 Form data will be sent to Web Technologies page: /action_page. php then 35
Javascript Datatypes Example Output: Saab 3/3/2021 Web Technologies 36
Javascript Object Output: 3/3/2021 Web Technologies 37
Javascript Object Notation (JSON) q A format for sending & receiving objects/xml q. Objects with many attribute value pairs qvar json='{"first. Name": "John”, ”last. Name”: ”Doe”}’; JSON q. This is equivalent to var jobj= {first. Name: “John”, last. Name: “Doe”}; JS Object 3/3/2021 Web Technologies 38
JS (JSON) Object vs JSON q JSON: Java. Script Object Notation q Closely related to JS Object, very similar syntax, all JS Object data are valid JSON data and the reverse q JSON is language independent format used to exchange information between services but JS Object is for JS use only JS Object 3/3/2021 JSON https: //medium. com/@easyexpresssoft/object-literal-vs-json-7 a 2084872907 39
JS Object, JSON Conversion q. Javascript has built-in support for conversion between JSON and javascript object q. JSON. stringify(obj): converts an JS object ‘obj’ to a JSON data, q. JSON. parse(data): coverts JSON (text) data ‘data’ to JS object 3/3/2021 Web Technologies 40
JSON - JS Object example Output: 3/3/2021 Web Technologies 41
JSON Example JSON Converts JSON to JS Object 3/3/2021 Web Technologies 42
JSON Array 3/3/2021 Web Technologies 43
JSON vs XML q Syntax for storing / exchanging data, alternative to XML JSON XML 3/3/2021 Web Technologies 44
Angular. JS q Angular. JS extends HTML attributes with Directives, and binds data to HTML with Expressions q Directive: introduces new syntax that associates new behavior to DOM elements (attribute, names) via event listeners q. Built-in, custom directives q Can be added to HTML with the <script> tag: 3/3/2021 Web Technologies 45
Built-in Directives q ng-app: initializes Angular. JS application, defines <div> element as the owner of the Angular. Js expression q ng-model: binds value of an input field to variable created in Angular. JS q ng-bind: binds to value of inner. HTML (print/use value) q ng-init: initializes application data q ng-repeat: repeats HTML elements q use double braces {{ }} or ng-bind to display content from the model : <p>First name: {{firstname}}</p> 3/3/2021 Web Technologies 46
Angular. JS Example <div> is owner of Angular JS application replace the content of HTML element with this value Same as <p>}}name}}</p> 3/3/2021 Web Technologies 47
Angular. JS Example init value OUTPUT <p>Your wrote: <span ng-bind="name"><span></p> Web Technologies 3/3/2021 48
ng-repeat, ng-init Output: Code: 3/3/2021 Web Technologies 49
PHP q Server scripting language for making dynamic and interactive Web pages (alternative to ASP) q PHP scripts execute on the server, various platforms q PHP code combined with HTML, CSS, JQUERY, Javascript. . q What can PHP do q can generate dynamic page content q Manipulate files (open, read, write, delete, close files) on server q can collect form data q can send and receive cookies q can add, delete, modify data in database q can be used to control user-access q can encrypt data 3/3/2021 Web Technologies 50
PHP Example <? php for($i=0; $i<4; $i++) { ? > <h 1>This is a test</h 1> <? php } ? > vars start with $ No datatypes ! <h 1>This is a test</h 1> 3/3/2021 Web Technologies 51
Why Server Side Scripting? 1. Create HTML dynamically: <? php for($i=0; $i<1000; $i++) { ? > <h 1>User: <? php echo $users[$i]; ? ></h 1> <? php } ? > 2. Control the flow and structure a page accordingly <? php if($language == ‘en’) { ? > <h 1> English </h 1> <? php } else { ? > <h 1> Ελληνικά </h 1> <? php } ? > 3/3/2021 Web Technologies <? php if($language == ‘en’) { echo ‘english’; } else { echo ‘Ελληνικά’; } ? > 52
AJAX q AJAX = Asynchronous Java. Script and XML over HTTP. q Allows Web client to communicate with the server in the background asynchronously without interfering with the content of the entire page q Typically calls to XMLHttp. Request from Java. Script q Data format: XML/JSON q Advantages: q allows web pages to be updated asynchronously by exchanging data with the server q possible to update parts of a web page, no reloading of the page q Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs 3/3/2021 Web Technologies 53
HOW AJAX Works q XMLHttp. Request (XHR) to exchange data asynchronously with server q Java. Script to display/interact with information 3/3/2021 Web Technologies 54
AJAX Example Javascript code triggered every time the ready. State changes Value 4: request ok, response ready Input Output The server/file location 3/3/2021 Web Technologies 55
XMLHttp. Request Object Methods Method Description new XMLHttp. Request() Creates a new XMLHttp. Request object abort() Cancels the current request get. All. Response. Headers() Returns header information get. Response. Header() Returns specific header information open(method, url, async, user, psw) Specifies the request method: the request type GET or POST url: the file location async: true (asynchronous) or false (synchronous) user: optional user name psw: optional password send() Sends the request to the server Used for GET requests send(string) Sends the request to the server. Used for POST requests set. Request. Header() Adds a label/value pair to the header to be sent 3/3/2021 Web Technologies 56
XMLHttp. Request Object Properties Property Description onreadystatechange Defines a function to be called when the ready. State property changes ready. State Holds the status of the XMLHttp. Request. 0: request not initialized 1: server connection established 2: request received 3: processing request 4: request finished and response is ready response. Text Returns the response data as a string response. XML Returns the response data as XML data status Returns the status-number of a request 200: "OK" 403: "Forbidden" 404: "Not Found" For a complete list go to the Http Messages Reference status. Text Returns the status-text (e. g. "OK" or "Not Found") 3/3/2021 Web Technologies 57
Server Side Scripting Client Side Scripting HTML CSS JAVASCRIPT JQUERY ANGULAR Server Side Scripting BROWSER PHP JSP ASP node. js Server A script running on the server before the server responds to the client's request 3/3/2021 Web Technologies 58
Server Side Scripting Client Requests Page Server processes the scripts (php, jsp, asp) and returns an HTML page to the client 3/3/2021 Web Technologies 59
Why Use Server Side Scripting? Restrict Clients Access to resources (e. g. , a Database) Example: Login Authentication if(username == “admin” && password == “ 12345”) Clients CANNOT view server side code!!! 3/3/2021 Web Technologies 60
Server Side Languages Language Server PHP Apache JSP (Java) Apache Tomcat ASP. Net (Visual Basic) Windows. Net Server 3/3/2021 Web Technologies License/ Server OS Open ALL Microsoft Proprietary Windows Server 61
Java. Server Pages (JSP) q. Similar to PHP is used to create Web pages dynamically based on HTML, XML q. Apache Tomcat (servelet container) q. JSPs are translated to servlets at runtime q. JSPs are combined with Java code and HTML with the resulting page being compiled and executed on the server 3/3/2021 Web Technologies 62
Asynchronous Programming 3/3/2021 Web Technologies 63
• Ajax Contents Long Polling Server Side Events Web. Sockets Node. JS (Javascript On the Server) 3/3/2021 Web Technologies 64
Real Time Applications § Web apps need to communicate with the server in realtime: § real-time chat application § multi-player HTML 5 game § event-based applications § HTTP is based on request/response § Lots of overhead in request handshake, error checking, and delivery validation § Cannot make very often requests to server
AJAX Using javascript to make a asynchronous requests to server
AJAX Cons - Pros Works when: üclient needs to request or send data occasionally Falls short when: üclient needs to request or send data often üserver needs to initiate and send data without client request
AJAX long polling
How it works q. Similar to AJAX but Long polling makes the client to poll the server for an event (or set of events) until timeout q. Client sends AJAX request to the server which is kept open until the server has new data to respond or until timeout q. Client immediately sends another long-poll request after receiving response q. The response can contain XML or JSON or javascript to be executed on the client 3/3/2021 Web Technologies 69
AJAX long polling Works when: ü Client needs to request one or a few pieces of data at a time ü Server needs to send one or a few pieces of data occasionally Falls short when: üclient needs to send data often üclient needs to initiate and send data when available üserver needs to send data often
Server-Sent Events (SSE) q Client opens connection with server and gets updates from a server automatically q Server sends data to client as it becomes available
Server-Sent Events (SSE) Works when: ü server needs to send data often Falls short when: ü uni-drirectional channel (server to client) üclient needs to send data requires new channel
Websockets q Client opens connection with server q Client and server send data to each other as data becomes available on either side
Websockets ü Bi-directional, full-duplex, persistent connection from a web browser to a server. ü Once a Web. Socket connection is established the connection stays open until the client or server decides to close this connection. ü Web programming entirely event driven, not (just) user initiated. üServer application is aware of all connections, allowing you to communicate with any number of open connections at any given time.
Websockets
Websocket events
Websocket on. Event Actions ü Update the Client that send the message ü Update a specific Client ü Update all clients ü Update all Clients except the Client that send the message
Message Datatypes üStrings üBuffered arrays üBlobs
SSEs vs Web. Sockets q Advantages of SSE over Web. Sockets: q Transported over simple HTTP instead of a custom protocol q Built in support for re-connection and event-id q Simpler protocol q Advantages of Websockets over SSE: q Real time, two directional communication. q Native support in more browsers q Web. Socket is a different protocol from HTTP (works over TCP) q Ideal use cases of SSE: q Stock ticker streaming q twitter feed updating q Notifications to browser 3/3/2021 http: //stackoverflow. com/questions/5195452/websockets-vs-server-sent-eventsource 79
Javascript on the server (Node. js) ü An environment that allows running javascript server side ü Designed to build scalable applications, many connections are handled concurrently ü Asynchronous Event-driven programming: For each operation you have to specify a callback function that is executed when the operation is complete. ü Until a “callback” is fired Node. js is sleeping ü One script handles all communication with the clients considerably reducing the number of resources used by the application (High performance web Apps) 3/3/2021 Web Technologies 80
Javascript on the server (Node. js) PHP Node. js is 93% faster than PHP !!!
No-SQL Databases 3/3/2021 Web Technologies 82
No. SQL Databases q Non-relational or “not only SQL”, schema-less (e. g. each application can adopt a different schema) q Data is not only in tabular form, triggered by the needs of Facebook, Amazon, Google q Simplicity of design (making some operations faster than in relational), scalability q Compromise consistency in favor of speed (Transaction management? Triggering mechanisms? ) q Elasticity: Both storage and server capacity can be added on-the-fly by merely adding more servers. No downtime is required when a new node is added q Low level query languages, no standardized interfaces 3/3/2021 http: //www. dataversity. net/nosql-vs-sql-its-about-the-performance-and-scale/ 83
Mongo. DB vs SQL: Query processing SQL databases ü Multiple queries are processed in parallel by using threads üStrong mathematical basis üPredefined schema üDeclarative syntax ü Row-locking üConsistency – Integrity checking üTriggering No SQL databases ü Not all data need to be relational üComplex queries with no joins üDynamic schema (schema evolves without changing data) ü Scalable !!
Types of No. SQL Databases q Key-value store: data is represented as a collection of key-value pairs, such that each possible key appears at most once in the collection (JSON store) q Column Based: collections of key-value pairs (multiple columns, but no pre-structured table), good when key-valu store is not good enough, good for unstructured data (e. g. Io. T data) q Document store: documents encapsulate and encode data q Graph store: data whose relations are well represented as a graph consisting of elements interconnected with a finite number of relations between them. The type of data could be social relations, public transport links, road maps or network topologies (RDF store). q Object store: information is represented in the form of objects as used in object-oriented programming q XML store 3/3/2021 Web Technologies 85
No. SQL Systems q. When to use: very large data sets, very fast especially for writes, reads are also fast, no structure from the beginning q. Popular Systems: q. Key/value: Redis, Memcache. DB q. Column: Cassandra, Hbase q. Document: Mongo. DB, Couch. Base q. Graph: Orient. DB, Neo 4 J 3/3/2021 https: //www. digitalocean. com/community/tutorials/a-comparison-of-nosql-databasemanagement-systems-and-models 86
Mongo. DB vs SQL: Storage Example User Article ID NAME ID TITLE TEXT 1 User 1 1 Title 1 Some text 1 2 User 2 2 Title 2 Some text 2 3 User 3 3 Title 3 Some text 3 4 user 4 4 Title 4 Some text 4 Comment ID TEXT USER_ID ARTICLE_ID 1 comment 1 1 2 2 Comment 2 1 2 3 comment 3 1 3
Mongo. DB Storage Example ARTICLE { _id : 1 , title : ”Title 1” , Text : “Some text 1”, Comments : [ { User : 1 , text : ”comment 1” } , { user : 1 , text : ”Comment 2” } , { User : 2 , text : ”comment 3” } ] } { _id : 2 , title : ”Title 2” , Text : “Some text 2”, Comments : [ { User : 3 , text : ”comment 4” } , { user : 1 , text : ”Comment 5” } , { User : 1 , text : ”comment 6” } ] }
Mongo. DB vs SQL: Query processing Reads and writes with Mongo. DB are like single reads and writes
Popular No. SQL systems and Comparison q. Mongo. DB: http: //db-engines. com/en/ranking q. Cassandra: https: //cassandra. apache. org q. The DB-Engines Ranking ranks database management systems according to their popularity: http: //db-engines. com/en/ranking q. Comparison: qhttps: //kkovacs. eu/cassandra-vs-mongodb-vscouchdb-vs-redis qhttp: //blog. nahurst. com/visual-guide-to-nosqlsystems 3/3/2021 Web Technologies 90
References qhttp: //www. w 3 schools. com qhttps: //www. tutorialspoint. com/web_develo pment_tutorials. htm qhttps: //en. wikipedia. org q https: //developer. mozilla. org/en. US/docs/Web 3/3/2021 Web Technologies 91
- Slides: 91