Sd-Ii-Ii Manual - N2
Sd-Ii-Ii Manual - N2
UGC AUTONOMOUS
(Accredited by NBA, Approved by AICTE NEW DELHI, Affiliated to JNTU, Hyderabad)
Kandlakoya, Medchal Road, Hyderabad-501 401
REGULATION: R22
A.Y: 2023-2024
Skill Development Course (NODE JS /REACT JS /DJANGO)
INTRODUCTION
NODE JS
Node.js is an open-source, cross-platform JavaScript runtime environment that allows
developers to run JavaScript code server-side. It uses the V8 JavaScript engine from Google
Chrome and enables developers to build scalable and efficient network applications. Node.js
is commonly used for building web servers, API servers, real-time applications, and various
other types of server-side applications.
Key features of Node.js include:
• Asynchronous and event-driven: Node.js uses non-blocking, asynchronous I/O
operations, which allows it to handle multiple connections simultaneously without
getting blocked. This architecture makes Node.js highly scalable and suitable for
building real-time applications.
• Single-threaded but highly scalable: Despite being single-threaded, Node.js can handle
thousands of concurrent connections efficiently due to its non-blocking I/O model.
• npm (Node Package Manager): npm is the default package manager for Node.js,
providing access to a vast ecosystem of libraries and tools that developers can use to
enhance their applications.
• JavaScript everywhere: Node.js enables developers to use JavaScript for both client-
side and server-side development, which promotes code reuse and simplifies the
development process for full-stack applications.
• Cross-platform: Node.js is compatible with various operating systems, including
Windows, macOS, and Linux, allowing developers to write code once and deploy it
across different environments.
• Overall, Node.js has gained widespread popularity in the web development community
due to its performance, scalability, and ease of use, making it a preferred choice for
building modern web applications.
ADVANTAGES OF NODE JS
Node.js offers several advantages for developers, making it a popular choice for building
server-side applications. Some of the key advantages of Node.js include:
Scalability: Node.js is well-suited for building highly scalable applications due to its non-
blocking, event-driven architecture. It can handle a large number of concurrent connections
efficiently, making it ideal for real-time applications such as chat applications, online gaming
platforms, and streaming services.
Performance: Node.js leverages the V8 JavaScript engine, which compiles JavaScript code
into machine code at runtime, resulting in fast execution speeds. Additionally, its non-blocking
I/O model allows applications to handle multiple requests simultaneously without blocking the
event loop, leading to improved performance.
JavaScript Everywhere: With Node.js, developers can use JavaScript for both client-side and
server-side development, enabling them to share code between the front end and back end of
their applications. This promotes code reuse, simplifies the development process, and reduces
the learning curve for developers who are already familiar with JavaScript.
Rich Ecosystem: Node.js has a vibrant ecosystem supported by npm (Node Package
Manager), which hosts over a million packages that developers can leverage to extend the
functionality of their applications. This vast library of modules covers a wide range of use
cases, from web frameworks and database drivers to utility libraries and tools for testing and
deployment.
Community Support: Node.js has a large and active community of developers who contribute
to its development, share knowledge, and provide support through forums, online communities,
and open-source projects. This community-driven approach ensures that developers have
access to resources, tutorials, and best practices to help them overcome challenges and build
high-quality applications.
Cross-Platform Compatibility: Node.js is cross-platform and can run on various operating
systems, including Windows, macOS, and Linux. This allows developers to write code once
and deploy it across different environments without making significant changes, streamlining
the development and deployment process.
Easy to Learn and Use: Node.js is relatively easy to learn, especially for developers who are
already familiar with JavaScript. Its event-driven, asynchronous programming model may
require some adjustment for developers coming from synchronous programming backgrounds,
but once mastered, it can lead to more efficient and scalable code.
Overall, Node.js offers a compelling set of advantages that make it a popular choice for
building modern, high-performance web applications.
EXAMPLE
REACT JS
React.js, commonly referred to as React, is an open-source JavaScript library for building user
interfaces (UIs) or UI components. It was developed by Facebook and has gained widespread
adoption in the web development community due to its declarative and component-based
approach to building user interfaces.
Some of the key advantages of React.js include:
Declarative Syntax: React allows developers to describe the UI state and how it should render
based on changes to that state. With its declarative syntax, developers can write cleaner and
more understandable code compared to imperative approaches.
Component-Based Architecture: React encourages a modular and reusable approach to
building UIs through its component-based architecture. Developers can create individual
components that encapsulate their own logic and UI, making it easier to manage and maintain
complex applications.
Virtual DOM (Document Object Model): React uses a virtual DOM to efficiently update the
UI. Instead of directly manipulating the browser's DOM, React creates a lightweight
representation of the DOM in memory and updates it based on changes to the UI state. This
minimizes the number of actual DOM manipulations, resulting in better performance.
One-Way Data Binding: React follows a unidirectional data flow, where data flows
downward from parent components to child components. This makes it easier to understand
how data is passed and manipulated within the application, reducing the likelihood of bugs and
making the codebase more maintainable.
JSX (JavaScript XML): React uses JSX, an extension of JavaScript that allows developers to
write HTML-like syntax directly within their JavaScript code. This approach makes it easier
to visualize and understand the structure of UI components, as well as to integrate HTML
seamlessly with JavaScript logic.
Rich Ecosystem and Community: React has a large and active community of developers who
contribute to its development, create reusable components, and provide support through
forums, documentation, and online resources. Additionally, React has a rich ecosystem of
libraries and tools, such as React Router for routing, Redux for state management, and React
Native for building native mobile applications.
Performance: React's efficient handling of the virtual DOM and its ability to selectively
update only the components that have changed contribute to improved performance compared
to traditional approaches. This makes React well-suited for building fast and responsive user
interfaces, even in large-scale applications.
Overall, React.js offers a powerful and flexible framework for building modern web
applications with dynamic and interactive user interfaces. Its combination of declarative
syntax, component-based architecture, and efficient rendering make it a popular choice for
developers seeking to create high-quality UIs.
EXAMPLE
function App() {
return (
<div className="App">
<HelloWorld />
</div>
);
}
• Run your React.js project by executing npm start in the terminal while inside your
project directory.
• Open a web browser and visit http://localhost:3000/, you should see the text "Hello,
World!" rendered on the page.
• This example demonstrates how to create a simple React.js component named
HelloWorld that renders "Hello, World!" inside an <h1> tag. You can then use this
component in your React.js application to display the message wherever needed.
DJANGO
Django is a high-level Python web framework that encourages rapid development and clean,
pragmatic design. It follows the "batteries-included" philosophy, providing developers with a
set of tools and libraries to build web applications quickly and efficiently.
Some of the key advantages of Django include:
Rapid Development: Django's "batteries-included" approach means that it comes with many
built-in features and functionalities, such as an ORM (Object-Relational Mapping) system,
authentication, URL routing, form handling, and administrative interface. This allows
developers to focus on building application-specific features rather than reinventing the wheel.
DRY Principle (Don't Repeat Yourself): Django emphasizes the DRY principle by providing
reusable components and encouraging developers to write modular, reusable code. This helps
reduce code duplication, improves maintainability, and makes it easier to scale the application
as it grows.
ORM (Object-Relational Mapping): Django's built-in ORM simplifies database interactions
by allowing developers to work with database models using Python classes and methods, rather
than writing raw SQL queries. This abstraction layer makes it easier to perform common
database operations, such as querying, inserting, updating, and deleting records.
Admin Interface: Django comes with a powerful admin interface that can be automatically
generated based on the application's database models. This admin interface allows developers
and administrators to manage site content, user accounts, and other data without writing custom
admin panels.
Security: Django provides built-in protection against common security threats, such as SQL
injection, cross-site scripting (XSS), cross-site request forgery (CSRF), and clickjacking. It
also offers features like user authentication, session management, and secure password hashing
out of the box, helping developers build secure web applications by default.
Scalability: Django's architecture is designed to scale from small, single-server deployments
to large, high-traffic websites. It supports various deployment options, including traditional
web servers like Apache and Nginx, as well as cloud platforms like Heroku, AWS, and Google
Cloud Platform.
Community and Ecosystem: Django has a large and active community of developers who
contribute to its development, create reusable packages and libraries, and provide support
through forums, documentation, and online resources. This vibrant ecosystem makes it easier
for developers to find solutions to common problems, learn best practices, and stay up-to-date
with the latest developments in web development.
Overall, Django is a powerful and versatile framework for building web applications with
Python. Its emphasis on rapid development, clean design, and security makes it a popular
choice for developers of all skill levels.
EXAMPLE
Django application that defines a basic view to render "Hello, World!" on a webpage
1. First, make sure you have Django installed. You can install it using pip:
pip install Django
2. Create a new Django project using the following command:
django-admin startproject hello_world_project
3. Navigate into the project directory:
cd hello_world_project
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('hello_world_app.urls')),
]
8. You can now run the development server using the following command:
python manage.py runserver
9. Visit http://127.0.0.1:8000/ in your web browser, and you should see "Hello, World!"
displayed on the page.
This example demonstrates how to create a simple Django application with a single view that
renders "Hello, World!" when accessed.
FACULTY HOD
Experiment 1
AIM: Build a responsive web application for shopping cart with registration, login,
catalog and cart pages using CSS3 features, flex and grid.
PROGRAM:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Shopping Cart</title>
</head>
<body>
<header>
<h1>CMR Shopping Cart</h1>
<nav>
<ul>
<li><a href="#catalog">Catalog</a></li>
<li><a href="#cart">Cart</a></li>
<li><a href="#login">Login</a></li>
<li><a href="#register">Register</a></li>
</ul>
</nav>
</header>
<main id="main-content">
<!-- Content will be dynamically loaded here using JavaScript -->
</main>
<footer>
<p> Thank you visit again</p>
</footer>
<script src="script.js"></script>
</body>
</html>
1
OUTPUT:
• Catalog
• Cart
• Login
• Register
2
Experiment 2
AIM: Make the above web application responsive web application using Bootstrap
framework.
PROGRAM:
Catalog.html
<!DOCTYPE html>
<html lang="en">
<!-- divinectorweb.com -->
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Product Card</title>
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&display=swap"
rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css"
integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N"
crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-
Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct"
crossorigin="anonymous"></script>
</head>
<body>
<div class="wrapper">
<div class="product-area">
<div class="img-area">
<img alt="Product 1" src="img/1.jpg">
<div class="product-overlay">
<div class="overlay">
<a class="btn-1" href="#">Add to Cart</a>
<a class="btn-2" href="#">View Details</a>
</div>
</div>
</div>
<div class="info-area">
<h3>Product name</h3>
<div class="rating">
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
3
<span class="fa fa-star checked"></span>
<span class="fa fa-star"></span>
<span class="fa fa-star"></span>
</div>
<div class="product-price">
Rs.400
</div>
</div>
</div>
<div class="product-area">
<div class="img-area">
<img alt="" src="img/2.jpg">
<div class="product-overlay">
<div class="overlay">
<a class="btn-1" href="#">Add to Cart</a>
<a class="btn-2" href="#">View Details</a>
</div>
</div>
</div>
<div class="info-area">
<h3>Product name</h3>
<div class="rating">
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star"></span>
</div>
<div class="product-price">
Rs.700
</div>
</div>
</div>
<div class="product-area">
<div class="img-area">
<img alt="" src="img/3.jpg">
<div class="product-overlay">
<div class="overlay">
<a class="btn-1" href="#">Add to Cart</a>
<a class="btn-2" href="#">View Details</a>
</div>
</div>
</div>
<div class="info-area">
<h3>Product name</h3>
<div class="rating">
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
4
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
</div>
<div class="product-price">
Rs.2000
</div>
</div>
</div>
<div class="product-area">
<div class="img-area">
<img alt="" src="img/4.jpg">
<div class="product-overlay">
<div class="overlay">
<a class="btn-1" href="#">Add to Cart</a>
<a class="btn-2" href="#">View Details</a>
</div>
</div>
</div>
<div class="info-area">
<h3>Product name</h3>
<div class="rating">
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star"></span>
<span class="fa fa-star"></span>
</div>
<div class="product-price">
Rs.2500
</div>
</div>
</div>
<div class="product-area">
<div class="img-area">
<img alt="" src="img/5.jpg">
<div class="product-overlay">
<div class="overlay">
<a class="btn-1" href="#">Add to Cart</a>
<a class="btn-2" href="#">View Details</a>
</div>
</div>
</div>
<div class="info-area">
<h3>Product name</h3>
<div class="rating">
<span class="fa fa-star checked"></span>
<span class="fa fa-star checked"></span>
<span class="fa fa-star"></span>
<span class="fa fa-star"></span>
<span class="fa fa-star"></span>
5
</div>
<div class="product-price">
Rs.3000
</div>
</div>
</div>
<div class="product-area">
<div class="img-area">
<img alt="" src="img/6.jpg">
<div class="product-overlay">
<div class="overlay">
<a class="btn-1" href="#">Add to Cart</a>
<a class="btn-2" href="#">View Details</a>
</div>
</div>
</div>
<div class="info-area">
<h3>Product name</h3>
<div class="rating">
<span class="fa fa-star checked"></span>
<span class="fa fa-star"></span>
<span class="fa fa-star"></span>
<span class="fa fa-star"></span>
<span class="fa fa-star"></span>
</div>
<div class="product-price">
Rs.300/-
</div>
</div>
</div>
</div>
</body>
</html>
OUTPUT:
Product 1
Add to Cart View Details
Product name
Rs.400
Rs.700
Add to Cart View Details
Product name
6
Rs.2000
Rs.2500
Rs.3000
Rs.300/-
Registration.html
<html>
<head>
<title> Registration Page </title>
</head>
<body bgcolor="Lightskyblue">
<br>
<br>
<form id="Reset">
<h1><bold> Student Registration Form </bold></h1>
<label> Firstname :</label>
<input type="text" name="firstname" size="30"/><br><br>
<label> Middlename: </label>
<input type="text" name="middlename" size="30"/><br><br>
<label> Lastname: </label>
<input type="text" name="lastname" size="30"/><br><br>
<label>
Course :
</label>
<select>
<option value=" Course ">Course</option>
<option value="B.Tech">B.Tech</option>
<option value="BCA">BCA</option>
<option value="BBA">BBA</option>
<option value="MBA">MBA</option>
<option value="MCA">MCA</option>
7
<option value="M.Tech">M.Tech</option>
</select>
<br>
<br>
<label>
Gender :
</label><br>
<input type="radio" name="male" /> Male
<input type="radio" name="female"/> Female <br>
<br>
<br>
<label>
Phone :
</label>
<input type="text" name="country code" value="+91" size="2"/>
<input type="text" name="phone" size="10"/><br><br>
Address
<br>
<textarea cols="80" rows="5" value="address"></textarea><br>
<input type="button" name="submit" value="submit">
<input type = "button" value = "Reset" onClick = "fun()"/>
<script>
function fun(){
document.getElementById("Reset").reset();
}
</script>
OUTPUT:
Login.html
<!DOCTYPE html>
<html lang="en">
<head>
8
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Login Form Design using flexbox</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="form-box">
<div class="wrapper">
<div class="img-area">
<img src="1.png" alt="">
</div>
<div class="form-area">
<h3>Login Form</h3>
<form>
<div class="single-form">
<input type="text" placeholder="Username" />
</div>
<div class="single-form">
<input type="password" placeholder="Password" />
</div>
<input type="submit" value="Login"/>
</form>
</div>
</div>
</div>
</body>
</html>
OUTPUT:
9
Experiment 3
AIM: Use JavaScript for doing client side validation of the pages implemented in experiment 1
and experiment 2.
PROGRAM:
Login Validation.html
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
/* Style all input fields */
input {
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
margin-top: 6px;
margin-bottom: 16px;
}
background-color: #04AA6D;
color: white;
}
/* The message box is shown when the user clicks on the password field */
#message {
display:none;
background: #f1f1f1;
color: #000;
position: relative;
padding: 20px;
margin-top: 10px;
}
#message p {
padding: 10px 35px;
10
font-size: 18px;
}
/* Add a green text color and a checkmark when the requirements are right */
.valid {
color: green;
}
.valid:before {
position: relative;
left: -35px;
content: "✔";
}
/* Add a red text color and an "x" when the requirements are wrong */
.invalid {
color: red;
}
.invalid:before {
position: relative;
left: -35px;
content: "✖";
}
</style>
</head>
<body>
<h3>Password Validation</h3>
<p>Try to submit the form.</p>
<div class="container">
<form action="/action_page.php">
<label for="usrname">Username</label>
<input type="text" id="usrname" name="usrname" required>
<label for="psw">Password</label>
<input type="password" id="psw" name="psw" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Must
contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters" required>
<div id="message">
<h3>Password must contain the following:</h3>
<p id="letter" class="invalid">A <b>lowercase</b> letter</p>
<p id="capital" class="invalid">A <b>capital (uppercase)</b> letter</p>
<p id="number" class="invalid">A <b>number</b></p>
<p id="length" class="invalid">Minimum <b>8 characters</b></p>
11
</div>
<script>
var myInput = document.getElementById("psw");
var letter = document.getElementById("letter");
var capital = document.getElementById("capital");
var number = document.getElementById("number");
var length = document.getElementById("length");
// When the user clicks on the password field, show the message box
myInput.onfocus = function() {
document.getElementById("message").style.display = "block";
}
// When the user clicks outside of the password field, hide the message box
myInput.onblur = function() {
document.getElementById("message").style.display = "none";
}
// When the user starts to type something inside the password field
myInput.onkeyup = function() {
// Validate lowercase letters
var lowerCaseLetters = /[a-z]/g;
if(myInput.value.match(lowerCaseLetters)) {
letter.classList.remove("invalid");
letter.classList.add("valid");
} else {
letter.classList.remove("valid");
letter.classList.add("invalid");
}
// Validate numbers
var numbers = /[0-9]/g;
if(myInput.value.match(numbers)) {
number.classList.remove("invalid");
number.classList.add("valid");
} else {
number.classList.remove("valid");
number.classList.add("invalid");
}
12
// Validate length
if(myInput.value.length >= 8) {
length.classList.remove("invalid");
length.classList.add("valid");
} else {
length.classList.remove("valid");
length.classList.add("invalid");
}
}
</script>
</body>
</html>
OUTPUT:
13
Experiment 4
AIM: Explore the features of ES6 like arrow functions, call backs, promises,
async/await. Implement an application for reading the weather information
from openweathermap.org and display the information in the form of a graph on
the web page.
Features of ES6
ES6, or ECMAScript 2015, introduced several powerful features to JavaScript, including arrow
functions, callbacks, promises, and async/await. Let's explore each of these features:
1. Arrow Functions:
• Arrow functions provide a more concise syntax for writing anonymous functions.
• They use the => syntax.
• They don't bind their own this, arguments, super, or new.target.
• They are especially useful for short, one-liner functions and for maintaining the context
of this in callbacks.
EXAMPLE
// ES5
var double = function(x) {
return x * 2;
};
// ES6
const double = x => x * 2;
2. Callbacks:
• Callbacks are functions passed as arguments to other functions, to be executed later.
• They are commonly used in asynchronous programming to handle events or
• asynchronous operations.
• Callback functions can be synchronous or asynchronous.
EXAMPLE:
function fetchData(callback) {
// Simulating an asynchronous operation
setTimeout(() => {
const data = 'Some data fetched';
callback(data);
}, 1000);
}
fetchData(data => {
console.log(data);
14
});
3. Promises:
EXAMPLE:
function fetchData() {
return new Promise((resolve, reject) => {
// Simulating an asynchronous operation
setTimeout(() => {
const data = 'Some data fetched';
resolve(data);
}, 1000);
});
}
fetchData()
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
4. Async/Await:
• Async/await is a syntax for writing asynchronous code that looks synchronous, making it
• easier to read and understand.
• It is built on top of promises.
• async keyword is used to define an asynchronous function, and await is used to pause
• execution until a promise is settled.
EXAMPLE:
15
async function processData() {
try {
const data = await fetchData();
console.log(data);
} catch (error) {
console.error(error);
}
}
processData();
PROGRAM:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather Graph</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
}
.container {
max-width: 800px;
margin: 50px auto;
padding: 20px;
background-color: #fff;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1 {
text-align: center;
}
.graph-container {
margin-bottom: 20px;
}
.input-container {
display: flex;
justify-content: center;
}
16
#cityInput {
padding: 10px;
border-radius: 5px 0 0 5px;
border: 1px solid #ccc;
outline: none;
}
#fetchWeatherBtn {
padding: 10px 20px;
background-color: #007bff;
border: none;
color: #fff;
border-radius: 0 5px 5px 0;
cursor: pointer;
outline: none;
}
#fetchWeatherBtn:hover {
background-color: #0056b3;
}
</style>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div class="container">
<h1>Weather Graph</h1>
<div class="graph-container">
<canvas id="weatherChart"></canvas>
</div>
<div class="input-container">
<input type="text" id="cityInput" placeholder="Enter city name">
<button id="fetchWeatherBtn">Fetch Weather</button>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const apiKey = '7e43491c95b913ec443a233dc358de79';
let weatherChart;
document.getElementById('fetchWeatherBtn').addEventListener('click', function() {
const cityInput = document.getElementById('cityInput');
const city = cityInput.value.trim();
fetchWeatherData(city)
.then(data => {
const weatherData = extractWeatherData(data);
renderChart(weatherData);
})
.catch(error => {
console.error('Error fetching weather data:', error);
alert('Failed to fetch weather data. Please try again.');
});
});
function extractWeatherData(data) {
return {
temperature: data.main.temp,
humidity: data.main.humidity,
pressure: data.main.pressure
};
}
function renderChart(weatherData) {
if (weatherChart) {
weatherChart.destroy();
}
OUTPUT
19
20
Experiment 05
AIM: Develop a java stand alone application that connects with the database (Oracle / mySql) and
perform the CRUD operation on the database tables
PROGRAM:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
try {
PrintWriter out=response.getWriter();
out.print("<h1>Hello Eclipse</h1>");
}catch(Exception e)
e.printStackTrace();
import java.sql.*;
import java.util.Scanner;
public class InsertData {
public static void main(String[] args) {
try {
// to create connection with database
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/mydb", "root", "");
Statement s = con.createStatement();
21
// To read insert data into student table
Scanner sc = new Scanner(System.in);
System.out.println("Inserting Data into student table : ");
System.out.println(" ");
System.out.print("Enter student id : ");
int sid = sc.nextInt();
System.out.print("Enter student name : ");
String sname = sc.next();
System.out.print("Enter student address : ");
String saddr = sc.next();
// to execute insert query
s.execute("insert into student values("+sid+",'"+sname+"','"+saddr+"')");
System.out.println("Data inserted successfully into student table");
s.close();
con.close();
} catch (SQLException err) {
System.out.println("ERROR: " + err);
} catch (Exception err) {
System.out.println("ERROR: " + err);
}
}
}
UpdateData.java
import java.sql.*;
import java.util.Scanner;
public class UpdateData {
public static void main(String[] args) {
try {
// to create connection with database
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/mydb", "root", "");
Statement s = con.createStatement();
22
s.execute("update student set s_name='"+sname+"',s_address = '"+saddr+"' where s_id = "+sid);
System.out.println("Data updated successfully");
s.close();
con.close();
} catch (SQLException err) {
System.out.println("ERROR: " + err);
} catch (Exception err) {
System.out.println("ERROR: " + err);
}
}
}
DeleteData.java
import java.sql.*;
import java.util.Scanner;
public class DeleteData {
public static void main(String[] args) {
try {
// to create connection with database
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/mydb", "root", "");
Statement s = con.createStatement();
DisplayData.java
import java.sql.*;
import java.util.Scanner;
public class DisplayData {
public static void main(String[] args) {
try {
23
// to create connection with database
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/mydb", "root", "");
Statement s = con.createStatement();
}
}
OUTPUT
24
25
Experiment 06
AIM: create an XML for the bookstore validates the same using both DTD AND XSD.
An XML document that is well created can be validated using DTD (Document Type Definition) or XSD
(XML Schema Definition). A well-formed XML document should have correct syntax and should follow the
below rules:
• It must start with the XML declaration.
• It must have one unique root element enclosing all the other tags.
• It must have one unique root element enclosing all the other tags.
26
Difference between DTD and XSD
DTD XSD
DTD refers to Document Type Definition. XSD refers to XML Schema Definition.
These are derived from SGML syntax. These are written in XML.
It does not support datatypes. It supports datatypes.
It does not support namespaces. It supports namespaces.
It does not define the order of child elements. It defines the order of child elements.
It is not extensible. It is extensible.
It is not simple and easy to learn. It is simple and easy to learn.
It provides less control over the XML structure. It provides more control over the XML
structure.
PROGRAM:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<head>
<title>BookStore</title>
</head>
<body>
<table border="2">
<tr>
<th>Bookname</th>
<th>Author</th>
<th>Publisher</th>
<th>Edition</th>
<th>Price</th>
</tr>
<tr>
<td>Web Technology</td>
<td>Robet Roy</td>
<td>Technical</td>
<td>7th</td>
<td>650</td>
</tr>
<tr>
<td>Software Engineering</td>
<td>Ugrasen Suman</td>
<td>Technical</td>
<td>8th</td>
27
<td>450</td>
</tr>
<tr>
<td>DWDM</td>
<td>Vipin Kumar</td>
<td>Technical</td>
<td>5th</td>
<td>399</td>
</tr>
<tr>
<td>Computer Networks</td>
<td>Forouzan</td>
<td>Technical</td>
<td>7th</td>
<td>500</td>
</tr>
<tr>
<td>D.A.A</td>
<td>T.H.Cormen</td>
<td>Technical</td>
<td>7th</td>
<td>600</td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
OUTPUT
28
Experiment-7
AIM: Design a controller with servlet that provides the interaction with application developed in
experiment1 and the database created in experiment5.
PROGRAM:
package mypkg;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
OUTPUT:
29
Experiment-8
AIM: Maintaining the transaction history of any user is important. Explore the
various session tracking mechanisms (COOKIES, HTTP SESSION).
COOKIES IN SERVLET
A cookie is a small piece of information that is persisted between the multiple client requests.
A cookie has a name, a single value, and optional attributes such as a comment, path and domain
qualifiers, a maximum age, and a version number.
By default, each request is considered as a new request. In cookies technique, we add cookie with response
from the servlet. So cookie is stored in the cache of the browser. After that if request is sent by the user,
cookie is added with request by default. Thus, we recognize the user as the old user.
Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the browser. It is removed only if user
logout or signout.
30
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
PROGRAM:
32
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookiesServlet extends HttpServlet{
public void doGet(HttpServletRequestreq, HttpServletResponse res)throws IOException, ServletException{
Cookie c[] = req.getCookies);
printWritern pw = res.getwriter();
res.setContentType(“text/html”);
for (inti=0;i<c.length;i++){
String name = c[i].getName();
String value = c[i].getValue();
pw.printin("name="+name+" "+"value="+value);
pw.close();
}
}
Web file
‹?xml version="1.0" encoding="UTF-8" ?>
<web-app>
< servlet>
< servlet-name>AddCookieServlet</servlet-name>
< servlet-class>AddCookieServlet</servlet-class>
</servlet>
<servlet>
< servlet-name>GetCookiesServlet</servlet-name>
< servlet-class>GetCookiesServlet</servlet-class>
</servlet>
< servlet-mapping>
< servlet-name>AddCookieServlet</servlet-name>
<url-pattern>/AddCookieServlet</url-pattern>
</servlet-mapping>
<servlet-mapping >
< servlet-name>GetCookiesServlet</servlet-name>
‹url-pattern>GetCookiesservlet/se-pattern>
33
</servlet-mapping>
‹welcome-file-list>
‹welcome-file > AddCookie.html</welcome-file>
‹welcome-file> AddCookie.htm</welcome-file>
</welcome-file-list>
</web-app>
OUTPUT
34
VSCODE PROGRAM:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cookie Tracking Mechanism</title>
</head>
<body>
<h1>Welcome to our website!</h1>
<p>This is a basic example of cookie-based session tracking.</p>
<script>
// Function to set a cookie
functionsetCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
35
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
36
// Function to generate a random session ID
functiongenerateSessionId() {
returnMath.random().toString(36).substr(2, 9); // Generate a random string
}
37
38
Experiment-9
AIM: Create a custom server using http module and explore the other modules of
Node JS like os,path,event.
PROGRAM:
39
// Step 6: Print OS information
console.log('OS Type:', os.type());
console.log('OS Platform:', os.platform());
console.log('OS Architecture:', os.arch());
console.log('CPU Cores:', os.cpus().length);
OUTPUT
40
Experiment-10
AIM Develop an express web application that can interact with REST API to
perform CRUD operation on student data(postman).
PROGRAM:
Firstly we need to create a new folder and open the folder in the command prompt and enter a
command as below
npm init -y
41
}
});
});
}
// Function to create the 'students' table if it doesn't exist
function createStudentsTable(db) {
const createTableQuery = `
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
age INTEGER,
grade TEXT
);
`;
module.exports = { initializeDatabase }
const express = require('express');
const sqlite3 = require('sqlite3');
const{ initializeDatabase } = require('./db');
const app = express();
const port = 3000;
42
// Get all Students
app.get('/students', (req, res) => {
db.all('SELECT * FROM students', [], (err, rows) => {
if (err) {
return console.error(err.message);
}
res.json(rows);
});
});
// Update a student
app.put('/students/:id', (req, res) => {
const id = req.params.id;
const{ name, age, grade } = req.body;
db.run('UPDATE students SET name = ?, age = ?, grade = ? WHERE id = ?', [name, age,
grade, id], function (err) {
if (err) {
return console.error(err.message);
}
res.json({ updatedID:id });
});
});
43
// Delete a student
app.delete('/students/:id', (req, res) => {
const id = req.params.id;
db.run('DELETE FROM students WHERE id = ?', id, function (err) {
if (err) {
return console.error(err.message);
}
res.json({ deletedID:id });
});
});
app.listen(port, () => {
console.log('Server running at http://localhost:${port}');
});
OUTPUT
GET:
• Open Postman.
• Set the request type to GET.
• Enter the URL: http://localhost:3000/students.
44
•
45
DELETE:
• Set the request type to DELETE.
• Enter the URL for the student you want to delete (replace: id with an actual student
ID): http://localhost:3000/students/:id
• Place instead of ID which replace with number that is ID to be deleted.
• Then click send
PUT:
• Set the request type to PUT.
• Enter the URL for the student you want to delete (replace: id with an actual student
ID): http://localhost:3000/students/:id
• Go to the "Body" tab.
• Select raw and set the body to JSON format
46
Experiment 11
AIM : For the above application create authorized end points using
JWT.(JSONWEBTOKEN).
PROGRAM:
const express = require("express");
const jwt = require("jsonwebtoken");
const app = express();
const secretKey = "secretKey";
})
} })
})
function verifyToken(req,resp,next){
const brearerHeader = req.headers['authorization'];
if(typeof bearerHeader !=='undefined'){
const bearer = bearerHeader.split(" ");
const token= token;
next();
47
}else {
resp.send({
result:'Token is not valid'
})
}
}
app.listen(5000, () => {
console.log("app is running on 5000 port");
})
OUTPUT
48
49
Experiment-12
AIM: Create a React application for the student management system having
registration, login, contact, about pages and implement routing to navigate through
these pages.
PROGRAM:
Steps to create the React application:
Cd myreactapp
Project Structure:
50
// Filename - App.js
import './App.css';
import Form from "./Form"
function App() {
return (
<div className="App">
<Form />
</div>
);
}
// Filename - Form.js
51
};
return (
<div className="form">
<div>
<h1>User Registration</h1>
</div>
52
{/* Calling to the methods */}
<div className="messages">
{errorMessage()}
{successMessage()}
</div>
<form>
{/* Labels and inputs for form data */}
<label className="label">Name</label>
<input
onChange={handleName}
className="input"
value={name}
type="text"
/>
<label className="label">Email</label>
<input
onChange={handleEmail}
className="input"
value={email}
type="email"
/>
<label className="label">Password</label>
<input
onChange={handlePassword}
className="input"
value={password}
type="password"
/>
/* Filename: App.css */
.App {
53
text-align: center;
background-color: green;
}
.label {
display: block;
font-size: larger;
color: white;
padding: 5px;
}
.input {
font-size: larger;
padding: 5px;
margin: 2px;
.btn {
color: white;
background-color: red;
border-radius: 5px;
font-size: larger;
display: block;
padding: 5px;
margin: 10px auto;
}
.messages {
display: flex;
justify-content: center;
}
.error {
display: block;
background-color: red;
color: white;
width: fit-content;
height: 50px;
padding: 5px;
}
.success {
display: block;
background-color: lightblue;
color: black;
54
width: fit-content;
height: 50px;
padding: 5px;
}
OUTPUT
55
Experiment 13
AIM: Create a service in the react that fetches the weather information from open
weather map.org. and display the current and historical weather information using
graphical representation using chart .js .
PROGRAM:
Step 1: Create an OpenWeatherMap Account and Generate API Key
• Visit the OpenWeatherMap website (https://openweathermap.org/) and click on "Sign
Up" or "Log In" to create an account or log into your existing account.
• Once logged in, navigate to your account dashboard.
• From the dashboard, locate my API Keys section and click on "Create Key" or "API
Keys" to generate a new API key.
• Provide a name for your API key (e.g., "WeatherApp") and click on the "Generate" or
"Create" button.
• Your API key will be generated and displayed on the screen. Make sure to copy it as we
will need it later.
Step 2: Set up a new React project
• Open your terminal or command prompt.
• Run the following command to create a new React project:
• npxcreate-react-app weather-app
• Once the project is created, navigate into the project directory:
cd weather-app
56
• Add the following code to define a functional component named Weather:
import React, { useState } from 'react';
importaxios from 'axios';
const Weather = () => {
const [city, setCity] = useState('');
const [weatherData, setWeatherData] = useState(null);
`https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}`
);
setWeatherData(response.data);
console.log(response.data); // You can see all the weather data in console log
} catch (error) {
console.error(error);
}
};
57
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Enter city name"
value={city}
onChange={handleInputChange}
/>
<button type="submit">Get Weather</button>
</form>
{weatherData ? (
<>
<h2>{weatherData.name}</h2>
<p>Temperature: {weatherData.main.temp} °C</p>
<p>Description: {weatherData.weather[0].description}</p>
<p>Feels like: {weatherData.main.feels_like} °C</p>
<p>Humidity: {weatherData.main.humidity}%</p>
<p>Pressure: {weatherData.main.pressure} hPa</p>
<p>Wind Speed: {weatherData.wind.speed} m/s</p>
</>
):(
<p>Loading weather data...</p>
)}
</div>
);
};
58
import React from 'react';
import Weather from './Weather';
const App = () => {
return (
<div>
<h1>Weather Forecast App</h1>
<Weather />
</div>
);
};
export default App;
OUTPUT
59
60
Experiment 14
AIM: Create a TODO application in react with necessary components and deploy
it into github.
PROGRAM:
This command will create a directory named "todo-app" with all the initial code required for a
React app.
2. Navigate to the Project Directory:
Change your working directory to the "todo-app" folder:
cdtodo-app
npm start
This will open your React app, and yousee the default React starter page in your web browser
at 'http://localhost:3000'.
Step 2: Create the App Component
import React from 'react';
importTodoList from './components/TodoList';
function App() {
return (
<div className="App">
<TodoList />
61
</div>
);
}
export default App;
Step 3: Create the TodoList
src->Component
Now, let's create the 'TodoList' component, which is responsible for managing the list of tasks and
handling task-related functionality.
import React, { useState } from 'react';
importTodoItem from './TodoItem';
functionTodoList() {
const [tasks, setTasks] = useState([
{
id: 1,
text: 'Doctor Appointment',
completed: true
},
{
id: 2,
text: 'Meeting at School',
completed: false
}
]);
const[text, setText] = useState('');
functionaddTask(text) {
constnewTask = {
id: Date.now(),
text,
completed: false
};
62
setTasks([...tasks, newTask]);
setText('');
}
functiondeleteTask(id) {
setTasks(tasks.filter(task => task.id !== id));
}
functiontoggleCompleted(id) {
setTasks(tasks.map(task => {
if (task.id === id) {
return { ...task, completed: !task.completed };
} else {
return task;
}
}));
}
return (
<div className="todo-list">
{tasks.map(task => (
<TodoItem
key={task.id}
task={task}
deleteTask={deleteTask}
toggleCompleted={toggleCompleted}
/>
))}
<input
value={text}
onChange={e =>setText(e.target.value)}
63
/>
<button onClick={() =>addTask(text)}>Add</button>
</div>
);
}
export default TodoList;
Step 4: Create the place the TodoItem in
src->Component
In this step, we create the 'TodoItem' component, which represents an individual task in our Todo
List.
import React from 'react';
functionTodoItem({ task, deleteTask, toggleCompleted }) {
functionhandleChange() {
toggleCompleted(task.id);
}
return (
<div className="todo-item">
<input
type="checkbox"
checked={task.completed}
onChange={handleChange}
/>
<p>{task.text}</p>
<button onClick={() =>deleteTask(task.id)}>
X
</button>
</div>
);
}
64
export default TodoItem;
Step 5: Styling
.todo-item {
display: flex;
justify-content: space-between;
margin-bottom: 8px;
}
.todo-item p.completed {
color: #888;
text-decoration: line-through;
}
OUTPUT
Next,
65
VSCODE PROGRAM:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Todo List</title>
<style>
/* CSS Styles */
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
}
.container {
max-width: 600px;
margin: 20px auto;
padding: 20px;
background-color: #fff;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
input[type="text"] {
padding: 8px;
66
margin-right: 10px;
}
button {
padding: 8px 16px;
cursor: pointer;
}
ul {
list-style-type: none;
padding: 0;
}
li {
margin-bottom: 5px;
display: flex;
align-items: center;
opacity: 0;
animation: fadeIn 0.5s ease forwards;
}
.completed {
text-decoration: line-through;
transition: text-decoration 0.3s ease;
}
.checkbox {
margin-right: 10px;
}
.delete-btn {
margin-left: auto;
padding: 4px 8px;
background-color: #ff0000;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
}
.delete-btn:hover {
background-color: #cc0000;
}
@keyframes fadeIn {
67
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
</style>
</head>
<body>
<div class="container">
<h1>Todo List</h1>
<input type="text" id="taskInput" placeholder="Enter task">
<button onclick="addTask()">Add</button>
<ul id="taskList"></ul>
</div>
<script>
// JavaScript Code
function addTask() {
const taskInput = document.getElementById('taskInput');
const taskList = document.getElementById('taskList');
newTask.appendChild(checkbox);
newTask.appendChild(taskLabel);
newTask.appendChild(deleteBtn);
newTask.onclick = toggleTask;
taskList.appendChild(newTask);
taskInput.value = '';
68
}
}
function toggleTask(event) {
if (event.target.tagName === 'INPUT') {
const checkbox = event.target;
const listItem = checkbox.parentNode;
listItem.classList.toggle('completed');
}
}
function deleteTask() {
const listItem = this.parentNode;
const taskList = listItem.parentNode;
taskList.removeChild(listItem);
}
</script>
</body>
</html>
OUTPUT
69
70