0% found this document useful (0 votes)
31 views56 pages

Ash Ritha

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)
31 views56 pages

Ash Ritha

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/ 56

Title : Date :

Page No. :

Lab Cycle-1 22WH1A1278


JAVA BASIC PROGRAMS

a. Java program to add two numbers


public class AddTwoNumbers {
public static void main(String[] args) {
int num1 = 5, num2 = 10;
int sum = num1 + num2;
System.out.println("Sum of " + num1 + " and " + num2 + " is: " + sum);
output:-

b. Java program to check even or odd

import java.util.Scanner;
public class CheckEvenOdd {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
if (number % 2 == 0) {
System.out.println(number + " is even.");
} else {
System.out.println(number + " is odd.");
}}}
output:-
c.java program to add two binary numbers
import java.util.Scanner;
public class AddBinaryNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first binary number: ");
String bin1 = scanner.nextLine();
System.out.print("Enter second binary number: ");
String bin2 = scanner.nextLine();
int num1 = Integer.parseInt(bin1, 2);
int num2 = Integer.parseInt(bin2, 2);
int sum = num1 + num2;
String result = Integer.toBinaryString(sum);
System.out.println("Sum of the binary numbers: " + result);
}}
output:-

d. Java
Program to Calculate Area and Circumference of Circle import
java.util.Scanner;
public class CircleAreaCircumference {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the radius of the circle: ");
double radius = scanner.nextDouble();
double area = Math.PI * radius * radius;
double circumference = 2 * Math.PI * radius;
System.out.println("Area: " + area);
System.out.println("Circumference: " + circumference);}
}
output:-
e. Java Program to Multiply two Numbers
public class MultiplyTwoNumbers {
public static void main(String[] args) {
int num1 = 7, num2 = 8;
int product = num1 * num2;
System.out.println("Product of " + num1 + " and " + num2 + " is: " + product);
}}
output:-

f. Java
Program to
check Leap Year import
java.util.Scanner;
public class CheckLeapYear {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = scanner.nextInt();
boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
if (isLeapYear) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}}}
output:-

g. Java Program to check whether input character is vowel or consonant


import java.util.Scanner;
public class VowelOrConsonant {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a character: ");
char ch = scanner.next().charAt(0);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
System.out.println(ch + " is a vowel.");
}
*-*-----------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------

else {
System.out.println(ch + " is a consonant.");
} }}

output:-

h.java program to
calculate compound interest import
java.util.Scanner;
public class CompoundInterest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter principal amount: ");
double principal = scanner.nextDouble();
System.out.print("Enter annual interest rate (in %): ");
double rate = scanner.nextDouble();
System.out.print("Enter number of times interest applied per time period: ");
int n = scanner.nextInt();
System.out.print("Enter time the money is invested for (in years): ");
int t = scanner.nextInt();
double amount = principal * Math.pow(1 + (rate / 100) / n, n * t);
double compoundInterest = amount - principal;
System.out.println("Compound Interest: " + compoundInterest);
System.out.println("Amount: " + amount);
}}

output:-
i.Java program to calculate power of a number.
import java.util.Scanner;
public class PowerOfNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter base number: ");
int base = scanner.nextInt();
System.out.print("Enter exponent: ");
int exponent = scanner.nextInt();
double result = Math.pow(base, exponent);
System.out.println(base + " raised to the power of " + exponent + " is: " + result);
}}
output:-

2. Java Strings Programs


a.java program for convert char to string viceversa.
public class CharToStringAndStringToChar {
public static void main(String[] args) {
char ch = 'a';
String str = Character.toString(ch);
System.out.println("Char to String: " + str);
String str2 = "hello";
char ch2 = str2.charAt(0);
System.out.println("String to Char: " + ch2);
}}
output:-

b.duplicate

charcater in astring import

