Lab Manual
Lab Manual
Build a responsive web application for shopping cart with registration, login,
catalog and cart pages using CSS3 features, ex and grid.
AIM: Build a responsive web application for shopping cart with registration, login,
catalog and cart pages using CSS3 features, ex and grid.
Project Structure:
1. [Link] - Main HTML le containing the structure of the web application.
2. [Link] - CSS le for styling the web pages.
3. [Link] - JavaScript le for handling interactions and logic.
4. images/ - Folder for storing images.
[Link]:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="[Link]">
<title>Shopping Cart</title>
</head>
<body>
<header>
<h1>Shopping Cart</h1>
<nav>
<ul>
<li><a href="#catalog">Catalog</a></li>
<li><a href="#cart">Cart</a></li>
<li><a href="#login">Login</a></li>
<li><a href="#register">Register</a></li>
</ul>
</nav>
</header>
<main id="content">
<!-- Content will be loaded dynamically using JavaScript -->
</main>
<script src="[Link]"></script>
</body>
</html>
——————————————
[Link]:
body {
fi
fi
fi
fl
fl
font-family: 'Arial', sans-serif;
margin: 0;
padding: 0;
}
header {
background-color: #333;
color: # f;
padding: 10px;
text-align: center;
}
nav ul {
list-style: none;
padding: 0;
display: ex;
justify-content: center;
}
nav li {
margin: 0 10px;
}
main {
padding: 20px;
}
/* Add more styles based on your design */
[Link]:
// Dummy data for the catalog
const catalog = [
{ id: 1, name: 'Product 1', price: 20 },
{ id: 2, name: 'Product 2', price: 30 },
{ id: 3, name: 'Product 3', price: 25 },
];
// Function to load the catalog
function loadCatalog() {
const catalogContainer = [Link]('content');
[Link] = '<h2>Catalog</h2>';
[Link](product => {
const productCard = [Link]('div');
[Link]('product-card');
[Link] = `
<h3>${[Link]}</h3>
<p>$${[Link]}</p>
<button onclick="addToCart(${[Link]})">Add to Cart</button>
`;
[Link](productCard);
});
}
// Function to add a product to the cart
function addToCart(productId) {
// Implement cart functionality here
ff
fl
[Link](`Product ${productId} added to cart`);
}
// Initial load
loadCatalog();
Explanation
1. HTML Structure: The HTML le consists of a header, navigation, and a main
content area, initially empty but dynamically populated using JavaScript.
2. CSS Styles: The CSS le o ers basic styling for header, navigation, and main
content area, which can be customized according to your design needs.
Output:
The shopping cart application's basic structure is displayed in [Link], with the
catalog section containing dummy product data.
Note: The example is intentionally simpli ed, and you would need to add more
functionality, such
as user authentication, cart management, and server communication, for a fully
functional
shopping cart application.
fi
fi
ff
fi
fi
2. Make the above web application responsive web application using Bootstrap
framework
AIM: Make the above web application responsive web application using
Bootstrap framework
DESCRIPTION:
Bootstrap is a popular CSS framework that makes it easy to create responsive
web applications.
The previous example can be modi ed using Bootstrap by following these steps:
Project Structure:
1. [Link] - Main HTML le containing the structure of the web application
with Bootstrap.
2. [Link] - JavaScript le for handling interactions and logic (no changes from the
previous example).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap CSS -->
<link href="[Link]
[Link]"
rel="stylesheet">
<!-- Custom CSS -->
<link rel="stylesheet" href="[Link]">
<title>Shopping Cart</title>
</head>
<body>
<header class="bg-dark text-white text-center py-3">
<h1>Shopping Cart</h1>
<nav>
<ul class="nav justify-content-center">
<li class="nav-item"><a class="nav-link" href="#catalog">Catalog</a></li>
<li class="nav-item"><a class="nav-link" href="#cart">Cart</a></li>
<li class="nav-item"><a class="nav-link" href="#login">Login</a></li>
<li class="nav-item"><a class="nav-link" href="#register">Register</a></li>
fi
fi
fi
</ul>
</nav>
</header>
<main class="container mt-3" id="content">
<!-- Content will be loaded dynamically using JavaScript -->
</main>
<!-- Bootstrap JS (optional, for certain features) -->
<script
src="[Link]
[Link]"></script>
<script src="[Link]"></script>
</body>
</html>
[Link]:
/* You can include additional custom styles here if needed */
Explanation:
1. Bootstrap Integration: In the <head> section, we added links to the Bootstrap
CSS and JS les from a CDN (Content Delivery Network). This allows us to use
Bootstrap's styling and functionality.
4. Responsive Main Content: The container class ensures that the main content
area is responsive. Bootstrap will automatically adjust the width based on the
screen size.
Output:
When you open [Link] in a web browser, you'll see that the web application is
now responsive.
The Bootstrap framework takes care of making the layout adapt to di erent
screen sizes, providing a
more user-friendly experience on various devices.
Remember to test the responsiveness by resizing your browser or using di erent
devices to see how
the layout adjusts.
fi
fi
ff
ff
3. Use JavaScript for doing client – side validation of the pages implemented in
experiment 1 and experiment 2
AIM: Use JavaScript for doing client – side validation of the pages implemented
in experiment 1: Build a responsive web application for shopping cart with
registration, login, catalog and cart pages using CSS3 features, ex and grid and
experiment 2: Make the above web application responsive web application using
Bootstrap framework
DESCRIPTION: To perform client-side validation using JavaScript, you can add
scripts to validate user inputs on the registration and login pages.
The modi cations for both experiments are listed below.
Explanation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="[Link]">
<title>Weather Graph</title>
</head>
<body>
<div class="container">
<h1>Weather Graph</h1>
<canvas id="weatherGraph" width="400" height="200"></canvas>
</div>
<script src="[Link]
<script src="[Link]
<script src="[Link]"></script>
</body>
</html>
————————————————————————————————-
[Link]:
body {
font-family: 'Arial', sans-serif;
margin: 0;
fi
fi
fi
padding: 0;
background-color: #f4f4f4;
}
.container {
max-width: 600px;
margin: 50px auto;
background-color: # f;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1 {
text-align: center;
}
canvas {
display: block;
margin: 20px auto;
}
[Link]:
[Link]('DOMContentLoaded', () => {
const apiKey = 'YOUR_OPENWEATHERMAP_API_KEY';
const city = 'YOUR_CITY_NAME';
const apiUrl = `[Link]
&appid=$
{apiKey}&units=metric`;
const fetchData = async () => {
try {
const response = await [Link](apiUrl);
const weatherData = [Link];
updateGraph([Link]);
} catch (error) {
[Link]('Error fetching weather data:', [Link]);
}
};
Explanation:
1. HTML Structure: We have a simple HTML structure with a container for the
graph canvas.
3. JavaScript ([Link]):
• The fetchData function uses axios to make an asynchronous HTTP request to
OpenWeatherMap API.
• The retrieved weather data is used to update the graph using the
updateGraph function.
Output:
When you open [Link] in a web browser, the application fetches the current
weather information for the speci ed city from OpenWeatherMap API and displays
the temperature on a bar graph. Please note that you need to replace
'YOUR_OPENWEATHERMAP_API_KEY' with your actual API key. Additionally, the
responsiveness and appearance can be further enhanced based on your design
preferences
fi
5. Develop a java stand alone application that connects with the database
(Oracle / mySql) and perform the CRUD operation on the database tables.
AIM: Develop a java stand alone application that connects with the database
(Oracle / mySql) and perform the CRUD operation on the database tables.
1. Make sure you have MySQL installed, and you know the database name,
username, and password.
2. Download the MySQL JDBC driver (JAR le) from MySQL Connector/J and
include it in your project.
import [Link].*;
public class CRUDExample {
// JDBC URL, username, and password of MySQL server
private static nal String JDBC_URL = "jdbc:mysql://localhost:3306/
your_database";
private static nal String USERNAME = "your_username";
private static nal String PASSWORD = "your_password";
public static void main(String[] args) {
try {
// Step 1: Establishing a connection
Connection connection = [Link](JDBC_URL,
USERNAME, PASSWORD);
// Step 2: Creating a statement
Statement statement = [Link]();
// Step 3: Performing CRUD operations
createRecord(statement, "John Doe", 50000);
readRecords(statement);
updateRecord(statement, 1, "John Updated", 55000);
readRecords(statement);
deleteRecord(statement, 1);
readRecords(statement);
// Step 4: Closing resources
[Link]();
[Link]();
} catch (SQLException e) {
[Link]();
fi
fi
fi
fi
}
}
// 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 + “)";
[Link](insertQuery);
[Link]("Record created successfully.");
}
// Read all records from the database
private static void readRecords(Statement statement) throws SQLException {
String selectQuery = "SELECT * FROM employees";
ResultSet resultSet = [Link](selectQuery);
[Link]("ID\tName\tSalary");
while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
int salary = [Link]("salary");
[Link](id + "\t" + name + "\t" + salary);
}
[Link]();
}
// 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;
[Link](updateQuery);
[Link]("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;
[Link](deleteQuery);
[Link]("Record deleted successfully.");
}
}
Explanation:
1. Connection Parameters: Replace your_database, your_username, and
your_password with your 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:
2. DTD File ([Link]): Describes the structure of the XML document using
Document Type De nition. Speci es that a bookstore must contain one or more
book elements. Each book must contain title, author, and price elements.
3. XSD File ([Link]): Describes the structure of the XML document using
XML Schema De nition. De nes complex types for bookstore and book.
Speci es that a bookstore must contain an unbounded sequence of book
elements. Each book must contain title (string), author (string), and price (decimal)
elements.
Validation:
You can validate the XML le using a tool or programming language that supports
DTD and XSD
validation. Here, I'll show you how to do it using a Java program.
Java Program for Validation:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link]
import [Link];
public class XMLValidator {
public static void main(String[] args) {
validateWithDTD("[Link]", "[Link]");
validateWithXSD("[Link]", "[Link]");
}
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 =
[Link](XMLConstants.XML_DTD_NS_URI);
Schema schema = [Link](new
StreamSource(dtdStream));
Validator validator = [Link]();
[Link](new StreamSource(xmlStream));
[Link]("Validation with DTD successful.");
}
fi
fi
fi
fi
fi
fi
catch (SAXException | IOException e) {
[Link]("Validation with DTD failed. Reason: " + [Link]());
}
}
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 =
[Link](XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = [Link](new
StreamSource(xsdStream));
Validator validator = [Link]();
[Link](new StreamSource(xmlStream));
[Link]("Validation with XSD successful.");
}
catch (SAXException | IOException e) {
[Link]("Validation with XSD failed. Reason: " + [Link]());
}
}
}
Output:
If the XML le adheres to the speci ed DTD and XSD, you will see output
messages like:
Validation with DTD successful.
Validation with XSD successful.
If there are issues with the XML le, the program will print error messages
explaining the validation failure.
Make sure to replace "[Link]", "[Link]", and "[Link]" with
the actual le paths in your project. Also, you can use various online XML
validators to validate your XML les against DTD and XSD if you prefer a web-
based approach.
fi
fi
fi
fi
fi
7. Design a controller with servlet that provides the interaction with application
developed in experiment 1 and the database created in experiment 5
AIM: Design a controller with servlet that provides the interaction with application
developed in experiment 1: Build a responsive web application for shopping cart
with registration, login, catalog and cart pages using CSS3 features, ex and grid
and the database created in experiment 5: Develop a java stand alone application
that connects with the database (Oracle / mySql) and perform the CRUD operation
on the database tables
DESCRIPTION: To design a servlet controller that interacts with the shopping
cart application (Experiment 1) and thedatabase (Experiment 5), you would
typically handle HTTP requests from the web application, process the data, and
communicate with the database to perform CRUD operations.
Explanation:
1. Servlet Annotation (@WebServlet("/ShoppingCartController")): This annotation
maps the servlet to the speci ed 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.
fi
3. Action Methods (handleRegistration, handleLogin, handleAddToCart): Each
method handles a speci c action requested by the client. It extracts data from 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.
AIM: Maintaining the transactional history of any user is very important. Explore
the various session tracking mechanism (Cookies, HTTP Session)
1. Cookies: Cookies are small data pieces stored on a user's device by a web
browser, used to maintain user-speci c information between the client and the
server.
if __name__ == '__main__':
[Link](debug=True)
HTML Templates ([Link] and set_language.html):
<!-- [Link] -->
<!DOCTYPE html>
<html lang="en">
<head>
<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 %}
fl
fi
<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 rst 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):
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-speci c information on the client and server sides, respectively.
fi
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
});
To run the server: node [Link]
B. path Module:
The path module provides methods for working with le and directory paths.
Example:
const path = require('path');
const lePath = '/path/to/some/ [Link]';
[Link]('File Name:', [Link]( lePath));
[Link]('Directory Name:', [Link]( lePath));
[Link]('File Extension:', [Link]( lePath));
fi
fi
fi
fi
fi
fi
Output: This will output the le name, directory name, and le extension for the
given le path.
C. events Module:
The events module provides an implementation of the EventEmitter pattern,
allowing objects to emit and listen for events.
Example:
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
// Event listener
[Link]('customEvent', (arg) => {
[Link]('Event triggered with argument:', arg);
});
// Emitting the event
[Link]('customEvent', 'Hello, EventEmitter!');
Output: This will output "Event triggered with argument: Hello, EventEmitter!".
These examples showcase the basic usage of the os, path, and events modules in
[Link]. Feel free to explore more features and methods provided by these
modules in the o cial [Link] documentation: os Module, path Module, events
Module.
fi
ffi
fi
fi
10. Develop an express web application that can interact with REST API to
perform CRUD operations on student data. (Use Postman)
AIM: Develop an express web application that can interact with REST API to
perform CRUD operations on student data. (Use Postman)
DESCRIPTION: Let's create a simple Express web application that interacts with
a REST API to perform CRUD (Create, Read, Update, Delete) operations on
student data. We'll use MongoDB as the database and Mongoose as the ODM
(Object Data Modeling) library.
Prerequisites:
AIM: For the above application create authorized end points using JWT (JSON
Web Token)
Aim: Create a react application for the student management system having
registration, login, contact, about pages and implement routing to navigate through
these pages.
This is a basic structure, and you can enhance it by adding functionality to the
registration and login forms, managing state, and connecting to a backend for data
storage. Also, consider using react-router-dom features like Switch, Redirect, and
withRouter for more advanced routing scenarios.
13. Create a service in react that fetches the weather information from
[Link] and the display the current and historical weather
information using graphical representation using [Link]
AIM: Create a service in react that fetches the weather information from
[Link] and the display the current and historical weather
information using graphical representation using [Link]
DESCRIPTION: To achieve this, you can create a React service that fetches
weather information from
OpenWeatherMap API and uses [Link] for graphical representation.
setChartData({
labels,
datasets: [
{
label: 'Temperature (°C)',
data: temperatures,
backgroundColor: 'rgba(75,192,192,0.2)',
borderColor: 'rgba(75,192,192,1)',
borderWidth: 1,
},
],
});
} catch (error) {
[Link]('Error fetching weather data:', error);
}
};
fetchData();
}, []);
return (
<div>
<h2>Historical Weather Chart</h2>
<Line data={chartData} />
</div>
);
};
export default WeatherChart;
ff
ff
5. Integrate WeatherChart in App Component:
src/[Link]:
// src/[Link]
import React from 'react';
import WeatherChart from './components/WeatherChart';
function App() {
return (
<div className="App">
<WeatherChart />
</div>
);
}
export default App;
7. Run the App: npm start Visit [Link] in your browser. The app
should fetch historical weather data and display it using [Link].
Note: The provided example fetches historical weather data for the past 7 days.
You may customize the date range and other parameters based on your
requirements. Additionally, consider error handling and user interface
improvements for a production-ready application.
14. Create a TODO application in react with necessary components and deploy it
into github
AIM: Create a TODO application in react with necessary components and deploy
it into github