Laboratorul 02.

This chapter is about e-health applications, so as a lab activity we are going to make a simple web client application using e-health data.

We will start by introducing a few concepts and technologies that are frequently used in modern e-health systems and in web services, which I am sure most of you are already familiar with.

Web Services

A web service is a piece of software that is available over the Internet or private networks. Data with a web service is usually communicated using HTTP. A web service can be created using many different languages, platforms, and frameworks, and nowadays usually follow two main formats: REST and SOAP.

Representational State Transfer (REST)

REST is an architecture used in web services whose purpose is to make data available as resources (for example “user” or “invoice”). To use REST, a language needs to be able to make HTTP calls and handle data in XML or JSON formats.

RESTful applications have four design principles.

1. Use HTTP Methods Explicitly

  • POST – creates new resources on the server
  • GET – retrieves the current state of the resource on the resource
  • PUT – change state of resource or update it on the server
  • DELETE – remove a resource from the server

2. Be Stateless

A REST call should not have any effect on future REST calls and a REST call does not depend on any previous calls. Each request should have all the information needed to satisfy the request. Statelessness speeds up development by separating the client from the server and leaving it to the client to manage stateful REST calls.

3. Use URI’s

RESTful services user Uniform Resource Identifiers (URI) which are well formatted links on the web that provides access to the resources or functions of a system. URIs are usually formatted like a directory and should be predictable and understandable.

4. Handle XML or JSON

REST services can implement multiple formats. The client is usually left to decide which format to use at runtime.

Simple Object Access Protocol (SOAP)

SOAP is a messaging protocol that makes data available as services (for example “getUser” or “PayInvoice”) allowing different systems to communicate with each other over HTTP using XML format. SOAP is used in enterprise situations where information security is paramount. SOAP is not restricted to HTTP and can also be implemented on top of other protocols such as SMTP. SOAP must use the Web Services Description Language format and is platform and language independent.

More information and comparisons:

https://u.osu.edu/ishmeet/2016/04/01/web-services/

http://nordicapis.com/rest-vs-soap-nordic-apis-infographic-comparison/

https://www.infosys.com/digital/insights/Documents/restful-web-services.pdf

Data Format

HTML

HTML is the standard markup language for creating Web pages.

  • HTML stands for Hyper Text Markup Language
  • HTML describes the structure of Web pages using markup
  • HTML elements are the building blocks of HTML pages
  • HTML elements are represented by tags
  • HTML tags label pieces of content such as “heading”, “paragraph”, “table”, and so on
  • Browsers do not display the HTML tags, but use them to render the content of the page

A simple HTML page would look like this:

<html>
  <head>
    <title> Hello world page title on the browser tab </head>
   </head>
  <body>
   <h1> Hello world! </h1>
   <div>
     <p> This is a simple HTML page </p>
   </div>
  </body>
</html>

For detailed information and syntax you can check https://www.w3schools.com/html/.

HTML was created to describe the content of a web page.

  • HTML can be formatted using CSS (Cascading Style Sheets).
  • CSS describes how HTML elements are to be displayed on screen, paper, or in other media
  • CSS saves a lot of work. It can control the layout of multiple web pages all at once
  • External stylesheets are stored in CSS files

A CSS rule-set consists of a selector and a declaration block: h1 {color:blue;}. In the above example all the h1 elements will be colored in blue.

CSS can use classes and ids in order to format specific elements.