java.util.HashMap;
public class DuplicateCharacters {
public static void main(String[] args) {
String str = "programming";
HashMap<Character, Integer> charCount = new HashMap<>();
for (char c : str.toCharArray()) {
charCount.put(c, charCount.getOrDefault(c, 0) + 1); }
System.out.println("Duplicate characters:");
for (char c : charCount.keySet()) {
if (charCount.get(c) > 1) {
System.out.println(c + ": " + charCount.get(c));
}}}
output:-
c. Java program to a string in alphabetical order.
import java.util.Arrays;
import java.util.Scanner;
public class SortStringsAlphabetically {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of strings: ");
int n = scanner.nextInt();
scanner.nextLine();
String[] strings = new String[n];
System.out.println("Enter the strings:");
for (int i = 0; i < n; i++) {
strings[i] = scanner.nextLine();
}
Arrays.sort(strings);
System.out.println("Strings in alphabetical order:");
for (String str : strings) {
System.out.println(str);
}}}
output:-

d. Java program to reverse words in a string.


import java.util.Scanner;
public class ReverseWordsInString {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();
String[] words = str.split("\\s+");
StringBuilder reversedString = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
reversedString.append(words[i]).append(" ");}
System.out.println("Reversed words: " + reversedString.toString().trim());
}}
output:-
e. Java program to perform bubble sort on string.
import java.util.Scanner;
public class BubbleSortStrings {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of strings: ");
int n = scanner.nextInt();
scanner.nextLine();
String[] strings = new String[n];
System.out.println("Enter the strings:");
for (int i = 0; i < n; i++) {
strings[i] = scanner.nextLine();
}
scanner.close();
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (strings[j].compareTo(strings[j + 1]) > 0) {
// Swap strings[j] and strings[j + 1]
String temp = strings[j];
strings[j] = strings[j + 1];
strings[j + 1] = temp; }}}
System.out.println("Strings after bubble sort:");
for (String str : strings) {
System.out.println(str); }}}
output:-

f. Java program for occurance of a character in a string


import java.util.Scanner;
public class CharacterOccurrence {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();
System.out.print("Enter a character to find: ");
char ch = scanner.next().charAt(0);
scanner.close();
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ch) {
count++; }}
System.out.println("The character '" + ch + "' occurs " + count + " times in the string.");}}
output:-

h.Java

program to count vowels and consonants in string. import

java.util.Scanner;
public class VowelsAndConsonants {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();
scanner.close();
int vowelsCount = 0;
int consonantsCount = 0;
String vowels = "aeiouAEIOU";
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (Character.isLetter(ch)) {
if (vowels.indexOf(ch) != -1) {
vowelsCount++;
} else {
consonantsCount++; }}}
System.out.println("Number of vowels: " + vowelsCount);
System.out.println("Number of consonants: " + consonantsCount);}}
output:-

3. java Arrays programs.


a. Java program to calculate avg of a numbers using array.
import java.util.Scanner;
public class AverageOfArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
double[] numbers = new double[n];
double sum = 0;
System.out.println("Enter the numbers:");
for (int i = 0; i < n; i++) {
numbers[i] = scanner.nextDouble();
sum += numbers[i];}
double average = sum / n;
System.out.println("Average of the numbers: " + average);}}
output:-

b. Java program to add elements in array


import java.util.Scanner;
public class SumOfArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] numbers = new int[n];
int sum = 0;
System.out.println("Enter the numbers:");
for (int i = 0; i < n; i++) {
numbers[i] = scanner.nextInt();
sum += numbers[i];
}System.out.println("Sum of the elements: " + sum);}}
output:-

c. Java program to reverse an array.


import java.util.Scanner;
public class ReverseArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] numbers = new int[n];
System.out.println("Enter the numbers:");
for (int i = 0; i < n; i++) {
numbers[i] = scanner.nextInt();
}
scanner.close();
System.out.println("Reversed array:");
for (int i = n - 1; i >= 0; i--) {
System.out.print(numbers[i] + " ");}}}
output:-

