18CSC311J WEB DESIGN AND DEVELOPMENT UNIT-4

sivakumarmcs 22 views 82 slides May 29, 2024
Slide 1
Slide 1 of 82
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82

About This Presentation

18CSC311J WEB DESIGN AND DEVELOPMENT,
UNIT-4,
SRM UNIVERSITY,
VI SEMESTER,
REGULATION 2018


Slide Content

18CSC311J WEB DESIGN AND DEVELOPMENT 2023-24 EVEN SEMESTER REGULATION 2018 Prepared by Dr.M.Sivakumar AP,NWC, SRMIST, KTR DEPARTMENT OF NETWORKING AND COMMUNICATIONS Prepared by Dr.M.Sivakumar 1

UNIT IV

Unit IV Contents Introduction to spring boot, Devops using spring boot, spring boot web hosting Node JS introduction and installation - Building serverless application using node JS Node JS installation , Node JS module - Node package Manager Express framework for web application development Creating Web server File System Event node JS, Express JS Data Base Connectivity Node JS web hosting

Session-1

Introduction to spring boot Spring Boot is an open-source Java-based framework used to create standalone, production-grade Spring-based applications . It simplifies the process of setting up and configuring Spring applications by providing a convention-over-configuration approach. It aims to get developers up and running with Spring applications quickly and with minimal configuration overhead.

Introduction to spring boot The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications - on any kind of deployment platform.

Features of Spring Boot Create stand-alone Spring applications Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files) Provide opinionated 'starter' dependencies to simplify your build configuration Automatically configure Spring and 3rd party libraries whenever possible Provide production-ready features such as metrics, health checks, and externalized configuration Absolutely no code generation and no requirement for XML configuration

Features of Spring Boot Auto-configuration : Spring Boot can automatically configure your Spring application based on the dependencies you have added. This greatly reduces the amount of boilerplate configuration code you need to write. Standalone : Spring Boot applications can be run as standalone JAR files. They include an embedded servlet container (such as Tomcat, Jetty, or Undertow), so you don't need to deploy your application to an external server. Spring Boot Starter : Spring Boot provides a set of "starter" dependencies that streamline the setup of various Spring technologies (e.g., Spring MVC, Spring Data, Spring Security). These starters include all the necessary dependencies and configuration to get started quickly. Actuator : Spring Boot Actuator provides production-ready features to help you monitor and manage your application. It includes endpoints for health checks, metrics, environment information, and more. Spring Boot CLI : Spring Boot offers a Command Line Interface (CLI) that allows you to quickly prototype and develop Spring Boot applications using Groovy scripts. Spring Boot DevTools : DevTools provide additional development-time features, such as automatic application restarts, live reloading of changes, and remote debugging support.

Devops using spring boot DevOps practices can be effectively integrated into Spring Boot applications to streamline the development, deployment, and maintenance processes.

Spring boot web hosting Hosting a Spring Boot application involves deploying it to a server where it can be accessed by users over the internet. There are several options for hosting Spring Boot applications, ranging from traditional server hosting to cloud-based solutions.

Spring boot web hosting Self-Managed Servers You can deploy Spring Boot applications to self-managed servers, such as virtual private servers (VPS) or dedicated servers. Providers like Amazon Web Services (AWS), Google Cloud Platform (GCP), Microsoft Azure, DigitalOcean , and Linode offer VPS hosting options where you can deploy your Spring Boot application on a virtual server instance. With self-managed servers, you have full control over the server environment and can customize it to your requirements.

Spring boot web hosting Platform as a Service ( PaaS ) PaaS providers, such as Heroku , Pivotal Web Services (PWS), and IBM Cloud Foundry, offer platforms for deploying and managing Spring Boot applications without worrying about infrastructure management. PaaS platforms typically provide features like automatic scaling, load balancing, monitoring, and logging, simplifying the deployment and management of Spring Boot applications.

