0% found this document useful (0 votes)
17 views50 pages

SD-LAB-MANUAL

Software development manual

Uploaded by

Krish Rock
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views50 pages

SD-LAB-MANUAL

Software development manual

Uploaded by

Krish Rock
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

CMR College of Engineering & Technology

Kandlakoya(v), Medchal Road Hyderabad, Telangana, India - 501401,


Telephone: 08418 - 200699. Email: info@cmrcet.ac.in.

SKILL DEVELOPMENT LABORATORY (NODE


JS/REACT JS/DJANGO)
B.TECH: III YEAR – I SEMESTER (2024-2025)

PREPARED BY
V. NARASIMHA
ASST.PROF

1
Vision
Our Vision is to remain a premier academic institution striving continuously for
excellence in technical education, research and render technological services to the
nation.

Mission
• Our Mission is to create and sustain a community of learning in which students
acquire knowledge and learn to apply it professionally with a concern for the
society.
• Pursue and Disseminate Research Findings and Offer Knowledge-Based
Technological Services to Satisfy the Needs of Society and the Industry.
• Promote Professional Ethics, Leadership Qualities and Social Responsibilities.

Vision of the Department

• To evolve as a centre of academic excellence in Computer Science &


Engineering by building strong teaching and research environment.

Mission of the Department

• To offer high quality graduate and post graduate programs in computerscience


education and to prepare students for professional career and/orhigher studies
globally.
• To develop self learning abilities and professional ethics to serve thesociety.

2
Program Educational Objectives (PEOs)

PEO I: Excel in their professional career and higher education in Computer Science &
Engineering and chosen fields.

Demonstrate leadership qualities, team work and professional ethics to serve the
PEO II: society

Adapt to state of art technology through continuous learning


PEO III: in the areas of interest.

3
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CMR College of Engineering & Technology


Kandlakoya(v), Medchal Road Hyderabad, Telangana, India - 501401,
Telephone: 08418 - 200699. Email: info@cmrcet.ac.in.
(A405513) SKILL DEVELOPMENT LABORATORY (NODE JS/REACT
JS/DJANGO)

Course Outcomes
1. Build a custom website with HTML, CSS, Bootstrap, and little JavaScript.
2. Demonstrate Advanced features of JavaScript and learn about JDBC
3. Develop Server – side implementation using Java technologies like
4. Develop the server–side implementation using Node JS.
5. Design a single-page application using React.

CO & PO Mapping
CO \ PO PO1 PO PO3 PO PO5 PO6 PO7 PO PO9 PO10 PO11 PO12 PSO1 PSO2
Mapping 2 4 8
CO1 1 2 3 2 1 2
CO2 2 2 2 3 3 2 1 2 2 2
CO3 2 2 3 3 3 2 3 2 2 2 2 2
CO4 2 2 3 3 3 2 2 2 2 2 2
CO5 2 2 2 3 3 3 2 2

4
LAB Exercises:
1. Build a responsive web application for shopping carts with registration, login, catalog and
cart pages using CSS3 features, flex and grid.
2. Make the above web application responsive web application using Bootstrap framework.
3. Use JavaScript for doing client – side validation of the pages implemented in experiment
1 and experiment 2.
4. Explore the features of ES6 like arrow functions, callbacks, 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.
5. Develop a java standalone application that connects with the database (Oracle / mySql)
and performs the CRUD operation on the database tables.
6. Create an xml for the bookstore. Validate the same using both DTD and XSD.
7. Design a controller with servlet that provides the interaction with application developed in
experiment 1 and the database created in experiment 5.
8. Maintaining the transactional history of any user is very important. Explore the various
session tracking mechanism (Cookies, HTTP Session)
9. Create a custom server using http module and explore the other modules of Node JS like
OS, path, event.
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).
12. Create a react application for the student management system having registration, login,
contact, about pages and implement routing to navigate through these pages.
13. Create a service in react that fetches the weather information from openweathermap.org
and the display the current and historical weather information using graphical
representation using chart.js.
14. Create a TODO application in react with necessary components and deploy it into
GitHub.

REFERENCE BOOKS

1. Jon Duckett, Beginning HTML, XHTML, CSS, and JavaScript, Wrox Publications,2010 .
2. Bryan Basham, Kathy Sierra and Bert Bates, Head First Servlets and JSP, O’Reilly
Media, 2nd Edition, 2008.
3. Vasan Subramanian, Pro MERN Stack, Full Stack Web App Development with Mongo,
Express, React, and Node, 2nd Edition, A Press.

5
LAB MANUAL

1. Build a responsive web application for shopping carts with registration, login,
catalog and cart pages using CSS3 features, flex and grid.

Structure of program
shopping-cart-app/
├── index.html
├── styles/
│ ├── style.css
├── scripts/
│ ├── app.js

index.html

<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="./style.css">
<title>Home - FBS</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="fbs.png" alt="FBS LOGO" width="130"
height="100"/></th>
<th colspan=4>
<h1 style="color:white;">FBS - 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>

6
</nav>
</div>
<div class="container1">
<div class="sidebar1"></div>
<div class="container2">
<main>
<center>
<h2>Welcome to FBS e-Book's Website</h2>
<p>Shopping at <font size=5>FBS</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 FBS ebooks</font></footer>
</div>
</body>
</html>

login.html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="./style.css">
<title>Login - FBS</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="fbs.png" alt="FBS LOGO" width="130"
height="100"/></th>
<th colspan=4>
<h1 style="color:white;">FBS - WORLD BEST ONLINE EBOOKS WEBSITE</h1>
</th>
</tr>
</table>
</header>
<nav>
<table width="100%" align="center" cellpadding="0" cellspacing="2">

7
<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 FBS ebooks</font></footer>
</div>
</body>
</html>