d. Java program to sort an into ascending order


import java.util.Arrays;
import java.util.Scanner;
public class SortArrayAscending {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] numbers = new int[n];
System.out.println("Enter the numbers:");
for (int i = 0; i < n; i++) {
numbers[i] = scanner.nextInt();}
Arrays.sort(numbers);
System.out.println("Sorted array in ascending order:");
for (int num : numbers) {
System.out.print(num + " ");}}}
output:-
e. Java program to convert char array to string.
import java.util.Scanner;
public class CharArrayToString {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of characters: ");
int n = scanner.nextInt();
scanner.nextLine();
char[] charArray = new char[n];
System.out.println("Enter the characters:");
for (int i = 0; i < n; i++) {
charArray[i] = scanner.next().charAt(0);}
String result = new String(charArray);
System.out.println("Converted String: " + result);
}}
output:-

4.a) Java program to calculate grades of a student.


import java.util.Scanner;
public class StudentGrades {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of subjects: ");
int numSubjects = scanner.nextInt();
double[] scores = new double[numSubjects];
double total = 0;
System.out.println("Enter the scores for each subject:");
for (int i = 0; i < numSubjects; i++) {
System.out.print("Score for subject " + (i + 1) + ": ");
scores[i] = scanner.nextDouble();
total += scores[i];}
double average = total / numSubjects;
System.out.printf("Total Score: %.2f%n", total);
System.out.printf("Average Score: %.2f%n", average);
String grade;
if (average >= 90) {
grade = "A";
} else if (average >= 80) {
grade = "B";
} else if (average >= 70) {
grade = "C";
} else if (average >= 60) {
grade = "D";
} else {
grade = "F";
}
System.out.println("Grade: " + grade);}}

output:-
Title : Date :

Page No. :

pw.println("Login Success");
}
else {
pw.println("Sorry... Login Failed");
}
pw.close();
}
}

Output:
Title : Date :

Page No. :

Program8: Maintaining the transactional history of any user is very important. Explore the
various session tracking mechanism (Cookies, HTTP Session) 24.05.2024
Create a file in index.html using java eclipse dynamic web project.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="FirstServlet" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
</body>
</html>

Output:
Title : Date :

Page No. :

Write a servlet program FirstServlet.java to add Cookie

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
Cookie ck=new Cookie("uname",n);//creating cookie object
response.addCookie(ck);//adding cookie in the response
//creating submit button
out.print("<form action='SecondServlet' method='post'>");
out.print("<input type='submit' value='Submit'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}
Title : Date :

Page No. :

Output:

Write a servlet program SecondServlet.java to add Cookie

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();

}catch(Exception e){System.out.println(e);}
}
}

Output:
Title : Date :

Page No. :

Program 9: Create a custom server using http module and explore the other modules of Node JS
like OS, path, event.

Code:

const http = require('http');


const os = require('os');
const path = require('path');
const EventEmitter = require('events');
const hostname = '127.0.0.1';
const port = 3000;
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('serverStart', () => {
console.log('Server has started!');
});

const server = http.createServer((req, res) => {


if (req.url === '/osinfo') {
const osInfo = {
osType: os.type(),
osPlatform: os.platform(),
cpuArchitecture: os.arch(),
totalMemory: os.totalmem(),
freeMemory: os.freemem(),
};

res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(osInfo, null, 2));
}
else if (req.url === '/pathinfo') {
const pathInfo = {
currentDirectory: dirname,
currentFile: filename,
fileExtension: path.extname( filename),
directoryName: path.dirname( filename),
baseName: path.basename( filename),
Title : Date :

Page No. :

parsedPath: path.parse( filename),


};

res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(pathInfo, null, 2));
}
else if (req.url === '/eventinfo') {
const eventInfo = {
message: 'Server has started and the event has been emitted!'
};

myEmitter.emit('eventTriggered');
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(eventInfo, null, 2));
}
else {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
}
});
server.listen(port, hostname, () => {
myEmitter.emit('serverStart');
console.log(`Server running at http://${hostname}:${port}/`);
console.log('Operating System Info:');
console.log(`OS Type: ${os.type()}`);
console.log(`OS Platform: ${os.platform()}`);
Title : Date :

Page No. :

console.log(`CPU Architecture: ${os.arch()}`);


console.log(`Total Memory: ${os.totalmem()}`);
console.log(`Free Memory: ${os.freemem()}`);
console.log('Path Module Info:');
console.log(`Current Directory: ${ dirname}`);
console.log(`Current File: ${ filename}`);
console.log(`File Extension: ${path.extname( filename)}`);
console.log(`Directory Name: ${path.dirname( filename)}`);
console.log(`Base Name: ${path.basename( filename)}`);
console.log(`Parsed Path:`, path.parse( filename));
});