Spring boot web hosting Containerization You can containerize your Spring Boot application using Docker and deploy it to container orchestration platforms like Kubernetes . Containerization provides portability and scalability, allowing you to run your Spring Boot application consistently across different environments. Cloud providers like AWS (Amazon ECS, EKS), Google Cloud (Google Kubernetes Engine), and Azure (Azure Kubernetes Service) offer managed Kubernetes services for deploying containerized applications.

Spring boot web hosting Serverless Computing Serverless platforms, such as AWS Lambda, Google Cloud Functions, and Azure Functions, allow you to deploy individual functions or endpoints of your Spring Boot application without managing servers. With serverless computing, you pay only for the resources consumed by your application, and the platform handles scalability and infrastructure management automatically.

Spring boot web hosting Static Site Hosting If your Spring Boot application includes static content (HTML, CSS, JavaScript), you can host it on static site hosting platforms like Netlify , Vercel , or GitHub Pages. These platforms are optimized for serving static content and provide features like CDN (Content Delivery Network) distribution, SSL/TLS encryption, and continuous deployment from Git repositories.

Session-2

Node JS introduction Node.js is an open-source, cross-platform JavaScript runtime environment that allows developers to run JavaScript code outside of a web browser. It is built on Chrome's V8 JavaScript engine, which is known for its speed and performance A Node.js app runs in a single process, without creating a new thread for every request.

Node JS introduction When Node.js performs an I/O operation, like reading from the network, accessing a database or the filesystem , instead of blocking the thread and wasting CPU cycles waiting, Node.js will resume the operations when the response comes back. This allows Node.js to handle thousands of concurrent connections with a single server without introducing the burden of managing thread concurrency, which could be a significant source of bugs.

Example // Import the built-in http module const http = require('http'); // Define the hostname and port number const hostname = '127.0.0.1'; const port = 3000; // Create a new HTTP server const server = http.createServer (( req , res) => { // Set the HTTP status code and Content-Type header res.statusCode = 200; res.setHeader ('Content-Type', 'text/plain'); // Send a response to the client res.end ('Hello, World!\n'); }); // Start the server and listen on the specified port and hostname server.listen (port, hostname, () => { // Display a message in the console when the server starts console.log(`Server running at http://${hostname}:${port}/`); });

What Can Node.js Do? Node.js can generate dynamic page content Node.js can create, open, read, write, delete, and close files on the server Node.js can collect form data Node.js can add, delete, modify data in your database

What is a Node.js File? Node.js files contain tasks that will be executed on certain events A typical event is someone trying to access a port on the server Node.js files must be initiated on the server before having any effect Node.js files have extension ". js "

Node JS installation Download Node.js Installer : Go to the official Node.js website at https://nodejs.org/ . On the homepage, you'll see two versions available for download: LTS (Long Term Support) and Current. For most users, it's recommended to download the LTS version, as it is more stable and suitable for production environments. Click on the "LTS" download button. Run the Installer : Once the installer executable (. msi file) is downloaded, locate it in your downloads folder or the location you saved it to. Double-click the downloaded file to start the installation process.

Node JS installation Accept License Agreement : In the Node.js Setup Wizard, you'll be presented with the license agreement. Read through it, and if you agree, check the "I accept the terms in the License Agreement" checkbox, then click on the "Next" button. Choose Installation Options : You'll be prompted to choose the installation options. By default, Node.js and npm (Node Package Manager) are selected for installation. You can also choose additional features like automatically installing necessary tools for native modules, or adding Node.js to the PATH environment variable. Once you've selected your desired options, click on the "Next" button.

Node JS installation Choose Installation Location : Select the destination folder where you want to install Node.js. By default, it's installed in "C:\Program Files\ nodejs ", but you can choose a different location if needed. After selecting the installation location, click on the "Next" button. Start Installation : Finally, click on the "Install" button to start the installation process. The installer will copy the necessary files and set up Node.js and npm on your system. Complete Installation : Once the installation is complete, you'll see a "Completed" message. You can then click on the "Finish" button to close the installer.