Registration.html

8
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="./style.css">
<title>Registration - FBS</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="fbs.png" alt="FBS LOGO" width="130"
height="100"/></th>
<th colspan=4>
<h1 style="color:white;">FBS - 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>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>

9
<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 &nbsp;&nbsp;
<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 FBS ebooks</font></footer>
</div>
</body>
</html>

Cart.html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="./style.css">
<title>Cart - FBS</title>
</head>
<body>
<div class="wrapper">
<div class="container">
<header>
<table width="100%" align="center" cellpadding="0" cellspacing="2">
<tr>

10
<th width="20%"><img src="fbs.png" alt="FBS LOGO" width="130"
height="100"/></th>
<th colspan=4>
<h1 style="color:white;">FBS - 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>
<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>

11
<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 FBS ebooks</font></footer>
</div>
</body>
</html>

CSS Styling
styles/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;

12
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;
}

header, nav, main, .sidebar1, .sidebar2, footer{


display: flex;
align-items: center;
justify-content: center;
border-radius: 10px;
}

.wrapper {
display: flex;
flex-direction: column;
font-weight: 600;
}

JavaScript Functionality.
scripts/app.js

document.addEventListener('DOMContentLoaded', () => {
// Add your JavaScript here
// For example, you can handle form submissions and cart interactions
});

Output

13
Experment 2:
Make the above web application responsive web application using Bootstrap framework.
Index.html

(add this code to above index.html experiment-1)


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shopping Cart App</title>
<!-- Bootstrap CSS -->
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
rel="stylesheet">
<link rel="stylesheet" href="styles/style.css">
</head>
<body>
<!-- Add your content here -->
<!-- Bootstrap JS and dependencies -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="scripts/app.js"></script>

14
</body>
</html>
Experiment-3
Use JavaScript for doing client – side validation of the pages implemented in the
experiment

Client - Side validation of Registration Page


registrationJS.html
<html>
<head>
<title> Welcome to NNRG e-Book's website</title>
<script language="javascript">
function validate() {
// username validation
var uname = f1.username.value;
if (uname.length<=0)
{
alert("Please Enter UserName");
f1.username.focus();
return false;
}
if (uname.length < 8)
{
alert("Please enter UserName not less than 8");
f1.username.focus();
return false;
}
//password validation
var pwd = f1.password.value;
if (pwd.length<=0)
{
alert("Please Enter password");
f1.password.focus();
return false;
}
if (pwd.length < 6)
{
alert("Please enter Password not less than 6");
f1.password.focus();
return false;
}
// email validation
var email = f1.email.value;
if (email.length<=0)
{
alert("Please Enter email");

15
f1.email.focus();
return false;
}
else {
let eflag=false;
for(i=0;i<email.length;i++) {
if(email.charAt(i)=="@")
{
eflag=true;
}
}
if(!(eflag))
{
alert("Please enter a valid Email ID");
f1.email.focus();
return false;
}
}
// phone number validation
var phno = f1.phno.value;
if (phno.length<=0)
{
alert("Please Enter Phone Number");
f1.phno.focus();
return false;
}
if (isNaN(phno))
{
alert("Please Enter Valid Phone Number");
f1.phno.focus();
return false;
}
if (phno.length != 10)
{
alert("Please Enter Valid Phone Number");
f1.phno.focus();
return false;
}
// gender validation
let flag=false;
for(i=0;i<f1.gen.length;i++)
if(f1.gen[i].checked)
flag=true;
if(!(flag))
{
alert("Please choose a Gender");

16
return false;
}
// Language validation
flag=false;
for(i=0;i<f1.lang.length;i++)
if(f1.lang[i].checked)
flag=true;
if(!(flag))
{
alert("Please select at least one of the Language options.");
return false;
}
// address validation
var addr = f1.address.value;
if (addr.length<=0)
{
alert("Please Enter address");
f1.address.focus();
return false;
}
// to display Success message
alert("Registration Successful");
}
</script>
</head>
<body>
<center><br>
<h3>Registration Form </h3>
<br/>
<form name="f1">
<table cellpadding="1" align="center" >
<tr><td> User 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="gen" value="Male">Male &nbsp;&nbsp;
<input type="radio" name="gen" value="Female">Female</td></tr>
<tr> <td valign="top">Language Known:*</td>
<td> <input type="checkbox" name="lang" value="English">English<br/>
<input type="checkbox" name="lang" value="Telugu">Telugu<br>
<input type="checkbox" name="lang" value="Hindi">Hindi<br>

17
<input type="checkbox" name="lang" value="Tamil">Tamil
</td></tr>
<tr> <td valign="top">Address:*</td>
<td><textarea name="address"></textarea></td>
<tr><td></td><td><input type="button" value="SUBMIT" hspace="10" onclick="validate()">
<input type="reset" value="RESET"></td></tr>
<tr> <td colspan=2 >*<font color="#FF0000">fields are mandatory</font>
</td>
</tr>
</table>
</form>
</center>
</body>
</html>

4. Explore the features of ES6 like arrow functions, callbacks, 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..

Arrow Functions: more concise syntax for writing functions

18
const add = (a, b) => a + b;
Callbacks:
• Functions passed as arguments to other functions and executed once a task is completed.
• Often used for asynchronous operations like reading files, making network requests, etc
function fetchData(callback) {
// Simulate a data fetch
setTimeout(() => {
const data = { temperature: 25 };
callback(data);
}, 1000);
}

fetchData((data) => {
console.log(data.temperature); // 25
});

Output

25

Promises:
• Objects representing the eventual completion (or failure) of an asynchronous operation.
• Allow chaining of asynchronous operations using .then() and handling errors with
.catch().

const fetchData = () => {


return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ temperature: 25 });
}, 1000);
});
};