myEmitter.on('eventTriggered', () => {
console.log('Event has been triggered!');
});
Title : Date :

Page No. :

Output:

HTTP Server Output:

OS Module Info output:


Title : Date :

Page No. :

Path Module Info output:

Event Module Info output:


Title : Date :

Page No. :

Output in postman:

HTTP Server module

OS module output:
Title : Date :

Page No. :

Path module output:

Event module output:


Title : Date :

Page No. :

Program 10: Develop an express web application that can interact with REST API to perform
CRUD operations on student data. (Use Postman)

Aim: Need to develop a web application using ExpressJs which interacts with Postman API, then
perform CRUD Operations.

Steps to implement the program 10

Step 1: Set Up Your Development Environment

1. Install Node.js:
 Download and install Node.js from the official website. This will also install
npm, the Node package manager.
2. Create a folder in your system and open the created folder in Visual Studio Code.
3. Create a Project Directory:
 Open a terminal or command prompt and create a new directory for your
project. Navigate into this directory.
mkdir my-express-app
cd my-express-app
4. Initialize a New Node.js Project:
 Initialize a new Node.js project with npm init. Follow the prompts to set up your
package.json file.
npm init -y

Step 2: Install Express.js

1. Install Express:
 Install Express.js and any other necessary dependencies.
npm install express

Step 3: Create the Express.js Application

1. Create the Application File:


 Create a new file named app.js in your project directory.
2. Write the Express.js Application Code:
 Open app.js in your Visual Studio Code editor and add the following code:
const express = require('express');
const app = express();
Title : Date :

Page No. :

const port = 3000;


app.use(express.json());
let items = []; // Sample in-memory data store

// Create – POST

app.post('/items', (req, res) => {


const newItem = req.body;
items.push(newItem);
res.status(201).send(newItem);
});

// Read – GET

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


res.send(items);
});

app.get('/items/:id', (req, res) => {


const item = items.find(i => i.id === parseInt(req.params.id));
if (!item) return res.status(404).send('Item not found');
res.send(item);
});

// Update – PUT

app.put('/items/:id', (req, res) => {


const item = items.find(i => i.id === parseInt(req.params.id));
if (!item) return res.status(404).send('Item not found');

Object.assign(item, req.body);
res.send(item);
});

// Delete – DELETE

app.delete('/items/:id', (req, res) => {


const index = items.findIndex(i => i.id === parseInt(req.params.id));
Title : Date :

Page No. :

if (index === -1) return res.status(404).send('Item not found');

const deletedItem = items.splice(index, 1);


res.send(deletedItem);
});

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

Step 4: Run the Application

1. Start the Server:


 In your terminal, run the following command to start your Express.js server.
node app.js
 You should see the message: Server running at http://localhost:3000.

Step 5: Test the Application with Postman

1. Open Postman:
 Open Postman to test your API endpoints.
2. Create (POST) Operation:
 Set the method to POST and enter the URL http://localhost:3000/items.
 Go to the Body tab, select raw, and choose JSON format.
 Enter JSON data, e.g.:
{
"id": 1,
"name": "Anil",
"description": "This is item Name"
}
 Click Send to create a new item.
