Skip to main content

Web Applications

 

Sem 3 - Web Applications

Module 1 Context

Module 1

Context


Session Overview

Learning Objective:

After studying this module, students will be able to:

  1. Know what Client-Server Programming means.
  2. Understand the Hyper-Text Transfer Protocol
  3. Explain the Functions of a browser
  4. Understand the Definition of Rendering, Protocol End-Point
  5. Understand what Transitions Data means

Structure

1.1 Client-Server Programming

1.2 Hyper-Text Transfer Protocol

1.3 Functions of a browser

1.4 Functions of a web server

1.5 Summary

1.6 References

Context

Client-Server Programming

The Client-Server Programming model is a distributed computing architecture that separates information users (clients) from information providers (servers).

1.     A client is an application that needs her web page, IP address, etc. from a server. Clients can contact the server for this information at any time. Clients are information users.

2.     A server is an application that provides information or resources to clients. It must always be up and running, waiting for requests from clients.

Client applications communicate only with server applications and vice versa. Clients do not communicate directly with other clients.

How does the browser interact with the server?

A client must follow several steps to interact with a server.

  1. The user enters the URL (Uniform Resource Locator) of a website or file. The browser then asks for her DNS (DOMAIN NAME SYSTEM) servers.
  2. A DNS server lookup of the web server's address.
  3. The DNS server responds with the web server's IP address.
  4. The browser sends HTTP/HTTPS requests to the web server's IP (provided by the DNS server).
  5. The server will send the necessary files for the website.
  6. The browser then renders the file and displays the website. This rendering is done with the help of a DOM (Document Object Model) interpreter, a CSS interpreter, and a JS engine collectively known as the JIT or (just-in-time) compiler.

Advantages of the client-server model:

  1. A centralized system with all your data in one place.
  2. Cost-effective, low maintenance costs, and data recovery.
  3. Client and server capacities can be changed independently.

Drawbacks of the client-server model:

  1. Clients are prone to viruses, Trojan horses, and worms when they reside on or are uploaded to the server.
  2. The server is susceptible to denial of service (DOS) attacks.
  3. Data packets can be spoofed or altered in transit.
  4. Phishing or obtaining user login credentials and other helpful information is standard, as are Man in the Middle (MITM) attacks.

Hypertext Transfer Protocol

  1. HTTP stands for Hypertext Transfer Protocol.
  2. A protocol used to access data on the (www) World Wide Web.
  3. The HTTP protocol is used to transfer data in formats such as plain text, hypertext, audio, and video.
  4. It was named the Hypertext Transfer Protocol because of its efficiency allowing it to be used in hypertext environments with rapid jumps from one document to another.
  5. HTTP is similar to FTP as it transfers files from one host to another. However, HTTP is simpler than FTP because it uses only one connection, that is, there is no control connection for transferring files.
  6. HTTP is used to carry data in a MIME-like format.
  7. HTTP is similar to SMTP because data is transferred between client and server. HTTP differs from SMTP in how messages are sent from client to server and from server to client. SMTP messages are stored and forwarded, but HTTP messages are delivered immediately.

HTTP Features:

  1. Connectionless protocol: HTTP is a connectionless protocol. An HTTP client initiates a request and waits for a response from the server. When the server receives the request, it processes the request and returns a response to the HTTP client. The client then disconnects. The connection between client and server exists only for the current request and response.
  2. Media Independence: The HTTP protocol is media independent as it allows data to be sent as long as both the client and server know how to handle the data content. Both client and server must specify the content type in the MIME type header.
  3. Stateless: HTTP is a stateless protocol because both client and server know each other only for the duration of the current request. Due to this feature of the protocol, both client and server do not retain information between various requests for her web page.

HTTP Transactions

 

The diagram above shows an HTTP transaction between client and server. A client initiates a transaction by sending a request message to the server. Servers respond to request messages by sending response messages.

Messages

There are two types of HTTP messages: requests and responses. Both message types follow the same message format.

 

Request Message: A request message is sent by the client and consists of a request line, headers, and possibly a body.

 

Response Message: The server sends the client response message consisting of a status line, headers, and sometimes a body.

Functions of a Browser

Protocol End-Point