fetchData().then(data => {
console.log(data.temperature); // 25
}).catch(error => {
console.error(error);
});

Output
25

Async/Await:
• A syntactic sugar built on top of Promises that allows writing asynchronous code that
looks synchronous.
• Makes the code easier to read and maintain.

19
const fetchData = async () => {
const response = await fetch('https://api.example.com/weather');
const data = await response.json();
console.log(data.temperature);
};

fetchData();
output

Building the Weather Application


To build a simple web application that fetches weather data from OpenWeatherMap and
displays it as a graph, follow these steps:

Index.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>Weather Graph</title> </head>
<body>
<div class="container"> <h1>Weather Graph</h1> <canvas id="weatherGraph"
width="400"
height="200"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script
src="script.js"></script>
</body>
</html>
</html>

Styles.css
body
{
font-family: 'Arial', sans-serif; margin: 0; padding: 0; background-color: #f4f4f4;
}
.container { max-width: 600px; margin: 50px auto; background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1 {
text-align: center;

20
}
canvas {
display: block;
margin: 20px auto;
}

script.js

document.add EventListener('DOMContentLoaded', () =>


{ const apiKey = 'YOUR_OPENWEATHERMAP_API_KEY';
const city = 'YOUR_CITY_NAME'; const apiUrl =
`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=
metric`;
const fetchData = async () => { try { const response = await axios.get(apiUrl);
const weatherData = response.data; updateGraph(weatherData.main.temp);
} catch (error) {
console.error('Error fetching weather data:', error.message);
} };
const updateGraph =
(temperature) => { const ctx =
document.getElementById('weatherGraph').getContext('2d');
new Chart(ctx, { type: 'bar', data: { labels: ['Temperature'], datasets: [{
label: 'Temperature (°C)', data: [temperature], backgroundColor: ['#36A2EB'], }],
}, options: { scales: { y: { begin At Zero: true, }, }, }, }); };
fetchData();
});

output:

21
5. Develop a java standalone application that connects with the database (Oracle /
mySql) and performs the CRUD operation on the database tables

import java.sql.*;
public class CRUDExample {
// JDBC URL, username, and password of MySQL server
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/Narasimha";
private static final String USERNAME = "Tiger";
private static final String PASSWORD = "chinna";
public static void main(String[] args) {
try {
// Step 1: Establishing a connection
Connection connection = DriverManager.getConnection(JDBC_URL, USERNAME,
PASSWORD);
// Step 2: Creating a statement
Statement statement = connection.createStatement();
// Step 3: Performing CRUD operations
createRecord(statement, "Happy junnu", 50000);
readRecords(statement);
updateRecord(statement, 1, "Happy Updated", 55000);
readRecords(statement);
deleteRecord(statement, 1);
readRecords(statement);
// Step 4: Closing resources
statement.close();
connection.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
// Create a new record in the database
private static void createRecord(Statement statement, String name, int salary) throws
SQLException {
String insertQuery = "INSERT INTO employees (name, salary) VALUES ('" +
name + "', " + salary + ")";
statement.executeUpdate(insertQuery);
System.out.println("Record created successfully.");
}
// Read all records from the database
private static void readRecords(Statement statement) throws SQLException {
String selectQuery = "SELECT * FROM employees";
ResultSet
resultSet = statement.executeQuery(selectQuery);
System.out.println("ID\tName\tSalary");
while (resultSet.next()) {

22
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int salary = resultSet.getInt("salary");
System.out.println(id + "\t" + name + "\t" + salary);
}
System.out.println();
}
// Update a record in the database
private static void updateRecord(Statement statement, int id, String newName, int
newSalary)
throws SQLException {
String updateQuery = "UPDATE employees SET name = '" + newName + "', salary = " +
newSalary + " WHERE id = " + id;
statement.executeUpdate(updateQuery);
System.out.println("Record updated successfully.");
}
// Delete a record from the database
private static void deleteRecord(Statement statement, int id) throws SQLException {
String
deleteQuery = "DELETE FROM employees WHERE id = " + id;
statement.executeUpdate(deleteQuery);
System.out.println("Record deleted successfully."); }}

Explanation:
1. Connection Parameters: Replace your_database, your_username, and
your_password withyour actual database name, username, and password.
2. JDBC Connection:
The getConnection method is used to establish a connection to the MySQL
database.
3. CRUD Operations:
createRecord: Inserts a new record into the database.
readRecords: Reads and prints all records from the database.
updateRecord: Updates a record in the database.
deleteRecord: Deletes a record from the database.
4. Output: The application prints the records before and after each operation, showing
the CRUD operations in action.
Output:
When you run this Java application, you should see output similar to the following in
the console:

23
6. Create an xml for the bookstore. Validate the same using both DTD and XSD.

Bookstore XML File (bookstore.xml):

<!ELEMENT bookstore (book+)>


<!ELEMENT book (title, author, price)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT price (#PCDATA)>
XSD File (bookstore.xsd):

<?xml version="1.0" encoding="UTF-8"?>


<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="bookstore" type="bookstoreType"/>
<xs:complexType name="bookstoreType">
<xs:sequence>
<xs:element
name="book"
type="bookType"
minOccurs="0"
maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>

24
<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>

XMLValidator.java

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.SAXException;
public class XMLValidator {
public static void main(String[] args) {
validateWithDTD("bookstore.xml", "bookstore.dtd");
validateWithXSD("bookstore.xml", "bookstore.xsd");
}
private static void validateWithDTD(String xmlFile, String dtdFile) {
try {
InputStream xmlStream = new FileInputStream(new File(xmlFile));
InputStream dtdStream = new FileInputStream(new File(dtdFile));
SchemaFactory schemaFactory =
SchemaFactory.newInstance(XMLConstants.XML_DTD_NS_URI);
Schema schema = schemaFactory.newSchema(new StreamSource(dtdStream));
Validator validator = schema.newValidator();
validator.validate(new StreamSource(xmlStream));
System.out.println("Validation with DTD successful.");
} catch (SAXException | IOException e) {
System.out.println("Validation with DTD failed. Reason: " + e.getMessage());
}
}
private static void validateWithXSD(String xmlFile, String xsdFile)
{
try {
InputStream xmlStream = new FileInputStream(new File(xmlFile));
InputStream xsdStream = new FileInputStream(new File(xsdFile));
SchemaFactory schemaFactory =

25
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(new StreamSource(xsdStream));
Validator validator = schema.newValidator();
validator.validate(new StreamSource(xmlStream));
System.out.println("Validation with XSD successful.");
}
catch (SAXException | IOException e) {
System.out.println("Validation with XSD failed. Reason: " + e.getMessage());
}
}
}

Output:
If the XML file adheres to the specified DTD and XSD, you will see output messages
like: Validation with DTD successful.
Validation with XSD successful.
7. Design a controller with servlet that provides the interaction with application
developed in experiment 1 and the database created in experiment 5

Servlet Controller (ShoppingCartController.java):


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ShoppingCartController") public class ShoppingCartController extends
HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
String action = request.getParameter("action");
if (action != null) {
switch (action) {
case "register":
handleRegistration(request, response);
break;
case "login":
handleLogin(request, response);
break;
case "addToCart":
handleAddToCart(request, response);
break;
// Add more cases for other actions as needed
default:
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid action");
}

26
}
else {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Action parameter
missing");
}
}
private void handleRegistration(HttpServletRequest request, HttpServletResponse
response)
throws IOException {
// Extract registration data from request
String username = request.getParameter("username");
String password = request.getParameter("password");
// Perform registration logic (e.g., insert data into the database)
// Send response to the client
PrintWriter out = response.getWriter();
out.println("Registration successful"); }
private void handleLogin(HttpServletRequest request, HttpServletResponse response)
throws IOException
{
// Extract login data from request
String username = request.getParameter("username");
String password = request.getParameter("password");
// Perform login logic (e.g., check credentials against the database)
// Send response to the client
PrintWriter out = response.getWriter();
out.println("Login successful"); }
private void handleAddToCart(HttpServletRequest request, HttpServletResponse
response)
throws IOException {
// Extract cart data from request
String productId = request.getParameter("productId");
// Additional parameters as needed
// Perform logic to add the product to the user's cart (e.g., update database)
// Send response to the client
PrintWriter out = response.getWriter();
out.println("Product added to cart");
}
// Add more methods for other actions as needed
}
Explanation:
1. Servlet Annotation (@WebServlet("/ShoppingCartController")):
This annotation maps the servlet to the specified URL pattern.
2. doPost Method: Handles HTTP POST requests. It checks the value of the "action"
parameter in the request and calls the appropriate method based on the action.
3. Action Methods (handleRegistration, handleLogin, handleAddToCart):
Each method handles a specific action requested by the client. It extracts data from

27
the request, performs the necessary logic (e.g., database operations), and sends a
response back to the client.
4. Error Handling: The controller checks for invalid actions or missing parameters
and sends an error response if necessary.
Note: This example assumes that the web application sends HTTP POST requests to
the servlet with an "action" parameter to specify the desired operation.
Ensure that your web application sends requests to the correct URL pattern, in this
case, "/ShoppingCartController".Make sure to handle exceptions properly, and
consider using a connection pool for database connections in a production
environment.
This is a basic outline, and depending on your specific application requirements, you
may need to expand and customize these methods accordingly.
8. Maintaining the transactional history of any user is very important. Explore the
various session tracking mechanism (Cookies, HTTP Session)

AIM: Maintaining the transactional history of any user is very important. Explore the
various session tracking mechanism (Cookies, HTTP Session)
DESCRIPTION:
Session tracking mechanisms are crucial for maintaining the state of a user's
interactions with a web application. Two common methods for session tracking are
Cookies and HTTP Sessions.
1. Cookies: Cookies are small data pieces stored on a user's device by a web browser,
used to maintain user-specific information between the client and the server.
Example: Suppose you want to track the user's language preference.
Server-side (in a web server script, e.g., in Python with Flask):
from flask import Flask, request, render_template, make_response
app = Flask(__name__)
@app.route('/')
def index():
# Check if the language cookie is set
user_language = request.cookies.get('user_language')
return
render_template('index.html',user_language=user_language)
@app.route('/set_language/<language>')
def set_language(language):
# Set the language preference in a cookie
response = make_response(render_template('set_language.html'))
response.set_cookie('user_language', language)
return response
if __name__ == '__main__':
app.run(debug=True)
HTML Templates (index.html and set_language.html):
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>

28
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cookie Example</title>
</head>
<body>
<h1>Welcome to the website!</h1>
{% if user_language %}
<p>Your preferred language is: {{ user_language }}</p>
{% else %}
<p>Your language preference is not set.</p>
{% endif %}
<p><a href="/set_language/en">Set language to English</a></p>
<p><a href="/set_language/es">Set language to Spanish</a></p>
</body>
</html>
<!-- set_language.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Set Language</title>
</head>
<body>
<h2>Language set successfully!</h2>
<p><a href="/">Go back to the home page</a></p>
</body>
</html>

Output:
When a user visits the site for the first time, the language preference is not set. When the
user clicks on
"Set language to English" or "Set language to Spanish," the preference is stored in a
cookie.
On subsequent visits, the site recognizes the user's language preference based on the
cookie.
2. HTTP Session: An HTTP session is a way to store information on the server side
between requests from
the same client. Each client gets a unique session ID, which is used to retrieve session
data.
Example: Suppose you want to track the number of visits for each user. Server-side (in a
web server
script, e.g., in Python with Flask):
from flask import Flask, request, render_template, session
app = Flask(__name__)
app.secret_key = 'super_secret_key'

29
# Set a secret key for session management
@app.route('/')
def index():
# Increment the visit count in the session
session['visit_count'] = session.get('visit_count', 0) + 1
return render_template('index_session.html', visit_count=session['visit_count'])
if __name__ == '__main__':
app.run(debug=True)
HTML Template (index_session.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Session Example</title>
</head>
<body>
<h1>Welcome to the website!</h1>
<p>This is your visit number: {{ visit_count }}</p>
</body>
</html>
Output:
Each time a user visits the site, the server increments the visit count stored in the session.
The visit count is unique to each user and persists across multiple requests until the
session expires.
These examples demonstrate simple use cases for cookies and HTTP sessions to maintain
user-specific
information on the client and server sides, respectively.
9. Create a custom server using http module and explore the other modules of Node JS
like OS, path, event.

AIM: Create a custom server using http module and explore the other modules of Node
JS like OS, path,
event
DESCRIPTION: Let's create a simple custom server using the http module in Node.js
and then explore
the os, path, and events modules with examples.
1. Creating a Custom Server with http Module:
Server-side (server.js):
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'
});
res.end('Hello, this is a custom server!');});
const PORT = 3000;server.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);});

