SD-LAB-MANUAL
SD-LAB-MANUAL
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.
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
3
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
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
<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;
}
.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
14
</body>
</html>
Experiment-3
Use JavaScript for doing client – side validation of the pages implemented in the
experiment
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
<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..
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().
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
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
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.
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
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" }
]
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
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" });
}
});
// 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;
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).
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
module.exports = authenticateToken;
Step 3: Create Authentication Routes (Login and Register)
routes/auth.js:
javascript
35
const path = require('path');
function saveUserData(data) {
fs.writeFileSync(dataPath, JSON.stringify(data, null, 2));
}
// Login a user
router.post('/login', async (req, res) => {
const { username, password } = req.body;
const users = getUserData();
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
function getStudentData() {
const jsonData = fs.readFileSync(dataPath);
return JSON.parse(jsonData);
}
function saveStudentData(data) {
fs.writeFileSync(dataPath, JSON.stringify(data, null, 2));
}
// 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" });
}
});
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
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
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
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>
);
}
40
import React from 'react';
import { Link } from 'react-router-dom';
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>
);
};
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
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
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
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
useEffect(() => {
fetchWeatherData();
}, [city]);
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>
)}
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>
);
};
function App() {
return (
<div className="App">
<WeatherDisplay />
</div>
);
}
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.
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
48
setTodos([...todos, { id: Date.now(), text: inputValue, completed: false }]);
setInputValue('');
}
};
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>
);
};
49
import React from 'react';
import TodoList from './components/TodoList';
function App() {
return (
<div className="App">
<TodoList />
</div>
);
}
{
"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
50