Node JS installation Verify Installation To verify that Node.js and npm are installed correctly, open a command prompt (search for " cmd " in the Windows search bar and open Command Prompt) and type the following commands: node –v This command will display the installed version of Node.js.

Building serverless application using node JS // Import the built-in http module const http = require('http'); // Create a new HTTP server const server = http.createServer (( req , res) => { // Set the HTTP status code and Content-Type header res.statusCode = 200; res.setHeader ('Content-Type', 'text/plain'); // Send a response to the client res.end ('Hello, World!\n'); }); // Define the hostname and port number const hostname = '127.0.0.1'; const port = 3000; // Start the server and listen on the specified port and hostname server.listen (port, hostname, () => { // Display a message in the console when the server starts console.log(`Server running at http://${hostname}:${port}/`); }); nodejsexample.js

Session-3

Express framework for web application development var express = require('express'); var app = express(); app.get ('/', function ( req , res) { res.send ('Hello World'); }) var server = app.listen (5000, function () { console.log("Express App running at http://127.0.0.1:5000/"); }) Express1.js

Express framework for web application development Express1.js

Express framework Example2 Express2.js <html> <body> <form action = "/ process_get " method = "GET"> First Name: <input type = "text" name = " first_name "> < br > Last Name: <input type = "text" name = " last_name "> < br > <input type = "submit" value = "Submit"> </form> </body> </html> index.html var express = require('express'); var app = express(); var path = require('path'); app.use ( express.static ('public')); app.get ('/', function ( req , res) { res.sendFile ( path.join (__ dirname,"index.html ")); }) app.get ('/ process_get ', function ( req , res) { // Prepare output in JSON format response = { first_name:req.query.first_name , last_name:req.query.last_name }; console.log(response); res.end ( JSON.stringify (response)); }) var server = app.listen (5000, function () { console.log("Express App running at http://127.0.0.1:5000/"); })

Express framework Example2

Express framework Example2

Express framework Example2

Session-4

Node JS module Node.js modules are reusable blocks of code that encapsulate specific functionality and can be easily imported and used in other parts of a Node.js application. Modules help in organizing code, improving maintainability, and facilitating code reuse. Two types of moduels Core modules Thirty-party modules

Types of modules Core Modules These are built-in modules that come pre-installed with Node.js and provide essential functionalities for working with files, networks, streams, etc. Core modules are accessed using their module names without needing to install them separately. Third-Party Modules These are external modules developed by the Node.js community or other developers. They are available through the Node Package Manager (NPM) registry and can be installed using the npm install command. Third-party modules extend the functionality of Node.js by providing additional features and utilities.

Core Modules Examples http Provides HTTP server and client functionality for building web servers and making HTTP requests. fs (File System) Provides file I/O operations such as reading and writing files, creating and deleting directories, etc. Path Provides utilities for working with file and directory paths. Events Provides an event-driven architecture for working with events in Node.js. Util Provides utility functions for common tasks such as formatting strings, inspecting objects, etc.

Third-Party Modules Examples Express A popular web application framework for building web servers and APIs. Mongoose An ORM (Object-Relational Mapping) library for MongoDB , providing a higher-level abstraction for interacting with MongoDB databases. Lodash A utility library that provides functions for manipulating arrays, objects, strings, etc. Axios A promise-based HTTP client for making HTTP requests from Node.js. Socket.io A library for real-time bidirectional event-based communication between web clients and servers.

How to use a module in a Node.js application? To use a module in a Node.js application, you typically import it using the require() function and assign it to a variable. // Core module example const fs = require(' fs' ); // Third-party module example const express = require('express');

Node JS module Create Your Own Modules Syntax exports.module_name =function() { //code } Example exports.myDateTime  = function () { return Date(); };

Node JS module Include Your Own Module var http = require('http'); var dt = require('./ myfirstmodule '); http.createServer (function ( req , res) { res.writeHead (200, {'Content-Type': 'text/html'}); res.write ("<h1>The date and time are currently: " + dt.myDateTime ()+"</h1>"); res.end (); }).listen(3000);

Node package Manager Node Package Manager ( npm ) is the default package manager for Node.js, allowing developers to discover, share, and use reusable code packages, known as npm packages or modules. npm provides a vast ecosystem of open-source libraries and tools that help streamline the development process by allowing developers to easily integrate existing solutions into their projects.

npm features and functionalities Package Installation npm allows developers to install packages from the npm registry using simple commands. For example, npm install package-name installs a package locally in the current project, while npm install -g package-name installs a package globally, making it accessible from any project. Dependency Management npm simplifies dependency management by automatically managing dependencies for each project based on the package.json file. When you install a package, npm installs its dependencies recursively, ensuring that all required packages are available. Version Management npm allows developers to specify package versions using semantic versioning ( semver ) in the package.json file. This ensures that projects use compatible package versions and facilitates version control.

npm features and functionalities Project Initialization npm provides the npm init command to initialize a new Node.js project. This command generates a package.json file that contains project metadata and dependencies, making it easy to manage project configuration. Scripts npm allows developers to define custom scripts in the package.json file. These scripts can be executed using the npm run command, providing a convenient way to automate common tasks such as building, testing, and deploying projects. Publishing Packages npm enables developers to publish their own packages to the npm registry, making them available for others to use. Publishing packages allows developers to share code with the community and contribute to the ecosystem.

npm features and functionalities Scoped Packages npm supports scoped packages, which allow developers to group related packages under a common namespace. Scoped packages are useful for organizing code within organizations and preventing naming conflicts with other packages. Security npm includes built-in security features to help protect against malicious packages and vulnerabilities. For example, npm audits packages for known security vulnerabilities and provides recommendations for remediation.

Session-5

Creating Web server

node-static module The node-static module is a Node.js library that serves static files over HTTP. It's commonly used to serve HTML, CSS, JavaScript, images, and other static assets for web applications. E:\> npm install node-static

Serve Static Resources using Node-static Module nodeserver.js var http = require('http'); var nStatic = require('node-static'); const port = 3000; var fileServer = new nStatic.Server ('./public'); const server= http.createServer (function ( req , res) { fileServer.serve ( req , res); }); server.listen (port, () => console.log(`Server listening at port ${port}...`));

Serve Static Resources using Express.js Create folder “public” Create a node.js server file as follows const express = require('express'); const app = express(); const port = 4000; // URL '/' (root) maps to 'public' directory app.use ( express.static ('public')); // URL '/static' also maps to 'public' directory app.use ('/static', express.static ('public')); app.listen (port, () => console.log(`Server listening at port ${port}...`)); Create few static files inside “public” folder Run the server e:\pgm>node nodeserver3.js

Handling form data index.html <!DOCTYPE html> <html> <body> <form action = "/" method = "post"> First Name: <input type = "text" name = " fname "> < br > Last Name: <input type = "text" name = " lname "> < br > <button type = "submit">Register</button> </form> </body> </html>

Handling form data nodepostdata.js const express = require('express'); const app = express(); app.use ( express.json ()); app.use ( express.urlencoded ({extended: true})); app.get ("/", ( req , res) => { res.sendFile (__ dirname + "/index.html"); }); app.post("/", ( req , res) => { const firstname = req.body.fname ; const lastname = req.body.lname ; console.log("First Name: " + firstname ); console.log("Last Name: " + lastname ); res.send ("Data received"); }); app.listen (3000);

Session-6

File System To handle file operations like creating, reading, deleting, etc., Node.js provides an inbuilt module called FS (File System).  To use this File System module, use the require() method: var fs = require(' fs' ); Common use for File System module: Open Files Read Files Write Files Append Files Close Files Delete Files

File System Open Files fs.open () Read Files fs.readFile () fs.readFileSync () fs.read () Write Files fs.writeFile () Append Files fs.appendFile () fs.appendFileSync () Close Files fs.close () Delete Files fs.unlink ()

Open Files var fs = require(" fs "); // Asynchronous - Opening File console.log("opening file!"); fs.open ('input.txt', 'r+', function(err, fd ) { if (err) { return console.error (err); } console.log("File open successfully"); });

Read Files Synchronous and Asynchronous approach Synchronous approach:  They are called  blocking functions  as it waits for each operation to complete, only after that, it executes the next operation, hence blocking the next command from execution i.e. a command will not be executed until & unless the query has finished executing to get all the result from previous commands. Asynchronous approach:  They are called  non-blocking functions  as it never waits for each operation to complete, rather it executes all operations in the first go itself.

Synchronous Read input.txt This is my text file readfile.js var fs = require(" fs "); // Synchronous read var data = fs. readFileSync ('input.txt'); console.log("Synchronous read: " + data.toString ());

Asynchronous Read input.txt This is my text file readfile.js var fs = require(" fs "); // Asynchronous read fs.readFile ('input.txt', function (err, data) { if (err) { return console.error (err); } console.log("Asynchronous read: " + data.toString ()); });

Reading a file using fs.read () var fs = require(" fs "); var buf = new Buffer.alloc (2048); console.log("opening an existing file"); fs.open ('input.txt', 'r+', function(err, fd ) { if (err) { return console.error (err); } console.log("File opened successfully!"); console.log("Reading the file"); fs.read ( fd , buf , 0, buf.length , 0, function(err, bytes) { if (err) { console.log(err); } console.log(bytes + " bytes read"); // Print only read bytes to avoid junk. if(bytes > 0) { console.log("File Contents:"+ buf.slice (0, bytes). toString ()); } }); });

Write a File var fs = require(" fs "); console.log("Writing into existing file"); fs.writeFile ('input.txt', 'This is new content', function(err) { if (err) { return console.error (err); } console.log("Data written successfully!"); console.log("Let's read newly written data"); fs.readFile ('input.txt', function (err, data) { if (err) { return console.error (err); } console.log("Asynchronous read: " + data.toString ()); }); });

Appending a File fs.appendFile ( filepath , data, options, callback); (OR) fs.appendFileSync ( filepath , data, options); filepath :  It is a String that specifies the file path. data:  It is mandatory and it contains the data that you append to the file. options:  It is an optional parameter that specifies the encoding/mode/flag. Callback:  Function is mandatory and is called when appending data to file is completed.

Appending a File var fs = require(' fs' ); var data = "\ nThis is new content appended"; // Append data to file fs.appendFile ('input.txt', data, 'utf8',function(err) { if (err) throw err; console.log("Data is appended to file successfully.") });

Appending a File Synchronously var fs = require(' fs' ); var data = "\ nThis is synchronously appended content"; // Append data to file fs.appendFileSync ('input.txt', data, 'utf8'); console.log("Data is appended to file successfully.")

Closing a file var fs = require(" fs "); // Open the file for reading const fd = fs.openSync ('input.txt', 'r'); // Read the file contents const data = fs.readFileSync ( fd , 'utf8'); // Close the opened file. fs. close ( fd , function(err) { if (err) { console.log(err); } console.log("File closed successfully."); });

Deleting a file var fs = require(" fs "); console.log("deleting an existing file"); fs. unlink ('input.txt', function(err) { if (err) { return console.error (err); } console.log("File deleted successfully!"); });

Session-7

Event node JS Events are fundamental in Node.js for building applications that handle asynchronous operations efficiently. They allow you to decouple different parts of your code and make it easier to manage asynchronous flows.

Steps for creating and handling events in node JS Require the events module, which provides the EventEmitter class Create an instance of EventEmitter Define an event handler function Assign the event handler to the event using the on method Emit the event using the emit method

Example //1. Require the events module const EventEmitter = require('events'); // 2. Create an instance of EventEmitter const myEmitter = new EventEmitter (); // 3. Define an event handler const myEventHandler = () => { console.log('Event1 occurred!'); }; // 4. Assign the event handler1 to the ' myEvent ' event myEmitter.on (' myEvent ', myEventHandler ); // 5. Emit the ' myEvent ' event myEmitter.emit (' myEvent ');

Session-8

Express.js Express is a fast, assertive, essential and moderate web framework of Node.js Back end web application framework for building RESTful APIs with Node.js

Features of Express framework It can be used to design single-page, multi-page and hybrid web applications. It allows to setup middlewares to respond to HTTP Requests. It defines a routing table which is used to perform different actions based on HTTP method and URL. It allows to dynamically render HTML Pages based on passing arguments to templates.

Example-1 express1.js var express = require('express'); var app = express(); // Getting the path request and sending the response with text app.get ('/', function ( req , res) { res.send ('Welcome to Express.js!'); }); // Listen on port 2000 app.listen (2000 , () => { console.log('listening at http://localhost:2000'); });

Example-2 index.html <!DOCTYPE html> <html> <body> <form action = "/ process_get " method = "get"> First Name: <input type = "text" name = " fname "> < br > Last Name: <input type = "text" name = " lname "> < br > <input type="submit" value="Submit"> </form> </body> </html>

Example-2 Express5.js var express = require('express'); var app=express(); app.use ( express.static ('public')); app.get ('/index.html', function ( req , res) { res.sendFile ( __ dirname + "/" + "index.html" ); }); app.get ('/ process_get ', function ( req , res) { res.send ('<p>First Name:'+req.query [' fname ']+'</p><p>Last Name:'+req.query [' lname ']+'</p>'); }); var server = app.listen (8000, function () { var port = server.address ().port console.log("Example app listening at % s",port ) });

Basic routing Routing  refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on ). Syntax app.METHOD (PATH , HANDLER ) app is an instance of express. METHOD is an  HTTP request method , in lowercase. PATH is a path on the server. HANDLER is the function executed when the route is matched.

Basic routing Respond with Hello World! on the homepage : app.get ('/', ( req , res) => { res.send ('Hello World!') }) Respond to POST request on the root route (/), the application’s home page : app.post ('/', ( req , res) => { res.send ('Got a POST request') })

Session-9

Data Base Connectivity Install MySQL node.js driver npm install mysql Import module require(' mysql ') Create connection createConnection () Establish a connection connnect () Running Query query() Terminating connection end()

Data Base Connectivity nodestoredata.js const express = require('express'); const app = express(); app.use ( express.json ()); app.use ( express.urlencoded ({extended: true})); var mysql = require(' mysql '); var con = mysql.createConnection ({ host: " localhost ", user: "root ", password: "", database: " srm " }); app.get ("/", ( req , res) => { res.sendFile (__ dirname + "/index.html"); }); app.post("/process", ( req , res) => { const cname = req.body.cname ; const caddr = req.body.addr ; console.log("Company Name: " + cname ); console.log("Address: " + caddr ); con.connect (function(err) { if (err) throw err; console.log("Connected!"); var sql = "INSERT INTO customers (name, address) VALUES (?,?)"; con.query ( sql ,[ cname , caddr ],function (err, result) { if (err) throw err; else console.log ("1 record inserted"); }); }); res.send ("Data Inserted Success"); }); port=3000; app.listen (port, () => console.log(`Server listening at port ${port}...`));

Data Base Connectivity nodeselectdata.js var mysql = require(' mysql '); var con = mysql.createConnection ({ host: " localhost ", user: "root", password: "", database: " srm " }); con.connect (function(err) { if (err) throw err; con.query ("SELECT * FROM customers", function (err, result, fields) { if (err) throw err; console.log(result); }); });