30
To run the server: node server.js
Output:
Visit http://localhost:3000 in your browser or use a tool like curl or Postman to make a
request, and you
should see the response "Hello, this is a custom server!".
2. Exploring Node.js Modules:
A. os Module:
The os module provides operating system-related utility methods and properties.
Example:
const os = require('os');
console.log('OS Platform:', os.platform());
console.log('OS Architecture:', os.arch());
console.log('Total Memory (in bytes):', os.totalmem());
console.log('Free Memory (in bytes):', os.freemem());
Output:
This will output information about the operating system platform, architecture, total
memory,
and free memory.
B. path Module:
The path module provides methods for working with file and directory paths.
Example:
const path = require('path');
const filePath = '/path/to/some/file.txt';
console.log('File Name:', path.basename(filePath));
console.log('Directory Name:', path.dirname(filePath));
console.log('File Extension:', path.extname(filePath));
Output: This will output the file name, directory name, and file extension for the given
file path.
C. events Module:
The events module provides an implementation of the Event Emitter pattern, allowing
objects to emit and
listen for events.
Example:
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();

10. Develop an express web application that can interact with REST API to perform
CRUD operations on student data. (Use Postman).
Explanation: To create express web application first create a directory and inside folder
write in command promt
1. npm init -y
2. npm install express body-parser nodemon
example structure
student-api/
├── index.js # Entry point