An API is a collection of protocols and tools that allow two applications to communicate. The two applications can be on the same machine (the current application, the web browser, communicates with the machine's operating system to display this article).

Using an API means that the interface is public, so programs can easily communicate with each other and behave in the way they expect (the whole interface forms a contract).

On the other hand, an endpoint is a URL that allows an API to access resources on a server, often through a RESTful API interface.

 

An interface (as above) can provide a set of endpoints that can be called at any time.

Rendering

It is responsible for displaying the requested content on the browser screen. Converts HTML, XML files, and images formatted using CSS. Generate a content layout and display it on the browser screen. However, other types of content can also be displayed using various plug-ins or extensions like this:

1.     Internet Explorer uses Trident

2.     Chrome and Opera 15+ use Blink

3.     Chrome (iPhone) & Safari use Web kit

4.     Firefox and other Mozilla browsers use Gecko

User Interaction

Mobile devices on the move, which can limit a user's attention, coupled with the form factors of these devices, make touch the primary means of interaction. This means that web developers should pay attention to interactivity when developing applications that run on top of mobile devices.

Addressing interaction accessibility requires a multi-layered approach. At the device level, accessibility support exposed by operating systems and assistive technologies has advanced significantly over the past few years. At the browser level, user agents must interact with assistive technologies to expose the semantics of web content. At the application level, web content developers must follow a set of accessibility principles to enable users with disabilities to interact with their content. Interestingly, due to the mobile limitations mentioned above, mobile users may experience similar barriers as people with disabilities, and similar solutions can be used to accommodate both angles.

Web Server Features:

1.     The client's browser splits the URL into diffs—the part splitting of addresses, pathnames, protocols, etc.

2.     DNS changes domain names to their corresponding IP addresses. A combination of numbers represents the site's actual address on the Internet.

3.     The browser decides which protocol to use. A protocol in general terms is a language for a client to communicate with a server. FTP and HTTP are some such protocols.

4.     Server sends her GET request to her web server to get the specified address. Make sure the specified address exists and find the required file. Run the appropriate script to exchange her cookies if necessary and return to your browser.

5.     The browser converts the data to HTML and displays the results to the user. If not found, send an error message to the browser and client.

Managing Requests on-Demand

On-Demand Management of Requests

Interactive applications can be developed to provide user credentials within the request sent to Oracle CRM on Demand, eliminating the need for explicit login requests. If the request is considered a stateless request, the Oracle CRM on Demand server checks to see if a session has already been established for that user. If a session is found, it will be reused for new requests. If no existing session for the user is found, a new session comes.

There is no logoff operation necessary for stateless web service requests. Sessions are eventually released due to timeouts or reused by session management routines for use by other users.

Enable support for stateless requests

To establish a session managed by the Oracle CRM on Demand server:

1.     Enterprises should enable support for stateless web services.

2.     WS-I login mechanisms must be used with the correct namespace and format described in the WS-I Basic Security Profile below.

http://www.ws-i.org/Profiles/BasicSecurityProfile-1.0.html#UsernameToken

⮚     Requests must specify the WSSE security namespace (http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd).

Requests that meet these norms qualify as stateless requests.

Oracle CRM On Demand Stateless Authentication Mechanism

Stateless login is available for all APIs. Stateless web service requests to the Web Services v1.0, Web Services v2.0, Services, and Data Loader APIs can be authenticated using:

⮚     Username and Password provided in SOAP security headers (using WSSE version 1.0 namespace)

⮚     Oracle CRM On Demand (SSO) token provided in SOAP security headers

⮚     SSO with SAML v1.1 or v2.0

For the Management Service API only, the following login options are supported for stateless web service requests.

⮚     Username and password provided in the SOAP security header (using the WSSE version 2.0 namespace)

⮚     Oracle CRM On Demand single sign-on (SSO) token provided in SOAP security headers

⮚     SSO with SAML v1.1

Login using Username and Password from the SOAP security header

The user's credentials can be provided because her User Name Token profile in WS-I Basic Security Profile Version 1.0 is supported. In this case, the SOAP header contains the element <wsse:UsernameToken>. This element has child elements that contain usernames and passwords.

Copy

<soap: Header>

            <wsse: Security soap:mustUnderstand="1">

                        <wsse: UsernameToken>

                                    <wsse: Username>USERNAME</wsse: Username>

                                    <wsse: Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-

                                    wss-username-token-profile-1.0#PasswordText">password</wsse:Password>

                        </wsse:UsernameToken>

            </wsse:Security>

</soap:Header>

Note: URL encoding of SSO tokens is not supported when provided in SOAP security headers. If the SSO token is URL-encoded, it must first be decoded before being provided in SOAP security headers.

SOAP requests will not be processed if the SSO token has expired. We recommend validating the SSO token before using it for login.

Login with Oracle CRM On Demand Single Sign-On Token in the SOAP Header

This login mechanism is a type of outbound SSO.

The client application supplies the SSO token in the <wsse:KeyIdentifier> element of the SOAP header:

Copy

<soap:Header>

            <wsse:Security>

                        <wsse:SecurityTokenReference>

                                    <wsse:KeyIdentifier ValueType="http://schemas.crmondemand.com/ws/2011/01/

                        secext#SSOTokenKeyIdentifier">$6$qx6pJ/czNwO1trwQRazQ26j4osNiQHMoqQSwRfpz/

                        6HX2D5cw=;$6$IjwKO/BBoBW5oiuqC7P/TxwOBX1LxVpExR9vp7P5J/

                        kixzGFWIjxHyRye7zy9Ld2g2vKp4W4jykxjbgF3KE8CFOGmD5g==</wsse:KeyIdentifier>

                        </wsse:SecurityTokenReference>

            </wsse:Security>

</soap:Header>

Note: URL encoding of SSO tokens is not supported when provided in SOAP security headers. If the SSO token is URL-encoded, it must first be decoded before being provided in SOAP security headers.

SOAP requests will not be processed if the SSO token has expired. We recommend validating the SSO token before using it for login.

SSO with SAML v1.1 or v2.0

This login mechanism is a sort of SSO inbound.

For SSO utilizing Security Assertion Markup Language (SAML), Oracle CRM On Demand only supports SAML Web Browser Profiles (Browser/Artifact Profile and Browser/POST Profile with Proprietary Token Method).

Support For Stateless Server Affinity

HTTP responses for stateless web service requests contain a cookie containing a session ID (JSESSIONID). This session ID is not used to identify a specific user session, but to identify the server within the Oracle CRM On Demand environment where the session was originally made. Subsequent requests can be sent to involve the session ID value, thus routing the request to the same server as the original request, preserving server affinity. However, the actual session cannot be used to serve requests unless the session is explicitly kept active.

Stateless Java Session Maintenance

An optional SOAP header parameter <SessionKeepAlive> allows the client to instruct the Oracle CRM on Demand server to keep a Java session open after processing a stateless request. By mentioning the optional <SessionKeepAlive> parameter with a value of true in the SOAP header of a stateless request, the Java session won't be logged off by Oracle CRM On Demand after requesting it is processed, and OM session pooling will continue to be used. Already used. Additionally, the JSESSIONID value returned in the SOAP response is used to authenticate future requests so that the same Java session can be reused without re-authenticating. This is mainly useful when SAML assertions are used for authentication. This eliminates multiple round trips to the specified provider when multiple requests are being prepared for the same person.

For stateless it asks where the <SessionKeepAlive> parameter is adjusted to false, is empty, or <SessionKeepAlive> does not exist, the Java session will be timed off by Oracle CRM On Demand after the request is processed.

Unlike stateful web service sessions, stateless requests do not have a logoff command. Java sessions are logged off by the Oracle CRM On Demand server after a period of inactivity. Attempting to use his JSESSIONID value for an expired Java session will return an error to the client for that thing. Stateless asks either a valid JSESSIONID value or valid user credentials (SSO token, SAML assertion, or username and password) for authentication. Requests that lack either a valid JSESSIONID value or valid user credentials will be rejected.

Here's an example of a SOAP header that includes a <SessionKeepAlive> element.

<soap:Header>

            <crmod:SessionKeepAlive xmlns:crmod="urn:crmondemand/ws">true

            </crmod:SessionKeepAlive>

            <wsse:Security>

                        <wsse:SecurityTokenReference>

                                    <wsse:KeyIdentifier ValueType="http://schemas.crmondemand.com/ws/2011/01/

                        secext#SSOTokenKeyIdentifier">$6$qx6pJ/rGFlDyJBy91C3Uxifc3oDEg/

                                    Sshtrsyj2z27RoHmO5M=;$6$jWkw/

                        HvIXoqw2FoHx10GDcYDc5WdZ2UV4v1G06AMEBNbWZv0JZinyJ1C4v7OHJR4OQVhZ4J3X+U/

                                    EvrP1c82LYHVOHA==</wsse:KeyIdentifier>

                        </wsse:SecurityTokenReference>

            </wsse:Security>

</soap:Header>

Using Stateful Web Service Requests

In instances where your application manages the creation and release of user sessions, the following applies:

⮚     The client should make login and logoff calls in code to manage the session.

⮚     The login procedure returns an HTTP cookie containing the session ID that should be used to make further requests.

⮚     A session remains working until the user explicitly logs out or the session logs out.

 HTTP-based is Web services session management and uses session IDs (also known as JSESSIONIDs) (contained in the HTTP session cookie) is used to uniquely identify a session established in Oracle CRM On Demand.

Oracle CRM On Demand Web Services allows session management by first creating a session using a login call and then referencing it in subsequent SOAP operations.

For Oracle SOAP sessions, after the session ID is created in the login request, it can be referenced by including the session ID in the cookie header line. If the session id is referenced as a cookie, then a cookie header line named JSESSIONID= her must appear in the request. In this case, the session ID is displayed in uppercase and the cookie value is exactly the session ID received from the login request.

Note: This is the recommended way to reference the session ID for several reasons. The Java Servlet specification recommends using cookies instead of URLs whenever possible. Most development environments and programming languages are more efficient with cookies than adding arguments to URLs. Additionally, the cookie container from the Oracle CRM On Demand login response can be copied into additional requests sent to Oracle CRM On Demand, making cookie implementation much easier. Joining the session ID as a parameter to the URL request line is against security standards and is not worth it.

When a login request is prepared, the session ID comes back as a cookie response to the requests. The responsibility is of the client for generating this session ID and utilizing it throughout the session. If the session logs out for any reason, the returned error reports that the session is invalid and the client should request a new session. No explicit logoff operation is required in this case.

Once the session ID is obtained, you can use the session ID to call the web service using HTTP POST.

⮚     To end a session by issuing a logoff request, use the JSESSIONID value to identify the session.

⮚     All requests must use HTTP Secure (HTTPS).

Oracle CRM On Demand Stateful Authentication Mechanism

Stateful login is available for the Web Services v1.0, Web Services v2.0, Services, and Data Loader APIs, but not the Admin Service API.

The following login options are assisted by Oracle CRM On Demand for stateful requests:

⮚     HTTP login (including UserName and Password in HTTP header)

⮚     UserName and Password provided in SOAP security headers (using WSSE Draft Namespace)

⮚     HTTP login (using Oracle CRM On Demand SSO token in header of HTTP

⮚     SSO using SAML v1.1

Login using HTTP GET (using username and password in HTTP headers)

You can use an HTTPS request to instantiate an Oracle CRM On Demand web service session and get a valid session ID. A client request login by sending an HTTP GET request to a URL like this:

https://secure ausomx[ENV].crmondemand.com/Services/Integration?command=login

[ENV] is the three-character identifier for your company's environment. If you do not know this value for your company, refer to the URL used to access the Oracle CRM On Demand UI.

Login input

The login mechanism differs depending on whether the login header contains URL encoding using the UTF-8 encoding system. This is required if your login credentials contain multibyte characters.

Input to the login is provided in URL parameters and HTTP headers as follows:

Two URL parameters:

⮚     a command with the value login

⮚     isEncoded. Used when the HTTP header is a URL encoded using UTF-8. If encoding is required, the value of this parameter must be Y or y. The value is N or n by default

Two HTTP headers, UserName and Password, should be set to values appropriate for your system. for example:

⮚     Username: johndoe@email.com

⮚     Password: mypass

HTTP headers can be clear text or URL-encoded.

Login Output

The login command returns:

⮚     Session cookie, JSESSIONID. The client should use this cookie when sending subsequent requests, including logoff requests.

⮚     Status code 200 if the session did not encounter any errors. This indicates that the request was successful.

Login using UserName and Password from the SOAP security header

The same login mechanism as for stateless requests is used, but the WSSE draft namespace (http://schemas.xmlsoap.org/ws/2002/04/secext or http://schemas.xmlsoap.org/ws/ 2002 /07/secext) rather WSSE version 1.0 namespace

The SOAP header comprises the element <wsse:UsernameToken>, which has child elements containing username and password.<soap:Header>

  <wsse:Security soap:mustUnderstand="1">

    <wsse:UsernameToken>

      <wsse:Username>USERNAME</wsse:Username>

      <wsse:Password Type="wsse:PasswordText">password</wsse:Password>

    </wsse:UsernameToken>

  </wsse:Security>

</soap:Header>

Login using Oracle CRM On Demand Single Sign-On (SSO) token in header of HTTP

This login mechanism is a means of outbound SSO.

A client instantiates an Oracle CRM On Demand web service session and acquires a valid session ID by sending an HTTP GET request to the next URL and specifying the SSO token:

where:

Copy

https://secure-ausomx[ENV].crmondemand.com/Services/

Integration?command=ssologin&odSsoToken=[SSOTOKEN]

Where:

⮚     [ENV] is a three-letter identifier for your company's environment. If you do not know this value for your company, refer to the URL used to access the Oracle CRM On Demand UI.

Note: Login parameter values are case sensitive.

⮚     [SSOTOKEN] is the SSO token string meant to authenticate the user to access data within Oracle CRM On Demand.

If the request for login is successful, the server will return a session ID in response.

The session won't be instantiated and the session ID won't be returned if the SSO token has expired. It is best way to validate the SSO token before using it for login,

SSO with SAML v1.1

For SSO make use of optional Security Assertion Markup Language (SAML), Oracle CRM On Demand only supports SAML web browser profiles (Browser/Artifact Profile and Browser/POST Profile). For information on how to log in and get a session ID to use for stateful requests, see

Logging out of a web service session

The client logs out by sending an HTTP POST or HTTP GET request to the URL. for example:

https://secure-ausomx[ENV]. crmondemand.com/Services/Integration?command=logoff;

Logoff input

The recommended practice is to include her JSESSIONID in the request as her cookie with the same name. There are no other URL parameters, no HTTP headers, and no HTTP body.

Logoff output

A status code of 200 is returned when the received request by the Oracle CRM On Demand server. It doesn’t guarantee that the logoff request has been processed and there may be a delay until session resources are freed up for use by new web service sessions.

Web Service Session Integration Request

A request of integration is an HTTPS request to call a web service to perform data creation, retrieve, update, and delete operations. Integration requests are made by HTTP POST commands to URLs such as:

https://secure-ausomx[ENV].crmondemand.com/Services/Integration/object

where object is the name of the related Oracle CRM On Demand object (record type). This Oracle CRM On Demand object is detected from the SOAP request contents

Integration request input. 

The JSESSIONID returned to the client upon login must be included in the request. The request should include the JSESSIONID as a cookie or URL parameter as follows:

https://secure-ausomx[ENV].crmondemand.com/Services/Integration/object;

jsessionid=xyZ12489w3482413

Web service inputs are provided as SOAP commands in the body of an HTTP POST request.

Output of the integration request.

Properties returned by the HTTP server are populated in the response headers and response body.

HTTP Response Table Properties

Property

Comments

HTTP Status

Status code returned in the response. If no value is provided, the response is given the value 200 (indicating success).

Content-Type

Content type returned in the response. If no value is provided, the response is given the value text/xml.

Comparing Stateless and Stateful Web Service Transactions

Stateful web services are typically used to query large numbers of records or perform bulk data operations such as uploading large amounts of data. Characteristics of stateful web service transactions include:

1.     Do not use OM session pooling (client applications must manage sessions for each request).

2.     Return a valid JSESSIONID value that will be used to authenticate subsequent requests.

3.     OM sessions are not shared, and details about previous requests can be saved. This is useful when paginating a query result set. The session is not used by other applications, as the session ID must be explicitly specified in the request.

4.     Session limit quota controls the number of sessions established for an enterprise.

In general, customers are encouraged to use stateless web services for several important reasons.

1.     Stateless web services offer more efficient resource utilization for most uses.

2.     Stateless web services do not affect session limit quotas.

3.     Using stateless web services can significantly reduce the complexity and cost of developing new integrations, as web service development is the customer's responsibility, and Oracle takes resource management. For stateful web services, this is your responsibility. For example, customers do not need to code logic to log off following stateless requests/responses.

4.     Stateless Web service requests achieve a higher level of concurrency because Oracle CRM On Demand code manages sessions.

5.     Additional error handling logic is the customer's responsibility and must be implemented correctly in the stateful web service.

Customers should ensure that stateless web services are used for short, interactive requests that require high concurrency.

Characteristics of stateless web service transactions include:

1.     Supports OM session pooling. Sessions are managed and pooled internally by the Oracle CRM On Demand server.

2.     Perform a logoff (invalidate the Java session) after processing each request unless the <SessionKeepAlive> parameter is set to true. A client application does not need to send a request to log off a session manually.

3.     Returns a JSESSIONID value that helps maintain server affinity (that is, send subsequent requests to the same Java server) if the request has the <SessionKeepAlive> parameter set to true.

The Management Service API requires the use of stateless web service transactions. A full login is performed for each request.

Database Interaction

The Data Integration Server is the Secure Agent service that runs data integration jobs such as mappings, tasks, and task flow instances.

When an advanced cluster handles data logic in advanced mode mappings, the Data Integration Server offloads advanced cluster subtasks to Elastic Server.

You can optimize the performance of Data Integration Server by setting some service properties. For example, you may want to change the network resiliency settings or the Secure Agent connection timeout period. You can change service properties when you edit the Secure Agent.

Application Logic

For application logic, keeping all application logic in one program promotes easier and bug-free development, making SPMD a popular choice among programmers.

A typical program structure includes the following steps:

Program initialization: This step typically involves deploying the program on a parallel platform and initializing the run-time system that allows multiple threads or processes to communicate and synchronize.

  1. Obtain a unique identifier: Identifiers are typically numbered starting from 0 and enumerate the threads or processes used. In some cases, identifiers are vectors instead of scalars (e.g., CUDA). The lifetime of the identifier follows the lifetime of the corresponding thread or process. Identifiers can be persistent (that is, they exist for the duration of the program), or they can be dynamically generated when needed.
  2. Program execution: Follow the execution path corresponding to the unique ID. This includes workload and data distribution, role diversification, etc.

Program Shutdown: You may shut down a thread or process and combine the partial results into a final answer.

Although the SPMD approach is convenient, it has its weaknesses. All application code and static (global) data are replicated on all nodes. This is both a merit and a disadvantage if you don't need these items.

State Management

The state is a property of each component that holds data, giving it personality and structure. This is important in establishing correct functionality and influencing interactivity so that users are greatly impacted. When you start writing your application, you should think about:

The application's architecture is in the way the components are isolated from each other. This idea has immediate benefits. Each component is responsible for providing the required data.

For example:

This component relies on the props passed to him to change the behavior of how data is ingested. Every time this prop changes, I get different data in the server call.

An easy way to visualize this idea is to know the basic principles of functional programming that react heavily influenced by.

The function should satisfy the following conditions:

1.     Pure (deterministic),

2.     Gives the same arguments and returns the same results,

3.     Must have no side effects. In other words, our component should be responsible for one primary responsibility, adjusting its output based on the props but fulfilling the reason it was created in the first place and not modifying the object passed as props.

The difficulty of any new web application is managing state, as it acquires complex structures that control not only the state of the server but also the interactivity of small atoms within components. A small disruption in the data flow in any of them can lead to unexpected or undesirable behavior.

Transition

A web transaction is a transactional interaction between a client (usually her web browser) and one or more databases as backends in a multi-tiered architecture. The middle tier of the architecture includes a web server that accepts client requests over HTTP.

Data

On the hardware side, a web server is a computer which stores web server software and website component files (HTML documents, images, CSS stylesheets, JavaScript files, etc.). A web server joins the Internet and supports the physical exchange of data with other web-connected device

Session Summary

Summary

This chapter has covered the HTML5 semantic markup elements that can be used in the proper layout of web pages. Unlike <div> elements, semantic elements are meant for specific purposes. Features covered in this article include <header>, <nav>, and <footer.

References

⮚     Mark Myers, 1st edition, 2014, A smart way to learn JavaScript, California, CreateSpace Independent Publishing Platform

⮚     Marijn Haverbeke, 3rd Edition, 2014, Eloquent Javascript, San Francisco, No Starch Press

⮚     Jon Duckett, 1st Edition, 2008, JavaScript and JQuery, New York, Wile

Module 2 Building Static, Single Page Applications

Module 2

Building Static, Single Page Applications

Session Overview

Learning Objective:

After studying this module, students will be able to:

  1. Know what Banking means.
  2. Understand the Current Banking Structure in India.
  3. Explain the Rights of the Banker types of accounts
  4. Understand the Definition of Banker and Customer
  5. Understand the Types of crossing

Structure

 2.1 Use of HTML

 2.2 Cascading Style Sheets

 2.3 JavaScript to build an elementary web application

 2.4 Browser-Server Communication using AJAX

 2.5 Summary

 2.6 References


Building Static, Single Page Applications

Use of HTML

HTML permits users to create and structure sections, headings, links, paragraphs, etc., on a website using various tags and elements. Almost anything you want to make a web page can be done using specific HTML code.

You may think HTML is complicated or say, "I forgot one symbol, and it ruined everything!" but HTML is very much like learning a new language. similar. But once you get the hang of it, you'll create web pages using HTML in no time. Ready to learn more? Read on.

How does HTML work?

100% of the time, I have visited websites that use HTML code. How do I know? This article consists of his HTML tags and elements in the backend.

This browser does not display the actual HTML tags but instead uses them to render specific content on the page so that visitors to the web page can view it. An average website typically contains several pages containing HTML code, such as a home page, a company page, a contact page, etc., each with its own HTML document.

HTML-element

The structure of an HTML element consists of a start tag, an end tag, and content between them. Think of these elements as the building blocks of your HTML page.

These tags are element names enclosed in angle brackets (in this case <p> for paragraphs).

The first tag is the opening tag, and the second is the closing tag. It should be written the same way, except the closing tag has a slash before the tag name. Any content between these two tags will be rendered as paragraphs on the website.

Common HTML tags

Many common HTML tags are commonly used to create web pages. Below are some commonly used tags used to build a web page from start to finish.

Document Type

The document type declaration helps the browser to display her web page correctly. Appears once at the top of the page.

All HTML documents begin with code that declares the document. This tag looks like this:

<!DOCTYPE html>

This may seem confusing, but basically, put it at the top of your document and keep building.

HTML-tag

As you can imagine, this tag is written as: <html>.

This element is sometimes called the root element because it wraps all the content for the entire page. This tag is below the document tag and must be closed with </html> at the end of the web page.

Title Tag

What's the title of the page you're creating? Whatever it is is wrapped in an <title> element and placed at the top of the tag.

<title>page title</title>

Body Tag

The <body> element contains all the content you want to display to your web page visitors. This includes text, images, videos, playable audio tracks, etc. Also, it should be closed with </body> at the end of the web page.

Heading Tag

This is written <h1> and defines a large heading on the page. You can have multiple heading tags, and each element has a corresponding number.

<h1>This is a heading.</h1>
<h2>This is also a heading.</h2>

Paragraph tag

A paragraph tag defines the text that is displayed as a paragraph using the element

<p>This is a paragraph about dogs.</p>
<p>This is another paragraph about dogs.</p>

Lists

The tag <ul> defines the text that is written as a numbered list <ol> or a bullet <li>.

Here's an example bullet point:

An example of a bulleted list would be:

<ul>
<li>Flour</li>
<li>Sugar</li>
<li>Butter</li>
</ul>

With this code, the web page displays the text as follows:

⮚     Flour

⮚     Sugar

⮚     Butter

Language Tag

The language of the document is defined with the "lang" tag. When the page is viewed in English, the tag looks like this:

The language of the document is defined by the “lang” tag. If your page will be displayed in English, the tag would be:

<html lang=”en”>

In this case, en stands for English. Other common language tags are es for Spanish, fr for French, it for Italian, he for Hebrew, and zh for Chinese.

Need your web page in another language? Check out this list of HTML language codes.

Images

The image element starts with the <img> tag, but other components must be included.

There are also source file (src), alt text (alt), and width and height tags. If you're using a Chicago Cubs photo that's 600 pixels wide and 450 pixels high, your image tag might look like this:

<img src=”Chicago_Cubs.jpg” alt=”Chicago-Cubs” style=”width:600px;height:450px”>

Links

There is a specific way to add a link in your text using HTML. To do so, use the element <a>, which is short for anchor.

In this case, let’s say my anchor text is G2 Learning Hub Link

There are specific ways to add links to text using HTML. To do this, we use the element <a>, short for an anchor.

In this case, let's say the anchor text is G2 Learning Hub.

<a>G2 Learning Hub</a>

Next, give the <a> element an href attribute with empty quotations:

<a href= “ “G2 Learning Hub</a>

Then, fill in the value of this attribute (in between the quotations) with the URL you will link to.

<a href= “https://learn.g2crowd.com/G2”>Learning Hub</a>

Basic HTML document

If we were to create a basic HTML document containing all the above elements and tags, it would look like this:

<!DOCTYPE html>

<html>
<html lang=”en”>

<title>Page Title</title>
<body>

<h1>This is your first header</h1>
<p>This is paragraph text that pertains to your first header.</p>

<h2>This is your second header</h2>
<p>This is paragraph text that pertains to your second header.</p>

<ul>
<li>List</li>
<li>List</li>
<li>List</li>
</ul>

<img src=”Image.jpg” alt=”Image-Alt-Text” style=”width:600px;height:450px”>

Click the link <a href= “https://learn.g2crowd.com/G2”>here</a> to be taken to the G2 Learning Hub.

</body>
</html>

HTML Pro

Using HTML to create web pages has many advantages. Some include:

1.     A widely used coding language with a vast community using it

2.     Runs on any web browser

3.     Use clean and consistent markup

4.     Completely free and open source

Disadvantages of HTML

Like all things that have strengths, HTML also has some weaknesses that need to be considered.

1.     Mainly used for static web pages

2.     All web pages must be created individually, even if they use the same elements and tags.

3.     Older browsers may not display newly developed tags

Cascading Style Sheets

"Cascading Style Sheets" (CSS) allow you to define styles, layout, and spacing separate from the content that needs to be styled. CSS information is usually contained in an external file. Other code, such as HTML pages, can reference layout information in CSS files. For example, an external file defines the fonts and colors used for a particular element.

CSS is defined as a standard. CSS 2.1 and CSS 3 versions are currently the most widely used.

CSS Selectors and Style Rules

CSS standards define selectors and style rules. The syntax is defined as:

selector { property: value; }

A selector can be either a predefined identifier (eg, H1), a class name (eg, .myclass), or an identifier (e.g., #myuniqueid).

CSS expects identifiers to be unique across all elements within a page (a window in this case), but classes can be assigned to multiple elements.

For example, the following CSS file defines the size and color of the "h1" tag

h1 {color: red; font-size: 48px; }

CSS pseudo-class

CSS pseudo-classes are used to decorate selector attributes. For example, when I select a visited link in HTML, it's styled differently.

a: Visited { color:red; }

HTML container by id and class

In HTML, you can define sections via the "div" container. These 'div' containers can be used to style different parts of your HTML document. For this purpose the div container can be identified via the id or class attributes.

The id and class produce the same output, but the id must be unique within the HTML document and the class attribute can be defined for multiple HTML elements within the page. CSS allows you to style these elements through special selectors.

You can also use other attributes. For example, the following defines a specific style for links that are visited or moused over. Identify if the link has already been visited or if the mouse is over the link and change the display of the link accordingly.

a: Visited {color:grey}

a:hover {text-decoraton:underline}

Contains CSS

CSS files can import other CSS files via the "@import" statement. This should be the first rule in any style sheet that uses the '@import' statement.

Margin and Padding

Margin

A block element can be thought of as a box that contains something. This box has a border to other elements and can affect the distance to other elements via the 'margin' and 'padding' settings.

Margin defines the distance outside other elements. It can be adjusted at top, right, bottom, and left values.

 

You can define the box margins separately or combine them in one statement.

body {

    margin-top10px;

    margin-right120px;

    margin-bottom20px;

    margin-left8px;

}

body {

    margin10px 120px 20px 8px;

}

Padding

Padding defines the inner distance of the element to the end of the box.

Positioning HTML elements using CSS

CSS allows elements to be fixed, relative, and absolute positioned. Relative is standard and modifies the distribution of different text containers based on available space.

Size definition

The most consistent way to define size is the unit 'em', which is relative to font-size. 1em is the same size as font size. 1em can be used to define the space between words (word-spacing) or letters (letter-spacing), or to define the line-height of an HTML element (line-height). text-indent allows you to define the intent of the first line of a paragraph. text-indent: -1em Places the first line slightly before the rest of the text.

Alignment and text conversion

You can use text-align to define how the content (not just the text) should be aligned. text-transform can be used to convert text to uppercase, lowercase or first letter uppercase

text-transform:uppercase;

text-transform:lowercase;

text-transform:capitalize;

text-align:left;

text-align:right;

text-align:center;

text-align:justify;

Versioning of CSS

The versioning of CSS files is not mandatory, but it could be very useful to force the browser to load a changed CSS file instead of using the CSS caching.

To achieve this just add ?version=1.1 at the end of the CSS file name when referencing to the file.

So instead of calling a CSS file like this:

https://www.vogella.com/css/companyfooter.css

you should replace it with

https://www.vogella.com/css/companyfooter.css?version=1.1

The wording after the '?' has no relevance and can be chosen freely. With this solution your CSS changes are immediately visible and you do not need to refresh your browser with CTRL F5 until you see them. Additionally, the name of the CSS file keeps the same which saves you a global search and replace.

Using the CSS editor in Eclipse

Eclipse has an integrated CSS editor that supports CSS2 by default. This feature must be enabled to see the new CSS3 properties.

You can activate by file, dynamic web project or static web project, but not other types of projects. It is also not available as a workspace-wide setting.

First, make sure you have the Eclipse web package installed. Otherwise, web content settings will not appear on the Properties page.

In Eclipse, Help → Install New Software … → Select Eclipse Release Software Site → Select Web Packages → Press Next >                         

 

After installation, do the following:

  1. Select a CSS file, dynamic web project, or static web project and right-click.
  2. Click Properties.
  3. Choosing web content settings
  4. Set the CSS profile value to "CSS3: Cascading Style Sheets, level 3".
  5. Click the OK button.                                 

 

This guide applies to Eclipse releases up to Mars. On Neon M6 the default CSS profile is set to CSS3.

JavaScript to build an elementary web application.

JavaScript for building basic web applications.

The front-end web app can be served by any web server, but it runs on the user's computing device (smartphone, tablet, or notebook) rather than a remote web server, as shown in the following architecture diagram.

 

Usually, but not always, front-end web apps are single-user applications and aren't shared with other users.

The minimal version of the JavaScript front-end data management app described in this tutorial contains only the minimum overall functionality required for a full app. It only handles one object type (Book) and supports four standard data management operations (create/read/update/delete), but uses CSS rules to style the user interface and, more importantly, It should be extended by adding parts. Of the app's overall features:

Part 2: Handle Responsive (HTML5) Constraint Validation

Part 3: Handling Enumerations

Part 4: Managing one-way associations that assign authors and publishers to books

Part 5: Managing bi-directional associations that assign books to authors and publishers

Part 6: Handling subtype (inheritance) relationships in class hierarchies

Background

This section briefly describes some elements of HTML and JavaScript. It is meant that the reader is familiar with basic programming concepts and has programming experience with PHP, Java, C#, etc.

HTML

Adopt a symbolic expression

HTML = HTML5 = XHTML5

When we say "HTML" or "HTML5" we really mean XHTML5. This is because we prefer the clean syntax of XML documents to the liberal and confusing HTML4-style syntax allowed by HTML5.

HTML = HTML5 = XHTML5

When you say "HTML" or "HTML5" you actually say you mean XHTML5. This is because we prefer the clean syntax of XML documents over the liberal and confusing HTML4-style syntax that HTML5 also allows.

JavaScript object

JavaScript objects are different from his traditional OO/UML objects. In particular, you don't need to instantiate the class. It can also have its own (instance-level) methods in the form of method slots to have method slots and (regular) property slots. Additionally, there may be key-value slots. So they may have three kinds of slots, whereas conventional objects (called "instance specs" in UML) only have property slots.

JavaScript objects can be used in different ways for different purposes. Here are five other use cases, or possible meanings, for JavaScript objects.

A set of property slots is called Records, for example:

JavaScript

var myRecord = { firstName:"Tom", lastName:"Smith", age:26}

r "hash map" or "associative array") is a set of key-value slots. For example, it supports looking up values based on keys such as:

JavaScript

var numeral2number = { "one":1, "two":2, "three":3}

This associates the number 1 with the key "1", 2 with "2", and so on. Keys don't have to be valid JavaScript identifiers but can be any kind of string (for example, they can contain whitespace).

Untyped objects do not instantiate classes. For example, you might have property and method slots like this:

JavaScript

var person1 = { 

  lastName: "Smith", 

  firstName: "Tom",

  getInitials: function () {

    return this.firstName.charAt(0) + this.lastName.charAt(0);

  } 

};

Namespaces can be defined as untyped objects referenced by global object variables. That name represents a namespace prefix. For example, the following object variable provides the main namespace for the application based on the Model-View-Controller (MVC) architectural paradigm. Here we have three sub-namespaces corresponding to the three parts of the MVC application.

introspection expression

JavaScript

var myApp = { model:{}, view:{}, ctrl:{} };

  1. typed object o that instantiates a class defined by a JavaScript constructor function C is created with the expression:

JavaScript

var o = new C(...)

The type/class of such a typed object can be retrieved with the introspective expression:

JavaScript

o.constructor.name  // returns "C"

Maps

Maps are processed with the help of a special loop that loops over all the keys of the map

Returns an array of all the keys of map a using the predefined function Object.keys(a) . for example,

JavaScript

var i=0, key="";

for (i=0; i < Object.keys( numeral2number).length; i++) {

  key = Object.keys( numeral2number)[i];

  alert('The numeral '+ key +' denotes the number '+ numeral2number[key]);

}

To add a new element to the map, simply create a new key-value entry like this:

numeral2number["thirty two"] = 32;

To remove an element from a map, you can use the predefined JavaScript remove operator as follows:

Remove numeric2number ["32"] .

Three types of data structures are supported by JavaScript

Three types of data structures (or complex data types) are :

1.     Records, which are special JS objects, as explained above

2.     A map, which is also a special JS object, as explained above

3.     An array list is a special JS object called an "array", but rather an array list (as defined in Java) because it is dynamic.

Class Definition and Instantiation

A class can be defined in two steps. First, define a constructor function that defines the properties of the class and assigns values for the parameters of the constructor.

Then define the instance-level methods of your class as function slots in the constructor function's prototype object property.

JavaScript

Person.prototype.getInitials = function () {

  return this.firstName.charAt(0) + this.lastName.charAt(0);

}

Finally, class-level ("static") methods can be defined as function slots of the constructor function, as in:

JavaScript

Person.checkName = function (n) {

  ...

}

An instance of a class is created by applying the new operator to the constructor function:

JavaScript

var pers1 = new Person("Tom","Smith");

The method getInitials is invoked on the Person object pers1 by using the 'dot notation':

JavaScript

alert("The initials of the person are: " + pers1.getInitials());

Coding the App

The purpose of the sample app is to manage information about books. That is, we are dealing with one object type, Book, as shown in the following figure.

 

What would such an information management application need? There are four typical use cases that an application should support.

  1. Create: Enter data for the workbook that you want to add to your collection of managed workbooks.
  2. Read: View a list of all the books in your managed book collection.
  3. Update workbook data.
  4. Delete a book record.

HTML forms can be used to provide user interface technology for web applications to enter data using the keyboard and computer screen.

Maintaining a collection of data objects requires a storage technology that allows data objects to be persisted in a permanent record on a secondary storage device such as a hard disk or solid state disk. Modern web browsers offer two such technologies. The simpler one is called Local Storage and the more powerful one is called IndexDB. The minimal sample app uses local storage.

Step 1 - The first step is to set up the application's folder structure. Choose the name of your app, such as "Public Library", and the corresponding (possibly abbreviated) name of your application folder, such as "publicLibrary". Then create this folder on your computer's disk and create a subfolder "src" for your JavaScript source code files. In this folder create subfolders 'model', 'view' and 'ctrl' following the model-view-controller paradigm of software application architecture. Finally, create an index.html file for your app's start page, as described below. So end up with the following folder structure:

public library

  src

    ctrl

    model

    view

  index.html

The app's start page loads the Book.js model class file and uses the menu to select one of the CRUD data management operations performed by the corresponding page (such as createBook.html) or help to test data. Provides a menu for creating Clear all data in the procedure Book.createTestData() or with Book.clearData():

The minimal app's start page index.html

HTML

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

  <meta charset="UTF-8" />

  <title>Minimal JS front-end App Example</title>

  <script src="src/model/Book.js"></script>

</head>

<body>

  <h1>Public Library</h1>

  <h2>An Example of a Minimal JavaScript front-end App</h2>

  <p>This app supports the following operations:</p>

  <menu>

    <li><a href="listBooks.html"><button type="button">List all books</button></a></li>

    <li><a href="createBook.html"><button type="button">Add a new book</button></a></li>

    <li><a href="updateBook.html"><button type="button">Update a book</button></a></li>

    <li><a href="deleteBook.html"><button type="button">Delete a book</button></a></li>

    <li><button type="button" onclick="Book.clearData()">Clear database</button></li>

    <li><button type="button" onclick="Book.createTestData()">Create test data</button></li>

  </menu>

</body>

</html>

Step 2 - Write the model code

The second step is to write the code for your model class in a specific JavaScript file. In the information design model above there is only one class representing the object type Book. So in the folder src/model first create a file Book.js with the following code

function Book( slots) {

  this.isbn = slots.isbn;

  this.title = slots.title;

  this.year = slots.year;

};

The model class Book is encoded as a JavaScript constructor function with a single slot parameter. This is assumed to be a record object with properties isbn, title, and year representing the values of the ISBN, title, and year attributes of class Book. Therefore, the constructor function assigns the slot property values to the corresponding attributes whenever a new object is created as an instance of this class.

In addition to defining the model class in the form of a constructor function, the Book.js file also defines:

  1. A class-level property Book.instances that represents the collection of all Book instances managed by the application in the form of a map.
  2. Class level method Book.loadAll to load all Book instances managed from the persistent data store.
  3. Class level method Book.saveAll to save all managed Book instances to persistent data stores.
  4. Class level method Book.add to create and save a new Book record.
  5. Class-level method Book.update to update an existing Book record.
  6. Class-level method Book.destroy to delete a Book instance.
  7. Class level method Book.createTestData to create some example book records to use as test data.
  8. Class level method Book.clearData to clear the book datastore

1. Represents a collection of all Book instances

Define and initialize a class-level property Book.instances in the following way to represent the collection of all Book instances managed by the application:

Book. instances = {};

So initially the book collection is empty. In fact, it is defined as an empty object (the value). The structure of such maps can be visualized in the form of lookup tables as shown in Table 1.

Table 1: A map representing a collection of books

Key

Value

006251587X

{ isbn:"006251587X," title:"Weaving the Web", year:2000 }

0465026567

{ isbn:"0465026567," title:"Gödel, Escher, Bach", year:1999 }

0465030793

{ isbn:"0465030793," title:"I Am A Strange Loop", year:2008 }

 

Note that the values in this map are simple record objects corresponding to table rows. Therefore, they can also be represented in a simple table, as shown in Table 2.

Table 2: A collection of book objects shown in as a table

ISBN

Title

Year

006251587X

Weaving the Web

2000

0465026567

Gödel, Escher, Bach

1999

0465030793

I Am A Strange Loop

2008

2. Load all Book instances

For persistent data storage, use Local Storage, an HTML5 JavaScript API supported by modern web browsers. Loading a book record from local storage requires three steps:

Use assignment to get the book table stored as a big string with key "bookTable" from local storage.\

  1. Retrieving the book table that has been stored as a large string with the key "bookTable" from Local Storage with the help of the assignment:

bookTableString = localStorage["bookTable"];

This search is performed on line 5 of the program listing below.

  1. Converting the book table string into a corresponding map bookTable with book rows as elements, with the help of the built-in function JSON.parse:

bookTable = JSON.parse( bookTableString);

This conversion, performed on line 11 of the program listing below, is called deserialization

Converts each row of bookTable (representing an untyped record object) to the corresponding object of type Book stored as an element in the map Book.instances. Book class:

JavaScript

Book.convertRow2Obj = function (bookRow) {

  var book = new Book( bookRow);

  return book;

};

Here is the full code of the procedure:

Book.loadAll = function () {

  var i=0, key="", keys=[], bookTableString="", bookTable={}; 

  try {

    if (localStorage["bookTable"]) {

      bookTableString = localStorage["bookTable"];

    }

  } catch (e) {

    alert("Error when reading from Local Storage\n" + e);

  }

  if (bookTableString) {

    bookTable = JSON.parse( bookTableString);

    keys = Object.keys( bookTable);

    console.log( keys.length +" books loaded.");

    for (i=0; i < keys.length; i++) {

      key = keys[i];

      Book.instances[key] = Book.convertRow2Obj( bookTable[key]);

    }

  }

};

Notice that since an input operation like localStorage["bookTable"] may fail, we perform it in a try-catch block, where we can follow up with an error message whenever the input operation fails.

3. Save all Book instances

Such objects from the Book.instances group in primary memory to local storage in secondary memory requires two steps:

Converting the map Book.instances into a string with the help of the predefined JavaScript function JSON.stringify:

bookTableString = JSON.stringify( Book.instances);

This conversion is called serialization.

  1. Writing the resulting string as the value of the key "bookTable" to Local Storage:

localStorage["bookTable"] = bookTableString;

These two steps are performed in line 5 and in line 6 of the following program listing:

JavaScript

Book.saveAll = function () {

  var bookTableString="", error=false,

      nmrOfBooks = Object.keys( Book.instances).length; 

  try {

    bookTableString = JSON.stringify( Book.instances);

    localStorage["bookTable"] = bookTableString;

  } catch (e) {

    alert("Error when writing to Local Storage\n" + e);

    error = true;

  }

  if (!error) console.log( nmrOfBooks + " books saved.");

};

4. Create a new Book instance

The Book.add procedure creates a new Book instance and adds it to the Book.instances collection.

JavaScript

Book.add = function (slots) {

  var book = new Book( slots);

  Book.instances[slots.isbn] = book;

  console.log("Book " + slots.isbn + " created!");

};

5 Updating an existing Book instance

To update an existing Book instance, first get it from Book.instances and reassign the attribute whose value has changed

Book.update = function (slots) {

  var book = Book.instances[slots.isbn];

  var year = parseInt( slots.year);

  if (book.title !== slots.title) { book.title = slots.title;}

  if (book.year !== year) { book.year = year;}

  console.log("Book " + slots.isbn + " modified!");

};

For numeric attributes (such as years), you must ensure that the value of the corresponding input parameter (y) (typically obtained from user input via an HTML form) is changed from string to number. Please be careful. Use one of the two type conversion functions parseInt and parseFloat.

6. Deleting existing Book instances

The Book instance is removed from the Book.instances collection. First we test if the map has an element with the specified key (line 2), then we apply the JavaScript built-in delete operator. Remove a slot from an object. Or , in this case the elements of the map:

JavaScript

Book.destroy = function (isbn) {

  if (Book.instances[isbn]) {

    console.log("Book " + isbn + " deleted");

    delete Book.instances[isbn];

  } else {

    console.log("There is no book with ISBN " + isbn + " in the database!");

  }

};

7. Create Test Data

To be able to test our code, we will create some test data and store it in a local storage database. You can use the following steps for this:

The next step is to erase all data from your local storageBook.createTestData = function () {

  Book.instances["006251587X"] = new Book({isbn:"006251587X", title:"Weaving the Web", year:2000});

  Book.instances["0465026567"] = new Book({isbn:"0465026567", title:"Gödel, Escher, Bach", year:1999});

  Book.instances["0465030793"] = new Book({isbn:"0465030793", title:"I Am A Strange Loop", year:2008});

  Book.saveAll();

};

8. Erase all data

The next step is to erase all data from your local storage.

Book.clearData = function () {

  if (confirm("Do you really want to delete all book data?")) {

    localStorage["bookTable"] = "{}";

  }

};

Step 3 - Initialize the Application

Initialize the application by defining a namespace and an MVC sub namespace. Namespaces are a key concept in software engineering, and many programming languages that include Java and PHP, provide native support for namespaces to help group related code and avoid naming conflicts. JavaScript has no specific support for namespaces, so we use a special object for this purpose (sometimes called a "namespace object"). First, define the app's root namespace (object). Then define three sub-namespaces, one for each of her three parts of application code (model, view, controller). For our sample app, this can be done with the following code

JavaScript

var pl = { model:{}, view:{}, ctrl:{} };

Here the main namespace is defined as pl which stands for "Public Library," and the three sub-namespaces model, view and ctrl, are initially empty objects. Place this code in a separate file, initialize.js, in the ctrl folder since such a namespace definition belongs to the controller part of the application code.

Step 4 - Implement the List Object Use Case

This use case addresses the "read" of the four basic data management use cases Create, Read, Update, and Delete (CRUD).

The user interface for this use case is given by the following HTML page, which contains an HTML table for displaying book objects. In our sample app, this page will be named listBooks.html (in the main folder publicLibrary).

nd contains the following HTML code:

HTML

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

  <meta charset="UTF-8" />

  <title>Minimal JS front-end App Example</title>

  <script src="src/ctrl/initialize.js"></script>

  <script src="src/model/Book.js"></script>

  <script src="src/view/listBooks.js"></script>

  <script>

   window.addEventListener( "load", pl.view.listBooks.setupUserInterface);

  </script>

</head>

<body>

  <h1>Public Library: List all books</h1>

  <table id="books">

    <thead><tr><th>ISBN</th><th>Title</th><th>Year</th></tr></thead>

    <tbody></tbody>

  </table>

  <nav><a href="index.html">Back to main menu</a></nav>

</body>

</html>

Note that this HTML file loads his 3 Javascript files: controller file src/ctrl/initialize.js, model file src/model/Book.js and view file src/view/listBooks.js. The first two files contain the code to initialize the app and the code for the model class Book described above. The third file represents his UI code for the "list of books" operation and is currently under development. In fact, this operation only requires a step to setup the data management context and his UI called setupUserInterface

JavaScript

 pl.view.listBooks = {

  setupUserInterface: function () {

    var tableBodyEl = document.querySelector("table#books>tbody");

    var i=0, keys=[], key="", row={};

    // load all book objects

    Book.loadAll();

    keys = Object.keys( Book.instances);

    // for each book, create a table row with a cell for each attribute

    for (i=0; i < keys.length; i++) {

      key = keys[i];

      row = tableBodyEl.insertRow();

      row.insertCell(-1).textContent = Book.instances[key].isbn;     

      row.insertCell(-1).textContent = Book.instances[key].title; 

      row.insertCell(-1).textContent = Book.instances[key].year;

    }

  }

};

The simple logic of this procedure includes following :

  1. Read the collection of all objects from the persistent data store (line 6).
  2. Display each object as a row in an HTML table on the screen (in a loop starting at line 9).

More specifically, the setupUserInterface procedure first calls Book.loadAll() to create a book object from the corresponding rows retrieved from local storage, then loops through all the key-value slots of the map Book.instances Create a view table with . Represents a book object. Each step in this loop creates a new row in the table body element using JavaScript DOM operation insertRow() , then creates three cells in this row using DOM operation insertCell() . The first is the book object's isbn property value, the second and third are its title and year property values. Both insertRow and insertCell must be called with the -1 argument to ensure that the new element is added to the list of rows and cells.

Step 5 - Implement the create object use case

For data management operations that involve user input, such as Create Object operations, an HTML page with an HTML form is required as the user interface. The form has a form field for each attribute of the Book class. In our sample app, this page is called createBook.html (in the app folder publicLibrary) and contains the following HTML code:

HTML

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

  <meta charset="UTF-8" />

  <title>Minimal JS front-end App Example</title>   

  <script src="src/ctrl/initialize.js"></script>

  <script src="src/model/Book.js"></script>

  <script src="src/view/createBook.js"></script>

  <script>

   window.addEventListener("load", pl.view.createBook.setupUserInterface);

  </script>

</head>

<body>

  <h1>Public Library: Create a new book record</h1>

  <form id="Book">

    <p><label>ISBN: <input name="isbn" /></label></p>

    <p><label>Title: <input name="title" /></label></p>

    <p><label>Year: <input name="year" /></label></p>

    <p><button type="button" name="commit">Save</button></p>

  </form>

  <nav><a href="index.html">Back to main menu</a></nav>

</body>

Procedures:

  1. Setup user interface retrieves a collection of all objects from the persistent data store and sets an event handler (handle save button click event) on the save button to save user input data and handle click button events.
  2. Field and save this data by calling the Book. save row procedure

Step 6 - Implement the object update use case

Again, we have a user interface page (updateBook.html) and a view code file (src/view/updateBook.js). Her HTML form in her UI for the "Update Object" operation has a select field to select the book to update and a form field for each attribute of the Book class. However, the Standard Identifier Attribute (ISBN) form field is read-only.

Change the standard identifier of an existing object to low.

Step 7 - Implement the Delete Object Use Case

For the "delete object" use case, the UI form only has a select field to select the book to delete.

Run the app and get the code

Browser-Server Communication using AJAX.

When Ajax communication is enabled, Ajax is used wherever possible when posting data from the browser to the server and to return Html output to the browser. Only the minimum data representing and changed controls is sent back to the client on each occasion – this is referred to as an Incremental Page Refresh for the remainder of this document. This technique provides significant benefits when the same web page is redisplayed to the user: the transition is much smoother and the response time is faster. Smoother transitions provide an enhanced user interface which is more like a native application.

When Ajax communication is disabled, a traditional HTTP POST request is sent with each user request and the entire page is refreshed on each occasion – this is referred to as a Full-Page Refresh for the remainder of this document.

There are many occasions where a Full-Page Refresh is required e.g. The application logic routes control to another page or another form. When these situations are detected, the initial Ajax request is processed by the server, then the browser is requested to issue a Full-Page Refresh request.

Back Button Considerations

The browser’s history cache (which the browser uses for back button and forward button requests) is not updated when an Incremental Page Refresh is used. Therefore, when Ajax is used successfully without the need for a Full-Page Refresh, the user will not have the ability to return to the page before the request was made. Instead, the back button will return the user to the page resulting from the last Full-Page Refresh. This situation will usually apply when the same page is redisplayed.

Use of jsps with Ajax

When JSP are HTML files are configured on a page, either as top, left, right or bottom jsps or in an Include Control, these are refreshed according to the setting of the static flag for each JSP or for the control: when a JSP is marked as static, it is not refreshed when that page is redisplayed e.g. As a result of an event such as a button click or field immediate validation. Jsps are always refreshed when moving to a different page. The static setting for a JSP can be configured at template level in the Form Default Properties or at form level in the Form Properties, or using the properties of an Include Control.

Session Summary

Summary

⮚     Javascript is a lightweight programming language used for small applications.

⮚     Javascript is an object-based programming language made in C++.

⮚     Javascript can be executed either on a client-side browser or on a server-side browser.

⮚     JavaScript’s can be downloaded and run and carry a threat of virus attack. Security of Javascript depends upon the security of the Java language. The process of executing the Javascript code after isolating it from the operating system is called ‗sandbox ‘model.

References

  1. Mark Myers, 1st edition, 2014, A smart way to learn JavaScript, California, CreateSpace Independent Publishing Platform
  2. Marijn Haverbeke, 3rd Edition, 2014, Eloquent Javascript, San Francisco, No Starch Press
  3. Jon Duckett, 1st Edition, 2008, JavaScript and JQuery, New York, Wiley

Module 3 Server-Side Programming

Module 3

Server-Side Programming


Session Overview

Learning Objective:

After studying this module, students will be able to:

  1. Know what Server-side Programming Requirements and Frameworks means.
  2. Understand the Authentication/Log-in system.
  3. Explain the Implementing Business Logic on the web server
  4. Understand the Definition Database Access from the web server
  5. Understand the Managing Sessions and Transactions

Structure

 3.1 Server-side Programming Requirements and Frameworks

 3.2 Authentication/Log-in

 3.3 Implementing Business Logic on the web server

 3.4 Database Access from the web server

 3.5 Managing Sessions and Transactions

 3.6 Summary

 3.7 References


Server-Side Programming

Server-side Programming Requirements and Frameworks

Server-side Frameworks are the structures that contain pre-written code (classes and functions) to which we can add our own code to solve the problem. It can also be said to use programmer code because the framework is within the programmer’s control. We can use the framework by calling its methods, inheriting from it, and providing “call-backs,” listeners, or other Observer pattern implementations.

Web application frameworks are software frameworks that make writing, maintaining, and scaling web applications easier. They offer tools and frameworks that make basic web development jobs easier, popular server-side frameworks such as routing URLs to appropriate handlers, communicating with databases, supporting sessions and user permission, formatting output (e.g. HTML, JSON, XML), and frame creation.

The Hypertext Transfer Protocol is used by web browsers to communicate with web servers (HTTP). An HTTP request is sent from the browser to the target server when you click a link on a web page, submit a form, or conduct a search. When designing online applications, there are a variety of server-side technologies to consider. Microsoft’s ASP.NET is the most popular, with server-side code written in languages like C# and VB.NET and using the same Framework. Permanent storage, such as databases or files, is interacted with using server-side processing. The server will also process user input and render pages for the client.

A framework isn’t required: it’s “only” one of the tools available to assist you in developing better and faster! Better, since a framework ensures that you’re creating an application that follows all business requirements, is a well-structured server side framework, and is both maintainable and upgradeable. Faster because it enables developers to save time by reusing existing code.

An operating system supports a software framework natively. A programme created for the Android Application Framework, for example, will operate on an Android smartphone without the need to install any additional files. Some apps, on the other hand, require a specialised framework to run.

Authentication/Log-in

Authentication/Login is the process of verifying the identity of a user or information. It  is the procedure of verifying the identity of the user when that user logs in to a computer system.

The two primary types of authentications are:

⮚      Stateless Authentication

⮚      Stateful Authentication

Stateful authentication: using session IDs and cookies.

Authentication flow:

⮚     User submits login credentials, i.e. username and password.

⮚     This is validated by the server against the database.

⮚     The server then creates a temporary user session.

⮚     The server issues her a cookie containing the session ID.

⮚     User/client can send her cookie with each request.

⮚     The server authenticates it against the session store and grants access.

⮚     When the user logs out, the server destroys the session and clears the cookie.

Stateful authentication features: All user sessions are stored server-side (stateful).

⮚     In-memory, or file system (less common).

⮚     Cache (Redis or Memcached)

⮚     In a database (commonly used include Postgres and MongoDB)

Each user is identified by a session ID.

  1. Opaque reference:

⮚     Third parties cannot extract the data.

⮚     Only the publisher (server) can revert the data.

  1. Stored in cookies:

⮚     Sign with a secret. Also, the cookie is often protected with a flag so the client cannot tamper with her cookie. The process of cryptographically signing her cookie on the server side is also done for the purpose of avoiding/detecting tampering with her cookie on the client side, so the server side can guarantee that her cookie has not been tampered with.

Stateless authentication: using tokens, JWT, OAuth, etc.

Authentication flow using token:

⮚     User submits login credentials, i.e. username and password.

⮚     The server validates the credentials against the database.

⮚     The server then generates a temporary token and embeds the user her data.

⮚     The server responds with the token (either in the body or headers).

⮚     Users store the token in client storage [local storage or session storage].

⮚     User sends a token with each request.

⮚     The server validates the token and grants access.

⮚     When the user logs out, the token is cleared from client storage.

Characteristics of a Stateless Authentication System:

⮚     Tokens are not stored on the server side, only on the client. (stateless)

⮚     Signed with a tamper-proof secret.

⮚     Server-verified and trusted.

⮚     Tokens can be opaque or self-contained.

⮚     Tokens can carry all necessary user data in the payload.

⮚     This reduces database lookups, but exposes the data to her XSS attacks.

⮚     Tokens are typically sent under an Authorization header.

⮚     Clients are issued both an access token and a refresh token so they can refresh the tokens when they are nearing expiration.

⮚     Refresh tokens can be used to refresh access tokens.

⮚     Used in SPA web apps, web APIs, and even mobile apps.

Implementing Business Logic on the web server

In the application server itself, nothing. In the APPLICATION being developed, the business logic is the parts of the application that implement - business logic. The parts that perform the financial calculations in a finance application are the business logic. The parts that calculate where a request should be routed in a distributed application based on the input parameters are the business logic. In short, it is all of the application which is not related to “other things”. What are these other things? General request/response handling. Security. Data Validation not related to business logic. Typically, business logic is written in a service class. In a STANDARD/bare layer MVC application, the business logic goes in the model. Best practice is to segregate a data model, often a view model, a data access layer (to interact with the actual data source) and the business logic layer. By breaking these components up, the application becomes more robust and easier to test and troubleshoot.

Database Access from the web server

Create a Data Source Name

To connect to a database using an ASP page, you must first create a Data Source Name (DSN) on your Web server for the various databases you want to connect to. To do this, use one of the following methods:

  1. To create a DSN for your database program (such as Microsoft Access):
  2. Log on to the web server computer as an administrator.
  3. Click Start, point to Settings, and click the Control Panel.
  4. Double-click Administrative Tools, and then double-click Data Sources (ODBC).
  5. Click the System DSN tab and click Add.
  6. Select the required database driver (for example,
  7. Select Microsoft Access Driver (*.mdb) and click Finish.
  8. In the Data Source Name box, enter the name you will use to refer to this DSN in your ASP code. For example, Northwind.
  9. Click Select.
  10. In the Select Database dialog box, browse to and select the desired database.
  11. Northwind.mdb.

NOTE: If your database is not on a web server, click Network, and then click Browse. Locate the shared network folder containing the database and click OK. Click Finish and select the desired database.

  1. Click OK.
  2. Click Details.
  3. If you want login credentials to be automatically provided to the database when using this DSN, enter them in the Login Name and Password boxes. Click OK.
  4. Click OK, then click OK.

For database servers

To create a DSN for SQL Server:

1.     Log in to the web server computer as an administrator.

2.     Click Start, point to Settings, and click the Control Panel.

3.     Double-click Administrative Tools, and then double-click Data Sources (ODBC).

4.     Click the System DSN tab and click Add.

5.     Select SQL Server and click Finish.

6.     In the Name box, enter the name you will use to refer to this DSN in your ASP code. For example, Northwind.

7.     In the Description box, optionally enter a description for the DSN.

8.     In the Server list, do one of the following:

⮚      Select the name of the SQL Server on your network.

⮚      Select (Local) if the desired SQL Server is running on the web server computer.

⮚      Enter a name (alias) for a server that does not appear in the server list.

9.     Click Next.

10.  Under How SQL Server verifies the authenticity of login IDs, click the required authentication method. For example, use Windows NT authentication using network login IDs. Click Next.

11.  Select the Change the default database to checkbox, select the required database (eg Northwind) from the list, and click Next.

12.  Click Finish, click OK, and click OK.

Create ASP script to connect to database using DSN

In your ASP script, use ActiveX Data Objects (ADO) Database Access Components (DAC) to create a connection to the database.

⮚      Use the Connection ADO object to create a connection to the database.

⮚      Retrieve, update, and delete existing database records using the record set object.

Example

The following example shows how to use ASP scripting to connect to the Microsoft Access NorthWind sample database.

 Step 1: Create a DSN

Make a DSN to the Microsoft Access Northwind.mdb sample database by following the steps in the About Database Programs section of this article.
 

Step 2: Create an ASP Page

  1. Start Notepad.
  2. In Notepad, type the following code:

<HTML>
<HEAD><TITLE>ASP Database Connection</TITLE></HEAD>
<BODY BGCOLOR=white>
<H1>Northwind Database Contacts</H1>
<%
Dim Connect, selectSQL, RecSet
Set Connect = CreateObject ("ADODB.Connection")
Connect.Open "DSN=Northwind"
selectSQL = "SELECT * FROM Customers"
Set RecSet = Connect.Execute (selectSQL)
If NOT RecSet.EOF
THEN
DO UNTIL RecSet.EOF
Response.Write RecSet("Companyname") & ", " & RecSet("Contactname") & "<BR><BR>"
RecSet.MoveNext
Loop
End If
RecSet.Close
Connect.Close
Set RecSet = Nothing
Set Connect = Nothing
%>
</BODY></HTML>

  1. On the File menu, click Save As.
  2. In the Save As dialog box, navigate to C:\Inetpub\wwwroot in the Save in the list, select All files in the Save as type list, and Enter in

Enter database. Asp in the File name box and click Save.

  1. Exit Notepad.

Step 3: Test the ASP Page

1.     Click Start and click Run.

2.     Enter http://localhost/database.asp in the Name box and click OK. A Web page displaying the customer list of the North Wind sample database appears in your browser window.

Troubleshooting

If you are unable to connect to the database using ASP web pages, make sure you have sufficient permissions to access the database.

  1. Ensure the DSN uses an account with sufficient privileges to access the database.
  2. If you are trying to connect to SQL Server over the Network, make sure you use a domain account as the anonymous IIS account.
  3. If you are trying to connect to a Microsoft Access database, ensure your IIS account has written permissions to the folder where the database is stored. This is so that temporary files can be created when users access the database.

Managing Sessions and Transactions;

A session provides all methods to access the database and is at the same time a cache holding all data being used in a transaction. If you load objects using a query or if you save an object or just attach it to the session, then the object will be added to the Persistence Context of the session.

Persistence Context

Objects are continuously added to the persistence context of the session until you close the session. If you call session get and the object already exists in the persistence context, then the object will not be retrieved from the database but from the context. Therefore, the session is called a first level cache.

There is one caveat with this behaviour. If you query a lot of objects, you might run out of memory if your session becomes too large. We will handle strategies for this caveat in the chapter performance.

All database access including read and write access should happen inside a transaction.

A session is not thread safe and should only be used by one thread. Usually this is guaranteed by the Session Factory.

To conclude: A session is used by one user in his thread to write and read data inside of transactions.

Typical Session usage. 

Session session = HibernateSessionFactoryUtil.openSession();

session.beginTransaction();

// do something

session.save(myObject);

session.getTransaction().commit();

session.beginTransaction();

// do something else

List result = session.createQuery(

   "from Order o where o.invoice.number like '2%' ").list();

session.getTransaction().commit();

session.close();

Write behind behaviour

The session is not sending the SQL statements directly to the database, if you call session.save. There are a number of reasons for this behaviour:

⮚      keep write locks in the database as short as possible

⮚      more efficient sending of SQL statements

⮚      allow optimisations like JDBC batching

By the default configuration the SQL statements are flushed when

⮚      tx.commit is called

⮚      a query is executed for an Entity which has a insert/update/delete statement in the queue

⮚      session.flush is called explicitly

This is the reason why you might see no SQL statements when calling session.save.

There is an exception to this rule as well. If you use select or identity as id generator, it is required that hibernate sends the insert immediately


Session Summary

Summary

In this we'll take a high-level look at server-side programming and answer questions like "What is it?" "How is it different from client-side programming?" and "Why is it so useful?" Read this article to see how server-side coding enhances his website.

Most large websites use server-side code to dynamically display various data as needed. These data are often retrieved from a database on the server and passed to the client for display via code (such as HTML or JavaScript).

References

  1. Mark Myers, 1st edition, 2014, A smart way to learn JavaScript, California, CreateSpace Independent Publishing Platform
  2. Marijn Haverbeke, 3rd Edition, 2014, Eloquent Javascript, San Francisco, No Starch Press
  3. Jon Duckett, 1st Edition, 2008, JavaScript and JQuery, New York, Wiley

Module 4 Deploying a Web Application

Session Overview

Learning Objective:

After studying this module, students will be able to:

  1. Know what Configuring a web server means.
  2. Understand Scalability and basic security.
  3. Explain the Deploying a 2-tier architecture and a 3-tier architecture

Structure

4.1 Configuring a web server

4.2 Scalability and basic security

4.3 Deploying a 2-tier architecture and a 3-tier architecture

4.4 Summary

4.5 References


Deploying a web application

Web server configuration

Materials And Resources

In developing the lessons and activities, we made some assumptions about the hardware and software available in the classroom for teachers accessing the LETSNet website. We assume that teachers using Internet-based lessons and activities have a computer with the necessary hardware components (mouse, keyboard, and monitor) and a World Wide Web browser. The sections below specify "special" hardware or software requirements (in addition to those listed above) for lessons or activities, and the level of Internet access required to conduct the activity.

Special Hardware Requirements: None.

Special Software Requirements: None.

Internet Access: Fast connection (28,800 BPS or better).

Activity content

The tasks below will guide you through the process of setting up your own web server. The process described is not necessarily complete, but is provided as a guide to the steps required to successfully set up a web server. Links to software (networking, HTTP, CGI, etc.) are provided so you can assemble your own toolkit for web server products. Commercial software is also available for PC and Macintosh platforms, such as Netscape's Communication Server (available free to educational institutions) and Microsoft's Internet Information Server (see Internet Resources below).

Step 1 –

Computer: A web server requires a dedicated computer connected directly to the Internet, usually via an Ethernet network (LAN/WAN). One can run a web server on a low end computer (80386 based PC or 68040 Macintosh), but if you want your server to be responsive to his web surfer, you'll need to use a more powerful computer (like Pentium or PowerPC) . based Macintosh). A web server needs a fast, large hard drive and a lot of RAM (16 MB or more).

Step 2 –

Operating System Software: The operating systems that can support the web server are Windows/NT, Windows/95, MacOS, Unix, and Linux. Of these, most existing web servers run on Windows/NT, MacOS (on PowerMacs), or Unix. PC/DOS-based version of Unix is Linux.

Step 3 –

Network Software: Every Internet computer needs TCP/IP and web servers are no exception. As mentioned above, the computer must be directly connected to the Internet, so proper Ethernet software may be required.

Step 4 –

Web Server Software: There are various web server programs available for different platforms, from Unix to DOS machines. For Macintosh, a popular web server is StarNine's WebStar (see Internet Resources below). For Windows/NT platforms, both Microsoft and Netscape offer powerful Web server programs free of charge to educational institutions (see Internet Resources below). Download or purchase web server software and install it on your computer according to the instructions provided.

Step 5 –

Configure the web server: When you install the web server, you will be prompted for basic settings (default directory or folder, whether visitors can browse the contents of the directory or folder, where to save log files, etc.). increase. Depending on the installation of web software , you may need to configure the software according to the instructions that come with it.

Step 6 –

Web Server Management: With more and more users accessing web servers, monitor log files to see what files users are reading, identify peak access times, and may need to consider upgrading. Adding more RAM and disk space to your Web server computer to enhance the performance. Also check for bottlenecks such as TCP/IP software. For example, Apple's Open Transport 1.1 has been modified to support faster TCP/IP access when installed on a web server.

Step 7 –

Get More Information About Working with Web Servers: For more information about finding, downloading, installing, and working with web servers, see the following Internet resources. For example, Web66 has details on setting up Macintosh and Windows/95 web servers, and many other useful resources are available.

Scalability and basic security

Let us now consider the web application scenario to build a scalable solution. It is always good to think ahead, but not beyond the foreseeable future.

Maintainability and scalability

Anticipating some growth ever we make must be maintainable. Otherwise, there would be huge work in every release version. Therefore, proper separation of concerns has to be practiced throughout the entire project.

 

Layering

The diagram represents the layering of content for two database instances. Load balancing is used either to use both cases or to use one at a time as fail safe mode.

Connecting Components

It is always to have separate components and have messages passed for communication. This would add the communication overhead, yet this can scale very well and be maintained easily too. The following diagram represents the organization of components in implementation. This is different from the above diagram. This does not demonstrate the actual flow of information but the separation of components in technical terms.

 

Placement of components in the actual implementation

NGINX is usually used (in the old days we used Apache; Microsoft has IIS and Passenger for Python and Ruby). Containers usually run-on different ports, but usually expose only port 80 (for security reasons) so that no one can connect to the database from the outside.

Sample flow

⮚      When a user requests www.mydomain.com, this request will be routed to her HTML static content.

⮚      Static content is loaded in the user's browser. This is primarily an Angular or ReactJS application. This is because unlike the old days when you used PHP, JSP, JADE, Twig, or Blade to build your templates, you no longer do that. This allowed us to wire up our application with APIs and request controllers.

Once the content is loaded, all other work is typically done by calling a web API. For example, a login request looks like

"method": "POST",
"body": {
    "username": "anuradha",
    "password": "password1234"
},
"headers": {
    "content-type": "application-json"
}

⮚      These requests are sent to the URL www.mydomain.com/login as post requests. NGINX sends these to the authorization server. If successful, you will receive a token for your web application. These are known as JWTs (JSON Web Tokens). These will be used later to authenticate the user.

⮚      All future requests will be sent to www.mydomain.com/api/somepath. NGINX routes /API/ requests to the API container. The JWT should be sent as a header in the format authorization: bearer <token>. Obviously, you should use an https connection to prevent someone from hijacking your token.

Why container

Containers are lightweight virtualization layers, most of which run a Linux kernel. They are used because they can be started and stopped more quickly than virtual machines. Also, they consume less resources than VMs.

Containers also allow secure deployment of content. For example, a vendor can ship a Docker image for an API after configuring it for a specific environment without submitting the codebase.

Deploying 2-tier and 3-tier architectures

There are endless combinations of options when building a new application. One of the most important choices is whether your application uses 2-tier or 3-tier architecture. The choice comes down to separating business logic and data logic into separate tiers. For web applications, the decision is yours.

However, if you are building a standalone application, you should choose.

The primary choice is whether the client application accesses the database directly or indirectly by executing code on an intermediate application server. There are many considerations when choosing architecture, including:

⮚      Safety

⮚      Cost

⮚      Ease of development

⮚      Ease of maintenance

⮚      Performance

⮚      Introduction

Of course, each consideration's relative importance depends on the application's intended use and environment.

 

The table given below has the two-tier architecture and has some compelling advantages. While these points are debatable and some come down to subjective preference, there is no dispute that two-tier applications are easier to build, cheaper to deploy, and easier to deploy. .

However, two-tier applications often perform poorly when the Internet is involved. Network speed can have a significant impact on application performance because a two-tier architecture requires more data to be transferred to the client.

Traditionally, network speed and performance have been the limiting factors, but with Nitro Accelerator installed on database servers and clients, two-tier applications can now run at speeds comparable to local area networks, making this an option worth considering as an important option.

Table 1: Design Considerations for Multi-tier Application Architecture

Design Consideration

Description

Winner

Security

The topic of security is a tough one because arguments can be made either way for 2 vs. 3-tiers. In my experience, the 3-tier architecture has the potential for better security, but if great care isn’t taken during development it frequently ends up less secure. With a 2-tier approach, the application authenticates to and communicates directly to the database, which simplifies the attack surface area and is one less boundary to be concerned about. Depending on the details of the application server, there could be, for example, many complex REST APIs that could each have their own attack weaknesses. This one topic could be covered in a book, so I’m simply calling this one in favor of 2-tier even though direct access to the data sounds unsafe.

Even though 3-tier has the potential of greater security, I’m calling this one in favor of 2-tier.

Cost

2-tier applications are generally easier to build and because of their lower complexity are less expensive all around.

2-Tier

Ease of maintenance

Although part of cost consideration, ease of maintenance is worth analyzing separately. Keeping the client up to date in a 2-tier architecture can be a trouble point that is not an issue with most 3-tier designs. However, in a 3-tiered architecture, keeping the application tier up to date is much more difficult in the long run. For example, sometimes security patches required to keep the application tier secure are not compatible with your code and require you to make code changes, which can be extensive.

2-Tier

Performance

Performance in a 2-tiered architecture is more sensitive to the hardware the client is running on, as well as the speed of the network connection.

Generally, 3-Tier

Deployment

In a 3-tiered architecture, typically users point their browsers to the application server to start using the application. However, the setup of that environment can be considerably more complex than setting up a database for the users to connect to and making the installer for the client available.

3-tier for end-users; 2-tier from an initial configuration and setup perspective



Comments

Popular Posts

PyThon - Notes

PyThon - Code