CY409PC NODE JS REACT JS DJANGO LAB Manual
CY409PC NODE JS REACT JS DJANGO LAB Manual
Build a responsive web application for shopping cart with registration, login, catalog
and cart pages using CSS3 features, flex and grid.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="./style.css">
<title>Home - PEC</title>
</head>
<body>
<div class="wrapper">
<div class="container">
<header>
<table width="100%" align="center" cellpadding="0" cellspacing="2">
<tr>
<th width="20%"><img src="PEC Header.png" alt="PEC LOGO" width=""
height="100"/></th>
<th colspan=4>
<h1 style="color:white;">PEC - WORLD BEST ONLINE EBOOKS WEBSITE</h1>
</th>
</tr>
</table>
</header>
<nav>
<table width="100%" align="center" cellpadding="0" cellspacing="2">
<tbody align="center" style="font-weight:bold;font-size:18px;"">
<tr>
<td width="20%"><hr><a href="index.html">Home</a><hr></td>
<td width="20%"><hr><a href="login.html">Login</a><hr></td>
<td width="20%"><hr><a ref="registration.html">Registration</a><hr></td>
<td width="20%"><hr><a href="cart.html" >Cart</a><hr></td>
</tr>
</tbody>
</table>
</nav>
</div>
<div class="container1">
<div class="sidebar1"></div>
<div class="container2">
<main>
<center>
<h2>Welcome to PEC e-Book's Website</h2>
<p>Shopping at <font size=5>PEC</font> can be both <font
size=5>fun</font>
and <font size=5>savings</font>.</br>Shop with us in this
special <font
size=5>discount</font> season and save upto
<font size=5>90%</font> on all your
purchases.</br></p>
<br/><br/><br/><br/><br/><br/><br/><br/>
</main>
</div>
<div class="sidebar2"></div>
</div>
<footer><font color="white">(C) 2024 All rights reserved by PEC
ebooks</font></footer>
</div>
</body>
</html>
registration.html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="./style.css">
<title>Registration - PEC</title>
</head>
<body>
<div class="wrapper">
<div class="container">
<header>
<table width="100%" align="center" cellpadding="0" cellspacing="2">
<tr>
<th width="20%"><img src="PEC Header.png" alt="PEC LOGO" width="130"
height="100"/></th>
<th colspan=4>
<h1 style="color:white;">PEC - WORLD BEST ONLINE EBOOKS WEBSITE</h1>
</th>
</tr>
</table>
</header>
<nav>
<table width="100%" align="center" cellpadding="0" cellspacing="2">
<tbody align="center" style="font-weight:bold;font-size:18px;"">
<tr>
<td width="20%"><hr><a href="index.html">Home</a><hr></td>
<td width="20%"><hr><a href="login.html">Login</a><hr></td>
<td width="20%"><hr><a href="registration.html">Registratio</a><hr></td>
<td width="20%"><hr><a href="cart.html" >Cart</a><hr></td>
</tr>
</tbody>
</table>
</nav>
</div>
<div class="container1">
<div class="sidebar1"></div>
<div class="container2">
<main>
<center><br>
<h3>Registration Form </h3>
<br/>
<form name="f1">
<table cellpadding="1" align="center" >
<tr><td> Name:*</td>
<td><input type="text" name="username"></td></tr>
<tr><td>Password:*</td>
<td><input type="password" name="password"></td></tr>
<tr><td>Email ID:*</td>
<td><input type="text" name="email"></td></tr>
<tr><td>Phone Number:*</td>
<td><input type="text" name="phno"></td></tr>
<tr><td valign="top">Gender:*</td>
<td><input type="radio" name="radio" value="1">Male
<input type="radio" name="radio" value="2">Female</td></tr>
<tr> <td valign="top">Language Known:*</td>
<td> <input type="checkbox" name="checkbox"
value="English">English<br/>
<input type="checkbox" name="checkbox" value="Telugu">Telugu<br>
<input type="checkbox" name="checkbox" value="Hindi">Hindi<br>
<input type="checkbox" name="checkbox" value="Tamil">Tamil
</td></tr>
<tr> <td valign="top">Address:*</td>
<td><textarea name="address"></textarea></td>
<tr><td></td><td><input type="submit" value="submit"
hspace="10">
<input type="reset" value="reset"></td></tr>
<tr> <td colspan=2 >*<font color="#FF0000">fields are
mandatory</font>
</td>
</tr>
</table>
</form>
</center>
</main>
</div>
<div class="sidebar2"></div>
</div>
<footer><font color="white">(C) 2024 All rights reserved by PEC
ebooks</font></footer>
</div>
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="./style.css">
<title>Login - PEC</title>
</head>
<body>
<div class="wrapper">
<div class="container">
<header>
<table width="100%" align="center" cellpadding="0" cellspacing="2">
<tr>
<th width="20%"><img src="PEC Header.png" alt="PEC LOGO" width="130"
height="100"/></th>
<th colspan=4>
<h1 style="color:white;">PEC - WORLD BEST ONLINE EBOOKS WEBSITE</h1>
</th>
</tr>
</table>
</header>
<nav>
<table width="100%" align="center" cellpadding="0" cellspacing="2">
<tbody align="center" style="font-weight:bold;font-size:18px;"">
<tr>
<td width="20%"><hr><a href="index.html">Home</a><hr></td>
<td width="20%"><hr><a href="login.html">Login</a><hr></td>
<td width="20%"><hr><a
href="registration.html">Registration</a><hr></td>
<td width="20%"><hr><a href="cart.html" >Cart</a><hr></td>
</tr>
</tbody>
</table>
</nav>
</div>
<div class="container1">
<div class="sidebar1"></div>
<div class="container2">
<main>
<center><br>
<h3> Login Details</h3> <br/>
<form name="f1">
<table width="100%" align="center" >
<tr>
<td> User Name : </td>
<td> <input type="text" name="username"></td>
</tr>
<tr><td><br></td></tr>
<tr>
<td> Password : </td>
<td> <input type="password" name="password"></td>
</tr>
<tr><td><br></td></tr>
<tr><td></td>
<td><input type="submit" value="SUBMIT">
<input type="reset" value="RESET"></td>
</tr>
</table>
</form>
</center>
</main>
</div>
<div class="sidebar2"></div>
</div>
<footer><font color="white">(C) 2024 All rights reserved by PEC
ebooks</font></footer>
</div>
</body>
</html>
cart.html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="./style.css">
<title>Cart - PEC</title>
</head>
<body>
<div class="wrapper">
<div class="container">
<header>
<table width="100%" align="center" cellpadding="0" cellspacing="2">
<tr>
<th width="20%"><img src="PEC Header.png" alt="PEC LOGO" width="130"
height="100"/></th>
<th colspan=4>
<h1 style="color:white;">PEC - WORLD BEST ONLINE EBOOKS WEBSITE</h1>
</th>
</tr>
</table>
</header>
<nav>
<table width="100%" align="center" cellpadding="0" cellspacing="2">
<tbody align="center" style="font-weight:bold;font-size:18px;"">
<tr>
<td width="20%"><hr><a href="index.html">Home</a><hr></td>
<td width="20%"><hr><a href="login.html">Login</a><hr></td>
<td width="20%"><hr><a href="registration.html">Registation</a><hr></td>
<td width="20%"><hr><a href="cart.html" >Cart</a><hr></td>
</tr>
</tbody>
</table>
</nav>
</div>
<div class="container1">
<div class="sidebar1"></div>
<div class="container2">
<main>
<center>
<h3>Cart</h3>
<table width="100%" align="center" >
<tbody>
<tr>
<th width="40%"><hr>BookName<hr></th>
<th width="20%"><hr>Price<hr></th>
<th width="20%"><hr>Quantity<hr></th>
<th width="20%"><hr>Amount<hr></th> </tr>
</tbody>
<tbody align=center>
<tr> <td>Java Programming </td>
<td>Rs. 2300/-</td>
<td>2</td>
<td>Rs. 4600/-</td></tr>
<tr><td>Web Technologies</td>
<td>Rs. 3000/-</td>
<td>1</td>
<td>Rs. 3000/-</td></tr>
<tr><td></td>
<td><hr><font color="#996600">Total Amount:</font><hr></td>
<td><hr>3<hr></td>
<td><hr>Rs. 7600/-<hr></td> </tr>
</tbody>
</table>
</center>
</main>
</div>
<div class="sidebar2"></div>
</div>
<footer><font color="white">(C) 2024 All rights reserved by PEC
ebooks</font></footer>
</div>
</body>
</html>
style.css
body{
font-family: monospace;
}
main {
background-color: #efefef;
color: #330000;
margin-left: 10px;
height: 60vh;
}
header, footer {
background-color: #000d57;
color: #fff;
padding: 1rem;
height: 50px;
}
header, nav{
margin-bottom: 10px;
flex-basis: 50%;
}
footer{
margin-top: 10px;
}
nav {
background-color: #fff;
color: #000;
padding: 1rem;
height: 20px;
}
.sidebar1, .sidebar2 {
flex-basis: 10%;
background-color: #fff;
color: #000;
}
.sidebar2{
margin-left: 10px;
}
.container1{
display: flex;
}
.container2 {
display: flex;
flex-direction: column;
flex: 1;
}
.wrapper {
display: flex;
flex-direction: column;
font-weight: 600;
}
2. Make the above web application responsive web application using Bootstrap
framework.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home - PEC</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]
alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body {
background-color: #f8f9fa;
}
.header-img {
height: 100px;
}
.custom-header {
background-color: #ffffff;
color: white;
padding: 20px 0;
}
.custom-nav a {
color: white;
text-decoration: none;
padding: 10px 20px;
display: inline-block;
}
.custom-nav a:hover {
border-radius: 5px;
}
nav{
background-color:#0b6620;
}
</style>
<link
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
rel="stylesheet">
</head>
<body>
<div class="container-fluid">
<div class="container-fluid">
<!-- Header Section -->
<header class="custom-header text-center">
<div class="container d-flex align-items-center justify-content-
between">
<img src="PEC Header.png" alt="PEC LOGO" class="header-img">
<h1 class="mb-0">PEC - WORLD BEST ONLINE EBOOKS WEBSITE</h1>
</div>
</header>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registration Page</title>
<!-- Bootstrap CSS -->
<link
href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.cs
s" rel="stylesheet">
<link rel="stylesheet" href="stylecss">
<style>
body {
background-color: #f8f9fa;
}
.header-img {
height: 100px;
}
.custom-header {
background-color: #ffffff;
color: white;
padding: 20px 0;
}
.custom-nav a {
color: white;
text-decoration: none;
padding: 10px 20px;
display: inline-block;
}
.custom-nav a:hover {
background-color: #495057;
border-radius: 5px;
}
</style>
<link
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
rel="stylesheet">
</head>
<body>
<div class="container-fluid">
<!-- Header Section -->
<header class="custom-header text-center">
<div class="container d-flex align-items-center justify-content-between">
<img src="PEC Header.png" alt="PEC LOGO" class="header-img">
<h1 class="mb-0">PEC - WORLD BEST ONLINE EBOOKS WEBSITE</h1>
</div>
</header>
<!-- Navigation Section -->
<nav class="bg-dark custom-nav text-center">
<a href="index.html">Home</a>
<a href="login.html">Login</a>
<a href="registration.html">Register</a>
<a href="cart.html">Cart</a>
</nav>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather App with ES6 Features</title>
<link rel="stylesheet" href="styles.css">
<!-- Chart.js for data visualization -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div class="container">
<h1>Weather App with ES6 Features</h1>
<div class="search-container">
<input type="text" id="city-input" placeholder="Enter city name">
<button id="search-btn">Search</button>
</div>
<div class="weather-container">
<div id="current-weather" class="weather-card">
<h2>Current Weather</h2>
<div id="weather-info"></div>
</div>
<div id="weather-chart-container">
<canvas id="weather-chart"></canvas>
</div>
</div>
<div class="es6-demo-container">
<h2>ES6 Features Demo</h2>
<div class="feature-section">
<h3>Arrow Functions</h3>
<button id="arrow-demo-btn">Run Demo</button>
<div id="arrow-result" class="result"></div>
</div>
<div class="feature-section">
<h3>Callbacks</h3>
<button id="callback-demo-btn">Run Demo</button>
<div id="callback-result" class="result"></div>
</div>
<div class="feature-section">
<h3>Promises</h3>
<button id="promise-demo-btn">Run Demo</button>
<div id="promise-result" class="result"></div>
</div>
<div class="feature-section">
<h3>Async/Await</h3>
<button id="async-demo-btn">Run Demo</button>
<div id="async-result" class="result"></div>
</div>
</div>
</div>
<script src="es6Features.js"></script>
<script src="weatherApp.js"></script>
</body>
</html>
style.css
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Arial', sans-serif;
}
body {
background-color: #f5f5f5;
color: #333;
line-height: 1.6;
}
.container {
max-width: 1000px;
margin: 0 auto;
padding: 20px;
}
h1 {
text-align: center;
margin-bottom: 30px;
color: #2c3e50;
}
h2 {
color: #3498db;
margin-bottom: 15px;
}
h3 {
color: #2c3e50;
margin-bottom: 10px;
}
.search-container {
display: flex;
justify-content: center;
margin-bottom: 30px;
}
#city-input {
padding: 10px;
width: 300px;
border: 1px solid #ddd;
border-radius: 4px 0 0 4px;
font-size: 16px;
}
#search-btn {
padding: 10px 20px;
background-color: #3498db;
color: white;
border: none;
border-radius: 0 4px 4px 0;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s;
}
#search-btn:hover {
background-color: #2980b9;
}
.weather-container {
display: flex;
flex-direction: column;
gap: 20px;
margin-bottom: 40px;
}
.weather-card {
background-color: white;
border-radius: 8px;
padding: 20px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
#weather-chart-container {
background-color: white;
border-radius: 8px;
padding: 20px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
height: 300px;
}
.es6-demo-container {
background-color: white;
border-radius: 8px;
padding: 20px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
.feature-section {
margin-bottom: 25px;
padding-bottom: 15px;
border-bottom: 1px solid #eee;
}
.feature-section:last-child {
border-bottom: none;
}
button {
padding: 8px 15px;
background-color: #3498db;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
margin-bottom: 10px;
transition: background-color 0.3s;
}
button:hover {
background-color: #2980b9;
}
.result {
background-color: #f9f9f9;
padding: 10px;
border-radius: 4px;
border-left: 3px solid #3498db;
min-height: 40px;
white-space: pre-wrap;
}
.weather-card {
flex: 1;
}
#weather-chart-container {
flex: 2;
}
}
es6Feastures.js
// Traditional function
function traditionalSum(a, b) {
return a + b;
}
// Arrow function
const arrowSum = (a, b) => a + b;
resultElement.innerHTML = `
Traditional function: ${traditionalSum(5, 3)} <br>
Arrow function: ${arrowSum(5, 3)} <br>
Arrow function with multiple statements: ${arrowMultipleStatements(5, 3)}
<br>
Array.map with arrow function: [${doubled}] <br>
Array.filter with arrow function: [${filtered}]
`;
});
// Creating a promise
const fetchDataPromise = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = true; // Change to false to simulate error
if (success) {
const data = { name: 'Promise Data', temperature: 28 };
resolve(data);
} else {
reject(new Error('Failed to fetch data'));
}
}, 1500);
});
};
if (success) {
const data = { name: 'Async/Await Data', temperature: 30 };
resolve(data);
} else {
reject(new Error('Failed to fetch data'));
}
}, 1500);
});
};
// Using async/await
try {
const data = await fetchDataAsync();
resultElement.innerHTML = `
Async/Await resolved after 1.5 seconds: <br>
Name: ${data.name} <br>
Temperature: ${data.temperature}°C
`;
} catch (error) {
resultElement.innerHTML = `Async/Await error: ${error.message}`;
}
});
weatherApp.js
// Constants
const API_KEY = '349e1822e8739db21980838d35c0354a'; // You need to get your API
key from OpenWeatherMap
const BASE_URL = 'https://api.openweathermap.org/data/2.5';
// DOM Elements
const cityInput = document.getElementById('city-input');
const searchBtn = document.getElementById('search-btn');
const weatherInfo = document.getElementById('weather-info');
const weatherChartCanvas = document.getElementById('weather-chart');
// Chart instance
let weatherChart = null;
// Event Listeners
searchBtn.addEventListener('click', () => {
const city = cityInput.value.trim();
if (city) {
getWeatherData(city);
} else {
alert('Please enter a city name');
}
});
} catch (error) {
weatherInfo.innerHTML = `Error: ${error.message}`;
clearChart();
}
};
weatherInfo.innerHTML = html;
};
// Initial instructions
weatherInfo.innerHTML = `
<div class="initial-message">
<p>Enter a city name and click "Search" to get weather information.</p>
<p>You'll need to add your OpenWeatherMap API key in the weatherApp.js
file.</p>
</div>
`;
file:///C:/Users/rames/OneDrive/1.PEC/2-2/LabPrograms/4/index.html
Type Hyderabad Search
Demo
5. Develop a java stand-alone application that connects with the database (Oracle / MySQL)
and perform the CRUD operation on the database tables.
InsertData.java
### Description:
This Java file contains the implementation for database operations.
import java.sql.*;
import java.util.Scanner;
DisplayData.java
### Description:
This Java file contains the implementation for database operations.
import java.sql.*;
while (rs.next()) {
System.out.println(rs.getString("s_id") + " \t " +
rs.getString("s_name") + " \t " + rs.getString("s_address"));
System.out.println("________________________________________");
}
}
updateData.java
### Description:
This Java file contains the implementation for database operations.
import java.sql.*;
import java.util.Scanner;
deleteData.java
### Description:
This Java file contains the implementation for database operations.
import java.sql.*;
import java.util.Scanner;
bookstore.xsd
<xs:complexType name="bookstoreType">
<xs:sequence>
<xs:element name="book" type="bookType" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="bookType">
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="author" type="xs:string"/>
<xs:element name="price" type="xs:decimal"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
OUTPUT:
Session Tracking Mechanisms in JavaScript
Introduction:
Maintaining a user's transactional history is essential for modern web applications. From shopping
carts to user preferences, tracking user activity across multiple requests creates a seamless
experience. Since HTTP is stateless (each request is independent), we need session tracking
mechanisms to maintain state between requests.
In this guide, we'll explore various session tracking mechanisms in JavaScript, including cookies,
localStorage, sessionStorage, and server-side sessions, with practical code examples for each
approach.
Before diving into implementation, it's important to understand the security implications and
limitations of client-side storage:
Size Limits: Cookies have a size limit (typically 4KB), while localStorage and
sessionStorage offer more storage (usually 5-10MB per domain).
Cookies are small pieces of data stored on the client's browser that are sent back to the server with
each request.
Cookie Utility Functions:
index.js
index.html
<!DOCTYPE html>
<html>
<head>
<title>Cookie-Based Visit Counter</title>
<script>
// Cookie utility functions (from above)
if (visitCount) {
// Returning user - increment counter
visitCount = parseInt(visitCount) + 1;
document.getElementById('message').textContent =
`Welcome back! You've visited this page ${visitCount} times.`;
} else {
// New user - initialize counter
visitCount = 1;
document.getElementById('message').textContent =
"Welcome! This is your first visit.";
}
Advantages of Cookies:
Limitations of Cookies:
localStorage provides persistent storage that remains available even after the browser is closed and
reopened.
Index2.js
Index2.html
<!DOCTYPE html>
<html>
<head>
<title>LocalStorage Transaction Tracker</title>
<style>
body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto;
padding: 20px; }
.transaction-form { background: #f8f9fa; padding: 20px; border-radius:
5px; margin-bottom: 20px; }
.transaction-list { list-style-type: none; padding: 0; }
.transaction-item { display: grid; grid-template-columns: 1fr 100px
150px; gap: 10px; padding: 10px; border-bottom: 1px solid #eee; }
</style>
<script>
// LocalStorage utility functions (from above)
const TransactionTracker = {
init: function() {
// Initialize transaction data if it doesn't exist
if (!localStorage.getItem('transactionData')) {
const initialData = {
count: 0,
transactions: [],
lastVisit: new Date().toISOString()
};
setLocalStorage('transactionData', initialData);
} else {
// Update last visit time
const data = this.getTransactionData();
data.lastVisit = new Date().toISOString();
setLocalStorage('transactionData', data);
}
getTransactionData: function() {
return getLocalStorage('transactionData') || {count: 0, transactions:
[], lastVisit: ''};
},
addTransaction: function(event) {
event.preventDefault();
data.transactions.push(transaction);
data.count++;
// Update display
this.displayTransactions();
// Reset form
document.getElementById('transaction-form').reset();
},
displayTransactions: function() {
const historyElement = document.getElementById('transaction-
history');
const statsElement = document.getElementById('transaction-stats');
const data = this.getTransactionData();
// Update stats
statsElement.textContent = `Total transactions: ${data.count}`;
// Display transactions
if (data.transactions.length === 0) {
historyElement.innerHTML = '<li>No transactions recorded
yet.</li>';
} else {
// Sort transactions by date (newest first)
const sortedTransactions = [...data.transactions].sort((a, b) =>
new Date(b.date) - new Date(a.date)
);
sortedTransactions.forEach(transaction => {
const date = new Date(transaction.date).toLocaleString();
const li = document.createElement('li');
li.className = 'transaction-item';
li.innerHTML = `
<span>${transaction.description}</span>
<span>$${transaction.amount.toFixed(2)}</span>
<span>${date}</span>
`;
historyElement.appendChild(li);
});
}
},
clearHistory: function() {
if (confirm('Are you sure you want to clear all transaction
history?')) {
const data = this.getTransactionData();
data.transactions = [];
data.count = 0;
setLocalStorage('transactionData', data);
this.displayTransactions();
}
}
};
<div class="transaction-form">
<h2>Add New Transaction</h2>
<form id="transaction-form">
<div>
<label for="description">Description:</label>
<input type="text" id="description" required>
</div>
<div>
<label for="amount">Amount ($):</label>
<input type="number" id="amount" step="0.01" min="0" required>
</div>
<button type="submit">Add Transaction</button>
</form>
</div>
<h2>Transaction History</h2>
<p id="transaction-stats">Total transactions: 0</p>
<button id="clear-button">Clear History</button>
<ul id="transaction-history" class="transaction-list">
<li>No transactions recorded yet.</li>
</ul>
</body>
</html>
Advantages of LocalStorage:
Limitations of LocalStorage:
SessionStorage works similarly to localStorage but is limited to the current browser session. Data
is cleared when the session ends (the browser tab is closed).
Index3.html
<!DOCTYPE html>
<html>
<head>
<title>SessionStorage Example</title>
<style>
body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto;
padding: 20px; }
.session-box { background: #f1f9fe; padding: 15px; border-radius: 5px;
margin-bottom: 20px; }
</style>
<script>
// SessionStorage utility functions
function setSessionStorage(key, value) {
sessionStorage.setItem(key, JSON.stringify(value));
}
function getSessionStorage(key) {
const value = sessionStorage.getItem(key);
return value ? JSON.parse(value) : null;
}
function removeSessionStorage(key) {
sessionStorage.removeItem(key);
}
// Session tracker
const SessionTracker = {
init: function() {
// Initialize session data if it doesn't exist
if (!sessionStorage.getItem('sessionData')) {
const initialData = {
startTime: new Date().toISOString(),
pageViews: 1,
actions: []
};
setSessionStorage('sessionData', initialData);
} else {
// Update page views
const data = this.getSessionData();
data.pageViews++;
setSessionStorage('sessionData', data);
}
getSessionData: function() {
return getSessionStorage('sessionData') || {startTime: '', pageViews: 0,
actions: []};
},
displaySessionInfo: function() {
const infoElement = document.getElementById('session-info');
const actionsElement = document.getElementById('action-list');
const data = this.getSessionData();
// Display info
infoElement.innerHTML = `
<p>Session started: <strong>${startTime.toLocaleString()}</strong></p>
<p>Session duration: <strong>${durationMinutes}m
${durationSeconds}s</strong></p>
<p>Page views this session: <strong>${data.pageViews}</strong></p>
<p>Actions recorded: <strong>${data.actions.length}</strong></p>
`;
// Display actions
actionsElement.innerHTML = '';
if (data.actions.length === 0) {
actionsElement.innerHTML = '<li>No actions recorded in this
session.</li>';
} else {
data.actions.forEach(action => {
const time = new Date(action.timestamp).toLocaleTimeString();
const li = document.createElement('li');
li.textContent = `${time}: ${action.description}`;
actionsElement.appendChild(li);
});
}
},
recordAction: function(event) {
event.preventDefault();
// Update display
this.displaySessionInfo();
// Reset form
document.getElementById('action-form').reset();
},
endSession: function() {
if (confirm('Are you sure you want to end this session? All session data
will be lost.')) {
sessionStorage.clear();
alert('Session ended. The page will now reload.');
window.location.reload();
}
}
};
<div class="session-box">
<h2>Current Session Information</h2>
<div id="session-info">Loading session info...</div>
<button id="end-session">End Session</button>
</div>
<div>
<h2>Record Action</h2>
<form id="action-form">
<div>
<label for="action-description">Action Description:</label>
<input type="text" id="action-description" required>
</div>
<button type="submit">Record Action</button>
</form>
</div>
<h2>Session Activity</h2>
<ul id="action-list">
<li>No actions recorded in this session.</li>
</ul>
<div>
<p><strong>Note:</strong> All data is stored in sessionStorage and will be
lost when you close this browser tab.</p>
</div>
</body>
</html>
To use this example:
To interact with server-side sessions using JavaScript, you can use AJAX requests. Here's a simple
example:
Index4.html
<!DOCTYPE html>
<html>
<head>
<title>AJAX Session Example</title>
<script>
// Function to make AJAX requests
async function makeRequest(url, method = 'GET', data = null) {
const options = {
method,
credentials: 'include', // Important: include cookies in the request
headers: {}
};
if (data) {
options.headers['Content-Type'] = 'application/json';
options.body = JSON.stringify(data);
}
try {
const data = await makeRequest('/api/transactions', 'POST', {
description, amount });
updateUI(data);
document.getElementById('transaction-form').reset();
} catch (error) {
console.error('Error adding transaction:', error);
document.getElementById('status').textContent = 'Error: Could not add
transaction.';
}
}
// Function
create server.js file
server.js
OUTPUT:
Solution :
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
package.js
{
"name": "10",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"express": "^5.1.0",
"sqlite3": "^5.1.7"
}
}
db.js
const sqlite3 = require('sqlite3').verbose();
// Function to initialize the database schema
function initializeDatabase() {
const db = new sqlite3.Database('./mydatabase.db', (err) => {
if (err) {
console.error(err.message);
} else {
console.log('Connected to the SQLite database.');
createStudentsTable(db);
}
});
// 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 });
});
});
// 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
10. Develop an express web application that can interact with REST
API to perform CRUD operations on student data. (Use Postman)
11.For the above application create authorized end points using JWT
(JSON Web Token).
Solution :
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
package.js
{
"name": "10",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"bcrypt": "^5.1.1",
"dotenv": "^16.5.0",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.2",
"sqlite3": "^5.1.7"
}
}
db.js
module.exports = { initializeDatabase };
app.js
// Use routes
app.use('/api/auth', authRoutes);
app.use('/api/students', studentRoutes);
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
Routes/auth.js
// Validate input
if (!username || !password) {
return res.status(400).json({message:'Username password required' });
}
if (user) {
return res.status(400).json({ message: 'User already exists' });
}
res.status(201).json({
message: 'User registered successfully',
token,
user: { id: this.lastID, username, role: userRole }
});
}
);
});
} catch (error) {
res.status(500).json({ message: error.message });
}
});
// Login user
router.post('/login', (req, res) => {
try {
const { username, password } = req.body;
// Validate input
if (!username || !password) {
return res.status(400).json({message:'Username password required' });
}
// Find user
db.get('SELECT * FROM users WHERE username = ?', [username], async (err,
user) => {
if (err) {
return res.status(500).json({ message: err.message });
}
if (!user) {
return res.status(400).json({message:'Invalid usernamepassword'});
}
// Check password
const validPassword = await bcrypt.compare(password, user.password);
if (!validPassword) {
return res.status(400).json({message:'Invaliduusernamepassword'});
}
res.json({
message: 'Login successful',
token,
user: { id: user.id, username: user.username, role: user.role }
});
});
} catch (error) {
res.status(500).json({ message: error.message });
}
});
module.exports = router;
Routes/students.js
// Validate input
if (!name || !age || !grade) {
return res.status(400).json({message:'Name, age, grade are required'});
}
// Validate input
if (!name || !age || !grade) {
return res.status(400).json({ message:'Name, age, grade are required'});
}
module.exports = router;
middleware/auth.js
next();
} catch (error) {
res.status(401).json({ message: 'Invalid token.' });
}
};
OUTPUT
POST http://localhost:3001/api/auth/register
Body:
"username": "admin",
"password": "admin123",
"role": "admin"
}
POST http://localhost:3001/api/auth/login
Body:
"username": "admin",
"password": "admin123"
3. Use the token returned from the login response in your Authorization header.
│
◆ Select a framework:
│ ● Vanilla
│ ○ Vue
│ ○ React
│ ○ Preact
│ ○ Lit
│ ○ Svelte
│ ○ Solid
│ ○ Qwik
│ ...
└
Select Vanilla
Select a variant:
│ ○ TypeScript
│ ● JavaScript
Select JavaScript
cd student-management-system
npm install
12>cd student-management-system
12/cd student-management-system>npm install [email protected]
12/cd student-management-system>npm install [email protected]
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Student Management System</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>
// C:\Users\rames\OneDrive\1.PEC\2-2\LabPrograms\12\src\pages\About.js
import React from 'react';
function About() {
return React.createElement('div', { className: 'container mt-5' },
React.createElement('h2', null, 'About Student Management System'),
React.createElement('div', { className: 'card mt-4' },
React.createElement('div', { className: 'card-body' },
React.createElement('h5', { className: 'card-title' }, 'Our Mission'),
React.createElement('p', { className: 'card-text' },
'The Student Management System is designed to streamline the process of
managing student information, ' +
'course registrations, and academic records. Our goal is to provide an
efficient and user-friendly ' +
'platform for both students and administrators.'
)
)
),
React.createElement('div', { className: 'card mt-4' },
React.createElement('div', { className: 'card-body' },
React.createElement('h5', { className: 'card-title' }, 'Features'),
React.createElement('ul', { className: 'list-group list-group-flush' },
React.createElement('li', { className: 'list-group-item' }, 'Student
Registration and Login'),
React.createElement('li', { className: 'list-group-item' }, 'Course
Management'),
React.createElement('li', { className: 'list-group-item' }, 'Grade
Tracking'),
React.createElement('li', { className: 'list-group-item' }, 'Attendance
Monitoring'),
React.createElement('li', { className: 'list-group-item' }, 'Performance
Analytics')
)
)
),
// C:\Users\rames\OneDrive\1.PEC\2-2\LabPrograms\12\src\pages\Register.js
import React, { useState } from 'react';
function Register() {
const [formData, setFormData] = useState({
name: '',
email: '',
password: '',
confirmPassword: '',
studentId: ''
});
In Browser
http://localhost:5173/
http://localhost:5173/register
http://localhost:5173/login
http://localhost:5173/about
http://localhost:5173/contact
Step 1: Create an OpenWeatherMap Account and Generate API Key
cd weather-app
Step 3: Install required packages
In the project directory, install the necessary packages by executing the following command
We will use the Axios library to make HTTP requests to the OpenWeatherMap API.
Inside the "src" directory, create a new file called "Weather.js" and open it in your code
editor.
Add the following code to define a functional component named Weather:
Weather.js
return (
<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}</p>
<p>Wind Speed : {weatherData.wind.speed}m/s</p>
</>
) : (
<p>Loading weather data...</p>
)}
</div>
);
};
cd todo-app
In the project directory, install the necessary packages by executing the following command
npm install
We will use the Axios library to make HTTP requests to the OpenWeatherMap API.
{
"name": "todo-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
App.css
.App {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: #f5f5f5;
}
.todo-container {
background-color: white;
padding: 2rem;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
width: 100%;
max-width: 500px;
}
h1 {
text-align: center;
color: #333;
margin-bottom: 2rem;
}
.todo-form {
display: flex;
gap: 1rem;
margin-bottom: 2rem;
}
.todo-input {
flex: 1;
padding: 0.5rem;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 1rem;
}
.todo-button {
padding: 0.5rem 1rem;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 1rem;
}
.todo-button:hover {
background-color: #45a049;
}
.todo-list {
list-style: none;
padding: 0;
margin: 0;
}
.todo-item {
display: flex;
align-items: center;
gap: 1rem;
padding: 0.5rem;
border-bottom: 1px solid #eee;
}
.todo-item:last-child {
border-bottom: none;
}
.todo-item input[type="checkbox"] {
margin-right: 0.5rem;
}
.todo-item span {
flex: 1;
}
.delete-button {
padding: 0.25rem 0.5rem;
background-color: #ff4444;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.delete-button:hover {
background-color: #cc0000; }
App.js
function App() {
const [todos, setTodos] = useState([]);
return (
<div className="App">
<div className="todo-container">
<h1>Todo List</h1>
<TodoForm onSubmit={addTodo} />
<TodoList
todos={todos}
onToggle={toggleTodo}
onDelete={deleteTodo}
/>
</div>
</div>
);
}
index.css
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
index.js
src/omponents/TodoForm.js
return (
<form onSubmit={handleSubmit} className="todo-form">
<input
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Add a new todo..."
className="todo-input"
/>
<button type="submit" className="todo-button">
Add
</button>
</form>
);
}
export default TodoForm;
src/components/TodoList.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Todo List Application created using React"
/>
<title>Todo List App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
After saving
Prerequisites
Before proceeding, ensure you have the following:
Conclusion
Your project is now successfully uploaded to GitHub. You can view it by navigating to your
repository URL in a web browser. Git allows you to track changes, collaborate, and manage
project history efficiently.
Next Steps
Clone your repository on another machine: git clone
https://github.com/yourusername/repository.git
Make and push changes:
git add .
git commit -m "Updated feature"
git push origin main
Pull the latest changes from GitHub:
git pull origin main