31
├── routes/
│ └── student.js # Student routes
└── data/
└── students.json # Temporary student data storage
Step1. Create Json file and save that file data/students.json
[
{ "id": 1, "name": "Junnu", "age": 20, "grade": "A" },
{ "id": 2, "name": "Bharath", "age": 22, "grade": "B" }
]

Step2: create express server


const express = require('express');
const bodyParser = require('body-parser');
const studentRoutes = require('./routes/student');

const app = express();


const PORT = 3000;

app.use(bodyParser.json()); // Parse JSON bodies


app.use('/api/students', studentRoutes); // Use student routes

app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});

Step3: define CRUD operation in routes/student.js


const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');

const dataPath = path.join(__dirname, '../data/students.json');

// Helper function to read student data


function getStudentData() {
const jsonData = fs.readFileSync(dataPath);
return JSON.parse(jsonData);
}

// Helper function to save student data


function saveStudentData(data) {
fs.writeFileSync(dataPath, JSON.stringify(data, null, 2));
}

// GET all students


router.get('/', (req, res) => {

32
const students = getStudentData();
res.status(200).json(students);
});

// GET student by ID
router.get('/:id', (req, res) => {
const students = getStudentData();
const student = students.find(s => s.id === parseInt(req.params.id));
if (student) {
res.status(200).json(student);
} else {
res.status(404).json({ message: "Student not found" });
}
});

// CREATE a new student


router.post('/', (req, res) => {
const students = getStudentData();
const newStudent = { id: students.length + 1, ...req.body };
students.push(newStudent);
saveStudentData(students);
res.status(201).json(newStudent);
});

// UPDATE a student
router.put('/:id', (req, res) => {
const students = getStudentData();
const studentIndex = students.findIndex(s => s.id === parseInt(req.params.id));
if (studentIndex !== -1) {
students[studentIndex] = { id: parseInt(req.params.id), ...req.body };
saveStudentData(students);
res.status(200).json(students[studentIndex]);
} else {
res.status(404).json({ message: "Student not found" });
}
});

// DELETE a student
router.delete('/:id', (req, res) => {
let students = getStudentData();
const studentIndex = students.findIndex(s => s.id === parseInt(req.params.id));
if (studentIndex !== -1) {
students = students.filter(s => s.id !== parseInt(req.params.id));
saveStudentData(students);
res.status(200).json({ message: "Student deleted successfully" });
} else {

33
res.status(404).json({ message: "Student not found" });
}
});

module.exports = router;

Step 4: Test with Postman


1. Start the Server:
bash

nodemon index.js
2. Test in Postman:
o GET all students: GET http://localhost:3000/api/students
o GET a specific student by ID: GET http://localhost:3000/api/students/1
o POST a new student: POST http://localhost:3000/api/students
▪ Body (JSON):

{
"name": "Alice Brown",
"age": 21,
"grade": "A"
}
o PUT to update a student: PUT http://localhost:3000/api/students/1
▪ Body (JSON):
json