3. Read (GET) Operations:
o To get all items, set the method to GET and enter the URL
http://localhost:3000/items, then click Send.
o To get a single item by ID, set the method to GET and enter the URL
http://localhost:3000/items/1, then click Send.
Title : Date :

Page No. :

4. Update (PUT) Operation:


o Set the method to PUT and enter the URL http://localhost:3000/items/1.
o Go to the Body tab, select raw, and choose JSON format.
o Enter the updated JSON data, e.g.:
{
"name": "Updated Item 1",
"description": "This is the updated item 1"
}
o Click Send to update the item.
5. Delete (DELETE) Operation:
o Set the method to DELETE and enter the URL http://localhost:3000/items/1.
Click Send to delete the item.

Output:
Title : Date :

Page No. :
Title : Date :

Page No. :

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

Steps to implement the program 11

To add authorization to the Express web application using JWT (JSON Web Token), need to
follow these steps:
1. Install additional dependencies.
2. Set up user authentication endpoints.
3. Create a middleware to protect certain routes.
4. Update your existing routes to use the authorization middleware.

Step 1: Install Additional Dependencies


Install jsonwebtoken and bcryptjs for handling JWTs and password hashing.
npm install jsonwebtoken bcryptjs

Step 2: Set Up User Authentication Endpoints


Update server.js to include user authentication logic.

// server.js
const express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const app = express();
const port = 3000;
const SECRET_KEY = 'your_secret_key'; // You should use an environment variable for this
let users = []; // This should be a database in a real application
let students = [];

// Middleware
app.use(bodyParser.json());

// Routes
app.get('/', (req, res) => {
res.send('Welcome to the Student CRUD API!');
});
Title : Date :

Page No. :

// User registration
app.post('/register', async (req, res) => {
const { username, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 8);
users.push({ username, password: hashedPassword });
res.status(201).send({ message: 'User registered successfully' });
});

// User login
app.post('/login', async (req, res) => {
const { username, password } = req.body;
const user = users.find(u => u.username === username);
if (!user) {
return res.status(404).send({ message: 'User not found' });
}
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
return res.status(401).send({ message: 'Invalid password' });
}
const token = jwt.sign({ username }, SECRET_KEY, { expiresIn: '1h' });
res.status(200).send({ token });
});

// Middleware to verify JWT


const verifyToken = (req, res, next) => {
const token = req.headers['authorization'];
if (!token) {
return res.status(403).send({ message: 'No token provided' });
}
jwt.verify(token, SECRET_KEY, (err, decoded) => {
if (err) {
return res.status(500).send({ message: 'Failed to authenticate token' });
}
req.user = decoded;
next();
});
};
Title : Date :

Page No. :

// Create a new student (protected)


app.post('/students', verify
Token, (req, res) => {
const student = req.body;
student.id = students.length + 1;
students.push(student);
res.status(201).send(student);
});

// Read all students (protected)


app.get('/students', verifyToken, (req, res) => {
res.status(200).send(students);
});

// Read a single student by ID (protected)


app.get('/students/:id', verifyToken, (req, res) => {
const student = students.find(s => s.id == req.params.id);
if (student) {
res.status(200).send(student);
} else {
res.status(404).send({ message: 'Student not found' });
}
});

// Update a student by ID (protected)


app.put('/students/:id', verifyToken, (req, res) => {
const studentIndex = students.findIndex(s => s.id == req.params.id);
if (studentIndex !== -1) {
students[studentIndex] = { ...students[studentIndex], ...req.body };
res.status(200).send(students[studentIndex]);
} else {
res.status(404).send({ message: 'Student not found' });
}
});
Title : Date :

Page No. :

// Delete a student by ID (protected)