p {color: black;}
p#special {color:red;}
.container {background: #cccccc;}
<html>
  <head>
    <title> Hello world page title on the browser tab </title>
  </head>
  <body>
    <h1> Hello world! </h1>
    <div class="container">
     <p> This is a simple HTML page </p>
     <p id="special">this is a special text</p>
    </div>
  </body>
</html>

For detailed information and syntax you can check https://www.w3schools.com/css/.

Nowadays, we use complex frameworks for CSS in order to speed up development. Popular examples are Tailwind, Bootstrap, Material. Here are some Tailwind examples that you can copy-paste immediately in order to build small sections of your app/website.

Data Transmission

Form Data

HTML is sending data by default using the form element.

<form action="https://example.com">

Data can be sent in multiple formats and multiple methods

  • The default method of the HTML form element if GET, although is not recommended anymore. We can only send simple form data using the GET method (encoded text). This will append data in the URL as query parameters, with an URL encoded string. Note that the URL string is usually limited to ~2000 characters.
<form method="GET" action="https://example.com">
result:
GET https://example.com?name=Alex&email=alex@example.com
  • We can send data using the POST or PUT method. This will also send form data using some query parameters, but they are send in a special form-data body container. We can also send complex data like images, audio, XML, JSON objects etc. using settings for Content-Type and encoding
<form method="POST" action="https://example.com" enctype="multipart/form-data" >
  • We can use Javascript to send data

XML

XML is a software - and hardware - independent tool for storing and transporting data.

  • XML stands for eXtensible Markup Language
  • XML is a markup language much like HTML
  • XML was designed to store and transport data
  • XML was designed to be self-descriptive
  • XML is a W3C Recommendation
<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

XML and HTML were designed with different goals:

  • XML was designed to carry data - with focus on what data is
  • HTML was designed to display data - with focus on how data looks
  • XML tags are not predefined like HTML tags are

JSON

JSON — short for JavaScript Object Notation — is a format for sharing data. As its name suggests, JSON is derived from the JavaScript programming language, but it’s available for use by many languages including Python, Ruby, PHP, and Java. JSON is usually pronounced like the name “Jason”.

A JSON object is a key-value data format that is typically rendered in curly braces. When you’re working with JSON, you’ll likely see JSON objects in a .json file, but they can also exist as a JSON object or string within the context of a program.

A JSON object looks something like this:

{
  "first_name" : "Alex",
  "last_name" : "Doe",
  "online" : true,
  "friends" : 236 
}

JSON values can be of the simple data types:

  • strings
  • numbers
  • objects
  • arrays
  • Booleans (true or false)
  • null

JSON supports nested objects or arrays:

{
  "first_name" : "Alex",
  "last_name" : "Doe",
  "online" : true,
  "friends" : {
	"total": 236,
	"friend_list": [
		{ "first_name": "John", "last_name":"Gray"},
		{ "first_name": "Dana", "last_name":"Fray"},
         ]
   } 
}

Comparison to XML

<users>
    <user>
        <username>SammyShark</username> <location>Indian Ocean</location>
    </user>
    <user>
        <username>JesseOctopus</username> <location>Pacific Ocean</location>
    </user>
    <user>
        <username>DrewSquir</username> <location>Atlantic Ocean</location>
    </user>
    <user>
        <username>JamieMantisShrimp</username> <location>Pacific Ocean</location>
    </user>
</users>
{"users": [
  {"username" : "SammyShark", "location" : "Indian Ocean"},
  {"username" : "JesseOctopus", "location" : "Pacific Ocean"},
  {"username" : "DrewSquid", "location" : "Atlantic Ocean"},
  {"username" : "JamieMantisShrimp", "location" : "Pacific Ocean"}
] }

JavaScript

JavaScript, or JS, is the programming language of HTML and the Web. Using JavaScript you can add interaction to web pages, download and format resources, and even create fully-featured apps that can run in browser like photo-editing, games, video-conferencing, diagrams etc.

JavaScript can be attached to HTML DOM elements directly, using specific element events, or separately, by using selectors. Here is an example of a script that will display the current date by pressing a button. Attached to an HTML element event:

<button 
  type="button" 
  onclick="document.getElementById('demo').innerHTML = Date()"
>
Click me to display Date and Time.
</button>
<p id="demo"></p>

In a separated script section:

<button id="myBtn" type="button">Click me to display Date and Time.</button>
<p id="demo"></p>
<script>
 document.getElementById("myBtn").addEventListener("click", displayDate);
 function displayDate()
 {
   document.getElementById('demo').innerHTML = Date()
 }
</script>

You can find useful DOM (document object model) function references, details and examples on the Moozila web page: https://developer.mozilla.org/en-US/docs/Web/API

let div = document.createElement("div")
let p = document.createElement("p")
div.append("Some text", p)
var el = document.querySelector("div.user-panel.main input[name='login']");
formElem.addEventListener('submit', (e) => {
  // on form submission, prevent default
  e.preventDefault();
 
  // construct a FormData object, which fires the formdata event
  new FormData(formElem);
});

As JavaScript applications become more and more complex, frameworks and libraries that help developers organize and code faster emerged, such as jQuery, Angular, ReactJS, VueJs, EmberJs, MeteorJs. There are also lots of specialized libraries like ThreeJs (WebGL for graphics and games), PlumbJs (diagram modelling), D3 (document and charts modelling), SoundJs (sounds) etc.

VueJS is a new, simple to use library, based on web components, that you can use to add interaction to your app.

Here is a small example that displays a list of todos with details on each task. You can also access it here: https://plnkr.co/edit/fgH90CirSOPHKp1KaVBP

Notice that the library file is loaded before usage: <script src=“https://cdn.jsdelivr.net/npm/vue”></script>. Also, you can define new HTML web components with custom functionality.

    <div id="app-1">
      <ol> <!-- ordered list -->
        <li v-for="todo in todos"> <!-- list item -->
          <a href="#" v-on:click="showDetails(todo)">{{ todo.text }}</a>
        </li>
      </ol>
 
      <h2 v-if="selectedItem" >Details:</h2>
      <todo-item inline-template :todo="selectedItem"> <!-- custom html component -->
        <div>
          <h3>{{ todo.text }}</h3>
          <ol>
            <li>ID: {{ todo.data.id }}</li>
            <li>Status: {{ todo.data.status }}</li>
          </ol>
        </div>
      </todo-item>
    </div>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script>
     var app = new Vue({
        el: '#app-1',
        data: {
          todos: [
            { text: 'Learn JavaScript', bla:'1', data: {'id': 1, 'status': 'done'} },
            { text: 'Learn Vue', data: {'id': 2, 'status': 'in progress'} },
            { text: 'Build something awesome', data: {'id': 3, 'status': 'pending'} }
          ],
          selectedItem: null
        },
        methods: {
          showDetails: function (todo) {
            this.selectedItem = todo
          }
        }
      })
 
      Vue.component('todo-item', {
        props: ['todo']
        data: {},
        methods: {}
      })
</script>

Usually, data in web apps is being fetched or transmitted asynchronous for a couple of reasons

  • minimize bandwidth consumption - only changed data is transmitted
  • minimize user impact - pages are not changed, only data parts
  • non-blocking processing - some tasks require longer processing times, so the user can still access other functions on the page while the request is still processing

This kind of web applications, that loads in a single interactive web page are called SPA - single page applications. The process of transmitting data asynchronous is usually addressed as AJAX - Asynchronous JavaScript + XML.

In order to make an ajax call using VueJS you will need another library: AXIOS.

Do not forget to include the library first

Usage example for a list of posts:

   axios.get(`http://jsonplaceholder.typicode.com/posts`)
    .then(response => {
      // JSON responses are automatically parsed.
      this.posts = response.data
    })
    .catch(e => {
      this.errors.push(e)
    })

W3schools.com has some tutorials with basic information, syntax and examples on HTML, CSS, JavaScript, XML and many others: https://www.w3schools.com/(https://www.w3schools.com/)

seh/laboratoare/02.txt · Last modified: 2022/03/18 18:04 by alexandru.gradinaru
CC Attribution-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0