{
"name": "John Doe",
"age": 21,
"grade": "A+"
}
o DELETE a student: DELETE http://localhost:3000/api/students/1

11. For the above application create authorized end points using JWT (JSON Web
Token).

Step 1: Install Additional Dependencies


1. Install JWT and bcrypt:
bash

npm install jsonwebtoken bcryptjs


2. Directory Structure (updated):
bash

student-api/

34
├── index.js # Entry point
├── routes/
│ ├── auth.js # Authentication routes
│ └── student.js # Student routes
├── middleware/
│ └── authMiddleware.js # JWT authorization middleware
└── data/
├── students.json # Student data storage
└── users.json # User data storage
3. Create Dummy Users Data File:
In the data/ folder, create a users.json file to temporarily store registered users.
data/users.json:
json

[
{ "id": 1, "username": "admin", "password": "$2a$10$hashed" } // Password is hashed
]
Note: Use bcrypt to hash passwords in a real application.
Step 2: Create the Authentication Middleware
middleware/authMiddleware.js:
javascript

const jwt = require('jsonwebtoken');


const SECRET_KEY = 'your-secret-key';

// Middleware to protect routes


function authenticateToken(req, res, next) {
const token = req.headers['authorization']?.split(' ')[1];
if (!token) return res.status(401).json({ message: 'Access token is missing' });

jwt.verify(token, SECRET_KEY, (err, user) => {


if (err) return res.status(403).json({ message: 'Token is not valid' });
req.user = user; // Attach user data to request
next();
});
}

module.exports = authenticateToken;
Step 3: Create Authentication Routes (Login and Register)
routes/auth.js:
javascript

const express = require('express');


const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const fs = require('fs');

35
const path = require('path');

const router = express.Router();


const SECRET_KEY = 'your-secret-key';
const dataPath = path.join(__dirname, '../data/users.json');

// Helper functions to manage users


function getUserData() {
const jsonData = fs.readFileSync(dataPath);
return JSON.parse(jsonData);
}

function saveUserData(data) {
fs.writeFileSync(dataPath, JSON.stringify(data, null, 2));
}

// Register a new user


router.post('/register', async (req, res) => {
const { username, password } = req.body;
const users = getUserData();

const existingUser = users.find(user => user.username === username);


if (existingUser) return res.status(409).json({ message: 'Username already exists' });

const hashedPassword = await bcrypt.hash(password, 10);


const newUser = { id: users.length + 1, username, password: hashedPassword };
users.push(newUser);
saveUserData(users);

res.status(201).json({ message: 'User registered successfully' });


});

// Login a user
router.post('/login', async (req, res) => {
const { username, password } = req.body;
const users = getUserData();

const user = users.find(user => user.username === username);


if (!user) return res.status(404).json({ message: 'User not found' });

const isPasswordValid = await bcrypt.compare(password, user.password);


if (!isPasswordValid) return res.status(401).json({ message: 'Invalid credentials' });

const token = jwt.sign({ id: user.id, username: user.username }, SECRET_KEY, {


expiresIn: '1h' });
res.status(200).json({ token });

36
});

module.exports = router;
Step 4: Secure the Student Routes
Update routes/student.js to use the authenticateToken middleware on each route.
routes/student.js:
javascript

const express = require('express');


const router = express.Router();
const fs = require('fs');
const path = require('path');
const authenticateToken = require('../middleware/authMiddleware');

const dataPath = path.join(__dirname, '../data/students.json');

function getStudentData() {
const jsonData = fs.readFileSync(dataPath);
return JSON.parse(jsonData);
}

function saveStudentData(data) {
fs.writeFileSync(dataPath, JSON.stringify(data, null, 2));
}

// GET all students


router.get('/', authenticateToken, (req, res) => {
const students = getStudentData();
res.status(200).json(students);
});

// GET student by ID
router.get('/:id', authenticateToken, (req, res) => {
const students = getStudentData();
const student = students.find(s => s.id === parseInt(req.params.id));
if (student) {
res.status(200).json(student);
} else {
res.status(404).json({ message: "Student not found" });
}
});

// CREATE a new student


router.post('/', authenticateToken, (req, res) => {
const students = getStudentData();
const newStudent = { id: students.length + 1, ...req.body };

37
students.push(newStudent);
saveStudentData(students);
res.status(201).json(newStudent);
});

// UPDATE a student
router.put('/:id', authenticateToken, (req, res) => {
const students = getStudentData();
const studentIndex = students.findIndex(s => s.id === parseInt(req.params.id));
if (studentIndex !== -1) {
students[studentIndex] = { id: parseInt(req.params.id), ...req.body };
saveStudentData(students);
res.status(200).json(students[studentIndex]);
} else {
res.status(404).json({ message: "Student not found" });
}
});

// DELETE a student
router.delete('/:id', authenticateToken, (req, res) => {
let students = getStudentData();
const studentIndex = students.findIndex(s => s.id === parseInt(req.params.id));
if (studentIndex !== -1) {
students = students.filter(s => s.id !== parseInt(req.params.id));
saveStudentData(students);
res.status(200).json({ message: "Student deleted successfully" });
} else {
res.status(404).json({ message: "Student not found" });
}
});

module.exports = router;
Step 5: Update index.js to Use Auth Routes
index.js:
javascript

const express = require('express');


const bodyParser = require('body-parser');
const studentRoutes = require('./routes/student');
const authRoutes = require('./routes/auth');

const app = express();


const PORT = 3000;

app.use(bodyParser.json());
app.use('/api/auth', authRoutes); // Authentication routes

38
app.use('/api/students', studentRoutes); // Secured student routes

app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Step 6: Test with Postman
1. Register a user:
o POST: http://localhost:3000/api/auth/register
o Body (JSON):
json

{
"username": "testuser",
"password": "testpassword"
}
2. Login to get a token:
o POST: http://localhost:3000/api/auth/login
o Body (JSON):
json