app.delete('/students/:id', verifyToken, (req, res) => {
const studentIndex = students.findIndex(s => s.id == req.params.id);
if (studentIndex !== -1) {
const deletedStudent = students.splice(studentIndex, 1);
res.status(200).send(deletedStudent);
} else {
res.status(404).send({ message: 'Student not found' });
}
});

// Start the server


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

Step 3: Test the Application with Postman

Register a New User


 Method: POST
 URL: http://localhost:3000/register
 Body: (JSON)
{
"username": "testuser",
"password": "Gabber123"
}

Log In and Get a Token


 Method: POST
 URL: http://localhost:3000/login
 Body: (JSON)
{
"username": "testuser",
"password": "Gabber123"
}
Title : Date :

Page No. :

 Response:
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InRlc3R1c2VyIi
wiaWF0IjoxNzE5NzcwMTI3LCJleHAiOjE3MTk3NzM3Mjd9.v3SDW1blrSdIf60psu-uEF-
Khhp4npS7kBJaNek87Xc"
}

Output:
Title : Date :

Page No. :
Title : Date :

Page No. :

Program12: 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: Create a New React Application


1. Open Visual Studio Code and open the terminal.
2. Create a new React app using Create React App by running:
npx create-react-app student-management-system
3. Navigate to the project directory:
cd student-management-system

Step 2: Install React Router


1. Install React Router:
npm install react-router-dom

Step 3: Create Pages


1. Create a components directory inside src.
2. Create the following component files inside components directory:
o Registration.js
o Login.js
o Contact.js
o About.js
o
Step 4: Implement the Pages
 Registration.js:
import React, { useState } from 'react';

function Registration() {
const [formData, setFormData] = useState({
username: '',
email: '',
password: '',
confirmPassword: ''
});

const handleChange = (e) => {


const { name, value } = e.target;
setFormData((prevFormData) => ({
Title : Date :

Page No. :

...prevFormData,
[name]: value
}));
};

const handleSubmit = (e) => {


e.preventDefault();
// Add form submission logic here
console.log('Form submitted:', formData);
};

return (
<div>
<h2>Registration</h2>
<form onSubmit={handleSubmit}>
<div>
<label>Username:</label>
<input
type="text"
name="username"
value={formData.username}
onChange={handleChange}
required
/>
</div>
<div>
<label>Email:</label>
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
required
/>
Title : Date :

Page No. :

</div>
<div>
<label>Password:</label>
<input
type="password"
name="password"
value={formData.password}
onChange={handleChange}
required
/>
</div>
<div>
<label>Confirm Password:</label>
<input
type="password"
name="confirmPassword"
value={formData.confirmPassword}
onChange={handleChange}
required
/>
</div>
<button type="submit">Register</button>
</form>
</div>
);
}

export default Registration;

Login.js:
import React, { useState } from 'react';

function Login() {
const [formData, setFormData] = useState({
email: '',
password: ''
});
Title : Date :

Page No. :

const handleChange = (e) => {


const { name, value } = e.target;
setFormData((prevFormData) => ({
...prevFormData,
[name]: value
}));
};

const handleSubmit = (e) => {


e.preventDefault();
// Add form submission logic here
console.log('Form submitted:', formData);
};

return (
<div>
<h2>Login</h2>
<form onSubmit={handleSubmit}>
<div>
<label>Email:</label>
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
required
/>
</div>
<div>
<label>Password:</label>
<input
type="password"
name="password"
value={formData.password}
onChange={handleChange}
required
/>
Title : Date :

Page No. :

</div>
<button type="submit">Login</button>
</form>
</div>
);
}

export default Login;

Contact.js:
import React, { useState } from 'react';