{
"username": "testuser",
"password": "testpassword"
}
o The response will contain a JWT token.
3. Access Secured Endpoints:
o Copy the token received from the login response.
o In Postman, for each secured student route (/api/students), set the Authorization
header:
▪ Authorization: Bearer <your_token_here>
Now the application is secured using JWT, allowing only authenticated users to perform
CRUD operations on student data.
12. Create a react application for the student management system having registration,
login, contact, about pages and implement routing to navigate through these pages.
Step 1: Set Up the React Project
1. Create a new React project:
bash

npx create-react-app student-management


cd student-management
2. Install dependencies for routing:
bash

npm install react-router-dom


3. Project Structure:
bash

39
student-management/
├── public/
├── src/
│ ├── components/
│ │ ├── Login.js
│ │ ├── Register.js
│ │ ├── Contact.js
│ │ ├── About.js
│ │ └── Navbar.js
│ ├── App.js
│ └── index.js
└── package.json
Step 2: Set Up Routing and Basic Pages
App.js - Main Application Component with Routing
javascript

import React from 'react';


import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Navbar from './components/Navbar';
import Login from './components/Login';
import Register from './components/Register';
import Contact from './components/Contact';
import About from './components/About';

function App() {
return (
<Router>
<Navbar />
<div className="container">
<Routes>
<Route path="/" element={<Login />} />
<Route path="/register" element={<Register />} />
<Route path="/contact" element={<Contact />} />
<Route path="/about" element={<About />} />
</Routes>
</div>
</Router>
);
}

export default App;


Step 3: Create the Navbar Component
components/Navbar.js - Navigation Bar
javascript

40
import React from 'react';
import { Link } from 'react-router-dom';

const Navbar = () => {


return (
<nav>
<ul>
<li><Link to="/">Login</Link></li>
<li><Link to="/register">Register</Link></li>
<li><Link to="/contact">Contact</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
</nav>
);
}

export default Navbar;


Step 4: Create the Individual Pages
components/Login.js - Login Page
javascript

import React, { useState } from 'react';

const Login = () => {


const [username, setUsername] = useState('');
const [password, setPassword] = useState('');

const handleLogin = (e) => {


e.preventDefault();
console.log('Logging in with', username, password);
// Implement login logic here
};

return (
<div>
<h2>Login</h2>
<form onSubmit={handleLogin}>
<input
type="text"
placeholder="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<input
type="password"
placeholder="Password"

41
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button type="submit">Login</button>
</form>
</div>
);
};

export default Login;


components/Register.js - Registration Page
javascript

import React, { useState } from 'react';

const Register = () => {


const [username, setUsername] = useState('');
const [password, setPassword] = useState('');

const handleRegister = (e) => {


e.preventDefault();
console.log('Registering user', username);
// Implement registration logic here
};

return (
<div>
<h2>Register</h2>
<form onSubmit={handleRegister}>
<input
type="text"
placeholder="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<input
type="password"
placeholder="Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button type="submit">Register</button>
</form>
</div>
);
};

42
export default Register;
components/Contact.js - Contact Page
javascript

import React from 'react';

const Contact = () => {


return (
<div>
<h2>Contact Us</h2>
<p>Email: support@studentsystem.com</p>
<p>Phone: +1 (555) 123-4567</p>
</div>
);
};

export default Contact;


components/About.js - About Page
javascript

import React from 'react';

const About = () => {


return (
<div>
<h2>About</h2>
<p>This is a student management system that allows users to manage student data
securely.</p>
</div>
);
};

export default About;


Step 5: Styling (Optional)
You can add styling by creating a src/App.css file and import it into App.js.
Step 6: Run the Application
1. Start the React application:
bash

npm start
2. Navigate to http://localhost:3000 to view the application.

13. Create a service in react that fetches the weather information from
openweathermap.org and the display the current and historical weather information
using graphical representation using chart.js

43
Step 1: Set Up OpenWeatherMap API
1. Sign up on OpenWeatherMap to get an API key.
2. API Endpoints:
o Current Weather:
https://api.openweathermap.org/data/2.5/weather?q={CITY_NAME}&appid={AP
I_KEY}
o Historical Weather (One Call API):
https://api.openweathermap.org/data/3.0/onecall/timemachine?lat={LAT}&lon={
LON}&dt={TIMESTAMP}&appid={API_KEY}
Step 2: Set Up React Project
1. Create a new React app:
bash

npx create-react-app weather-app


cd weather-app
2. Install Chart.js and React-Chartjs-2:
bash

npm install chart.js react-chartjs-2


3. Project Structure:
bash

weather-app/
├── src/
│ ├── components/
│ │ ├── WeatherChart.js
│ │ └── WeatherDisplay.js
│ ├── services/
│ │ └── weatherService.js
│ ├── App.js
│ └── index.js
└── package.json
Step 3: Create the Weather Service to Fetch Data
services/weatherService.js:
javascript

const API_KEY = 'your_openweathermap_api_key';

export const getCurrentWeather = async (city) => {


const response = await
fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}
`);
return response.json();
};

export const getHistoricalWeather = async (lat, lon, timestamp) => {

44
const response = await
fetch(`https://api.openweathermap.org/data/3.0/onecall/timemachine?lat=${lat}&lon=${l
on}&dt=${timestamp}&appid=${API_KEY}`);
return response.json();
};
Step 4: Create the Weather Display Component
components/WeatherDisplay.js:
javascript

import React, { useState, useEffect } from 'react';


import { getCurrentWeather, getHistoricalWeather } from '../services/weatherService';
import WeatherChart from './WeatherChart';

const WeatherDisplay = () => {


const [city, setCity] = useState('New York');
const [weatherData, setWeatherData] = useState(null);
const [historicalData, setHistoricalData] = useState([]);

const fetchWeatherData = async () => {


const data = await getCurrentWeather(city);
setWeatherData(data);

const lat = data.coord.lat;


const lon = data.coord.lon;
const currentTime = Math.floor(Date.now() / 1000);

let historyData = [];


for (let i = 1; i <= 5; i++) {
const timestamp = currentTime - i * 24 * 60 * 60;
const historical = await getHistoricalWeather(lat, lon, timestamp);
historyData.push(historical);
}
setHistoricalData(historyData);
};

useEffect(() => {
fetchWeatherData();
}, [city]);

const handleCityChange = (e) => setCity(e.target.value);

return (
<div>
<h1>Weather Information for {city}</h1>
<input
type="text"

45
value={city}
onChange={handleCityChange}
placeholder="Enter city"
/>
<button onClick={fetchWeatherData}>Get Weather</button>

{weatherData && (
<div>
<h2>Current Weather</h2>
<p>Temperature: {(weatherData.main.temp - 273.15).toFixed(2)} °C</p>
<p>Humidity: {weatherData.main.humidity}%</p>
<p>Weather: {weatherData.weather[0].description}</p>
</div>
)}

<WeatherChart historicalData={historicalData} />


</div>
);
};

export default WeatherDisplay;


Step 5: Create the Weather Chart Component
components/WeatherChart.js:
javascript

import React from 'react';


import { Line } from 'react-chartjs-2';
import { Chart as ChartJS } from 'chart.js/auto';

const WeatherChart = ({ historicalData }) => {


const labels = historicalData.map((data, index) => `Day -${index + 1}`);
const temperatures = historicalData.map(data => data.current.temp - 273.15); //
Convert from Kelvin to Celsius

const data = {
labels,
datasets: [
{
label: 'Temperature (°C)',
data: temperatures,
borderColor: 'rgba(75,192,192,1)',
fill: false,
tension: 0.1,
},
],
};

46
return (
<div>
<h2>Historical Weather (Last 5 Days)</h2>
<Line data={data} />
</div>
);
};

export default WeatherChart;


Step 6: Update App.js to Display Weather Information
App.js:
javascript

import React from 'react';


import WeatherDisplay from './components/WeatherDisplay';

function App() {
return (
<div className="App">
<WeatherDisplay />
</div>
);
}

export default App;


Step 7: Run the Application
1. Start the application:
bash

npm start
2. Navigate to http://localhost:3000 to view the application.

14. Create a TODO application in react with necessary components and deploy it into
GitHub.

Step 1: Set Up the React Project


1. Create a new React app:
bash

npx create-react-app todo-app


cd todo-app
2. Project Structure:
csharp

todo-app/

47
├── public/
├── src/
│ ├── components/
│ │ ├── Todo.js # Single Todo item
│ │ └── TodoList.js # List of Todos
│ ├── App.js # Main component
│ └── index.js
└── package.json
Step 2: Build the Todo Components
components/Todo.js - Todo Component
javascript

import React from 'react';

const Todo = ({ todo, toggleComplete, removeTodo }) => {


return (
<div style={{ display: 'flex', alignItems: 'center' }}>
<input
type="checkbox"
checked={todo.completed}
onChange={() => toggleComplete(todo.id)}
/>
<span style={{ textDecoration: todo.completed ? 'line-through' : 'none',
marginLeft: '10px' }}>
{todo.text}
</span>
<button onClick={() => removeTodo(todo.id)} style={{ marginLeft: 'auto' }}>
Remove
</button>
</div>
);
};

export default Todo;


components/TodoList.js - Todo List Component
javascript

import React, { useState } from 'react';


import Todo from './Todo';

const TodoList = () => {


const [todos, setTodos] = useState([]);
const [inputValue, setInputValue] = useState('');

const addTodo = () => {


if (inputValue.trim() !== '') {

48
setTodos([...todos, { id: Date.now(), text: inputValue, completed: false }]);
setInputValue('');
}
};

const toggleComplete = (id) => {


setTodos(
todos.map(todo =>
todo.id === id ? { ...todo, completed: !todo.completed } : todo
)
);
};

const removeTodo = (id) => {


setTodos(todos.filter(todo => todo.id !== id));
};

return (
<div>
<h1>Todo List</h1>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
placeholder="Add a new todo"
/>
<button onClick={addTodo}>Add</button>
<div>
{todos.map(todo => (
<Todo
key={todo.id}
todo={todo}
toggleComplete={toggleComplete}
removeTodo={removeTodo}
/>
))}
</div>
</div>
);
};

export default TodoList;


Step 3: Update the App.js Component
src/App.js:
javascript

49
import React from 'react';
import TodoList from './components/TodoList';

function App() {
return (
<div className="App">
<TodoList />
</div>
);
}

export default App;


Step 4: Deploy to GitHub Pages
1. Install gh-pages:
bash

npm install gh-pages --save-dev


2. Update package.json: Add the following fields in your package.json file to set up
GitHub Pages:
json

{
"homepage": "https://<your-username>.github.io/todo-app",
"scripts": {
"predeploy": "npm run build",
"deploy": "gh-pages -d build"
}
}
Replace <your-username> with your GitHub username.
3. Push the Code to GitHub:
o Initialize a new GitHub repository named todo-app (or use any name you like).
o Link your local project to GitHub and push it:
bash

git init
git add .
git commit -m "Initial commit"
git remote add origin https://github.com/<your-username>/todo-app.git
git push -u origin master
4. Deploy to GitHub Pages:
bash

npm run deploy


This command will build the app and deploy it to the gh-pages branch of your repository.
5. Access Your App: After deployment, your app will be live at https://<your-
username>.github.io/todo-app.

50

You might also like