function Contact() {
const [formData, setFormData] = useState({
name: '',
email: '',
message: ''
});

const handleChange = (e) => {


const { name, value } = e.target;
setFormData((prevFormData) => ({
...prevFormData,
[name]: value
}));
};

const handleSubmit = (e) => {


e.preventDefault();
// Add form submission logic here
console.log('Form submitted:', formData);
};

return (
<div>
Title : Date :

Page No. :

<h2>Contact Us</h2>
<form onSubmit={handleSubmit}>
<div>
<label>Name:</label>
<input
type="text"
name="name"
value={formData.name}
onChange={handleChange}
required
/>
</div>
<div>
<label>Email:</label>
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
required
/>
</div>
<div>
<label>Message:</label>
<textarea
name="message"
value={formData.message}
onChange={handleChange}
required
/>
</div>
<button type="submit">Send</button>
</form>
</div>
);
}
Title : Date :

Page No. :

export default Contact;

About.js:
import React from 'react';

function About() {
return (
<div>
<h2>About Us</h2>
<p>Welcome to our Student Management System. This application is designed to help
manage student information efficiently and effectively.</p>
<p>Our system allows you to register, log in, and view information about students. You can
also contact us through the contact page.</p>
<p>We aim to provide the best service possible and appreciate your feedback. Thank you
for using our system!</p>
</div>
);
}

export default About;

App.js

import React from 'react';


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

function App() {
return (
<Router>
<div>
<nav>
<ul>
Title : Date :

Page No. :

<li>
<Link to="/">Registration</Link>
</li>
<li>
<Link to="/login">Login</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
</nav>
<Routes>
<Route path="/" element={<Registration />} />
<Route path="/login" element={<Login />} />
<Route path="/contact" element={<Contact />} />
<Route path="/about" element={<About />} />
</Routes>
</div>
</Router>
);
}

export default App;

Step 5: Run the Application


1. Start the development server:
npm start
2. Open your browser and navigate to http://localhost:3000 to see your application in
action.
Title : Date :

Page No. :

Output:

Registration.js

Login.js
Title : Date :

Page No. :

Contact.js

About.js
Title : Date :

Page No. :

Program13: 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

Step 1: Setup Your React Application


1. Create a new React application:
bash
Copy code
npx create-react-app weather-app
cd weather-app
2. Install required dependencies:
bash
Copy code
npm install axios chart.js react-chartjs-2

Step 2: Fetch Weather Data


1. Create a services directory inside src and add a file named weatherService.js.
2. Implement the weather service to fetch data from OpenWeatherMap:
o weatherService.js

import axios from 'axios';

const API_KEY = 'YOUR_OPENWEATHERMAP_API_KEY';


const BASE_URL = 'https://api.openweathermap.org/data/2.5';

export const getCurrentWeather = async (city) => {


try {
const response = await axios.get(`${BASE_URL}/weather`, {
params: {
q: city,
appid: API_KEY,
units: 'metric'
}
});
Title : Date :

Page No. :

return response.data;
} catch (error) {
console.error('Error fetching current weather data:', error);
throw error;
}
};

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


try {
const oneDayInSeconds = 86400;
const currentTime = Math.floor(Date.now() / 1000);
const historicalTimes = [1, 2, 3, 4, 5].map((daysAgo) => currentTime - daysAgo *
oneDayInSeconds);
const historicalData = await Promise.all(
historicalTimes.map((time) =>
axios.get(`${BASE_URL}/onecall/timemachine`, {
params: {
lat,
lon,
dt: time,
appid: API_KEY,
units: 'metric'
}
})
)
);
return historicalData.map((response) => response.data);
} catch (error) {
console.error('Error fetching historical weather data:', error);
throw error;
}
};
Title : Date :

Page No. :

Step 3: Create Components


1. Create a components directory inside src and add the following files:
o WeatherChart.js
o WeatherDashboard.js
2. Implement the WeatherChart component:
WeatherChart.js:
import React from 'react';
import { Line } from 'react-chartjs-2';
import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title,
Tooltip, Legend } from 'chart.js';

ChartJS.register(CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip,


Legend);

const WeatherChart = ({ data, options }) => {


if (!data || !options) {
return <div>Loading chart...</div>;
}
return <Line data={data} options={options} />;
};

export default WeatherChart;

Step 4: Integrate Components into the App


1. Modify App.js to include the WeatherDashboard component:
App.js
import React from 'react';
import WeatherDashboard from './components/WeatherDashboard';
import './App.css';

function App() {
return (
<div className="App">
<WeatherDashboard />
</div>
Title : Date :

Page No. :

);
}

export default App;

Create App.css for basic styling:


App.css
.App {
text-align: center;
padding: 20px;
}

input {
margin-right: 10px;
}

button {
padding: 5px 10px;
}

h2 {
margin-top: 20px;
}

p{
margin: 5px 0;
}

Step 5: Run the Application


1. Start the development server:
npm start
2. Open your browser and navigate to http://localhost:3000 to see your application in action
Title : Date :

Page No. :

Output:
Title : Date :

Page No. :

Program 14: Create a TODO application in react with necessary components and deploy it into
github

Step 1: Set Up Your React App


1. Create React App: If you haven't already set up a React app, follow the steps in the
previous response to create a new React application using create-react-app.
npx create-react-app todo-app
cd todo-app
2. Navigate into Your App Directory:
cd todo-app

Step 2: Create Components for TODO App

App.js
This will be the main component where we'll manage our state and render other components.
// src/App.js

import React, { useState } from 'react';


import TodoForm from './components/TodoForm';
import TodoList from './components/TodoList';
import './App.css';

function App() {
const [todos, setTodos] = useState([]);

const addTodo = (todo) => {


setTodos([...todos, todo]);
};

const deleteTodo = (index) => {


const newTodos = [...todos];
newTodos.splice(index, 1);
setTodos(newTodos);
};

return (
<div className="App">
<h1>TODO App</h1>
Title : Date :

Page No. :

<TodoForm addTodo={addTodo} />


<TodoList todos={todos} deleteTodo={deleteTodo}
);
}

export default App;

TodoForm.js
Component for adding new TODO items.
// src/components/TodoForm.js

import React, { useState } from 'react';

function TodoForm({ addTodo }) {


const [value, setValue] = useState('');

const handleSubmit = (e) => {


e.preventDefault();
if (!value) return;
addTodo({ text: value });
setValue('');
};

return (
<form onSubmit={handleSubmit}>
<input
type="text"
className="input"
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder="Add TODO..."
/>
<button type="submit">Add</button>
</form>
);
}
export default TodoForm;
Title : Date :

Page No. :

TodoList.js
Component to display the list of TODO items.
// src/components/TodoList.js

import React from 'react';

function TodoList({ todos, deleteTodo }) {


return (
<ul>
{todos.map((todo, index) => (
<li key={index}>
{todo.text}
<button onClick={() => deleteTodo(index)}>Delete</button>
</li>
))}
</ul>
);
}

export default TodoList;

Step 3: Styling (Optional)


You can add CSS styles to App.css to customize the appearance of your TODO app.
Step 4: Deploy to GitHub
Now, let's deploy our TODO app to GitHub using GitHub Pages.
1. Initialize Git Repository:
git init
2. Add GitHub Remote:
If you haven't already set up a repository on GitHub, create a new repository. Then, add the
GitHub remote to your local repository:
git remote add origin https://github.com/Anil4799/NodeJs-Lab.git
3. Commit Changes:
git add .
git commit -m "Initial commit"
Title : Date :

Page No. :

4. Deploy to GitHub Pages:


Install gh-pages package as a development dependency:
npm install gh-pages --save-dev
Add deployment scripts to package.json:
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"deploy": "gh-pages -d build",
"predeploy": "npm run build"
},
5. Deploy Your App:
npm run deploy
6. Access Your Deployed App:
Your TODO app should now be deployed to GitHub Pages. You can access it at https://your-
username.github.io/todo-app.

Step 5: Verify Deployment

Visit the URL of your deployed TODO app to verify that it's working correctly.
Title : Date :

Page No. :
Title : Date :

Page No. :

Git Output:

You might also like