Web_Tech_Lab_File(BCS-552)
Web_Tech_Lab_File(BCS-552)
LABORATORY MANUAL
WEB TECHNOLOGY
(BCS-552)
Name
Roll No.
Section-Batch
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Mission 4: To create a conducive learning and research environment for life-long learning to develop
the students as technology leaders and entrepreneurs for addressing societal needs.
1
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
Graduate Will:
PEO1: Possess core theoretical and practical knowledge in Computer Science and Engineering for
successful career development in industry, pursuing higher studies or entrepreneurship.
PEO2: Ability to imbibe life long learning for global challenges to impact society and environment.
PEO3: To demonstrate work productivity with leadership and managerial skills having ethics and
human value in progressive career path.
PEO4: To exhibit communication skill and collaborative skill plan and participate in
multidisciplinary fields of Computer Science & Engineering.
PSO1: To analyze and demonstrate, the recent engineering practices, ethical values and strategies
in real time world problems to meet the challenges for the future.
PSO2: To develop adaptive computing system using computational intelligence strategies and
algorithmic design to address diverse challenges in data analysis and machine learning.
2
PROGRAM OUTCOMES
3
GENERAL LABORATORY INSTRUCTIONS
1. Students are advised to come to the laboratory at least 5 minutes before (to the
starting time), those who come after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, comeprepared to
the lab with the synopsis / program / experiment details.
3. Student should enter into the laboratory with:
• Laboratory observation notes with all the details (Problem statement, Aim,
Algorithm, Procedure, Program, Expected Output, etc.,) filled in for the
lab session.
• Laboratory Record updated up to the last session experiments and other
utensils (if any) needed in the lab.
• Proper Dress code and Identity card.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the
computer system allotted to you by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab
observation note book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must
maintain the discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded
systems, which should be utilized properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode
during the lab sessions. Misuse of the equipment, misbehaviors with the staff
and systems etc., will attract severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go
out; if anybody found loitering outside the lab / class without permission during
working hours will be treated seriously and punishedappropriately.
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she
leaves the lab after completing the task (experiment) in allaspects. He/she must
ensure the system / seat is kept properly.
4
DETAILS OF THE EXPERIMENTS CONDUCTED
(TO BE USED BY THE STUDENTS IN THEIR RECORDS)
INDEX
10
11
12
5
STUDY AND EVALUATION SCHEME
Course Course
Teaching Scheme Credits Assigned
Code Name
6
IMS Engineering College
NH-09, Adhyatmik Nagar, Near Dasna, Distt. Ghaziabad, U.P.
Tel: (0120) 4940000
Department of Computer Science and Engineering
________________________________________________________________
Course Name: Web Technology Lab Course Code: BCS-552
Semester / Year: 5Th /3rd NBA Code: C314
Bloom’s
COURSE OUTCOMES Level
C314.1 Understand the fundamental concepts of web development, including the history, K3, K6
protocols, and tools. Apply HTML and XML in the development of web projects.
C314.2 Apply CSS for designing and styling web pages, including the use of CSS K2, K3
properties, styling elements, and advanced techniques for creating responsive web
sites.
C314.3 Develop interactive web applications using JavaScript and AJAX, with a focus on K3, K6
scripting documents, forms, and networking concepts such as internet addressing
and TCP/IP sockets.
Design and implement server-side applications using Enterprise Java Beans (EJB)
C314.4 K2,
and Node.js, including the creation of JavaBeans, RESTful APIs, and database
operations with MongoDB. K4, K6
Implement web server functionality using Servlets and Java Server Pages (JSP),
C314.5 K2,
focusing on handling HTTP requests, session tracking, and utilizing custom tag
libraries for dynamic web content. K3, K4
CO-PO Matrix
Course
PO 1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2
Outcome
3 3 3 3 3 - - - 3 1 2 3 3 3
C314.1
3 3 3 3 3 - - - 3 1 2 3 3 3
C314.2
3 3 3 3 3 - - - 3 1 2 3 3 3
C314.3
C314.4
3 3 3 3 3 - - - 3 1 2 3 3 3
3 3 3 3 3 - - - 3 1 2 3 3 3
C314.5
3.00 3.00 3.00 3.00 3.00 - - - 3.00 1.00 2.00 3.00 3.00 3.00
Avg
7
LIST OF PROGRAMS
8
EXPERIMENT NO. - 1
AIM: Write HTML program for designing your institute website. Display
departmental information of your institute on the website.
Procedure:
HTML stands for Hyper Text Markup Language. HTML is the computer language that is used
to create documents for display on the Web. Many editors exist to create Web Pages – Word,
FrontPage, and Dream Weaver are just a few. Nevertheless, each of these software programs
(editors) performs the exact same task – they all generate HTML language.The HTML
language consists of a series of HTML tags. Learning HTML involves finding out what tags
are used to mark the parts of a document and how these tags are used in creating an HTML
document. Tags are instructions that tell your browser what to show on a Web page. They break
up your document into basic sections. All tags start with a < (left bracket) and end with a >
(right bracket).
Basic HTML Tags
<HTML></HTML>
This tag tells your browser that the file contains HTML-coded information. All html tags must
be placed between the open <HTML> tag and the closed tag </HTML>The file extension .html
also indicates the document is an HTML document. All html documents MUST be saved with
the .html file extension.
<HEAD></HEAD>
The head tag identifies the first part of your HTML-coded document. The title tag (explained
below) must be places between the open <HEAD> tag and the closed </HEAD> tag.
<BODY></BODY>
The largest part of your HTML document is the body, which contains the content of your
document (displayed within the text area of your browser window). All HTML tags that pertain
to the body of your HTML document must be places between the open <BODY> tag and the
closed </BODY> tag. The tag has attributes which you can use to set the colors of your
background, text, links, and also to include your own background image. They are as follows:
BGCOLOR="white" Sets the background color (other color names: red, black, blueetc)
• TEXT="black" Sets the body text color
• LINK="blue" Sets the unvisited hypertext links
• VLINK ="purple" Sets the visited hypertext links
• ALINK="red" Sets the active hypertext links (the color of the hypertext link when
you have your mouse button depressed)
• BACKGROUND Let you use an image as the background <background=Body
attributes are used as part of the open <body> tag. For example:<BODY BGCOLOR
= "white" TEXT = "black" LINK = "blue" VLINK = "purple" ALINK ="red">
9
Code/Method:
To create a complete lab manual that connects all these pages together, you can link the pages using
HTML navigation, ensuring seamless transitions between different sections (labs, sections, semesters,
and faculty information). Additionally, you can include comments and explanations in the code to guide
students or readers about the structure.
Here’s how to connect all the files together into a **Lab Manual** format with comments and
explanations.
This is the entry point for your lab manual. It will provide a simple navigation menu for users to access
different sections.
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Institute Lab Manual</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<!-- Header of the website -->
<header>
<h1>Welcome to the CSE1 Lab Manual</h1>
<p>Navigate through the labs, sections, semester info, and faculty details.</p>
</header>
<!-- Navigation menu linking to different sections of the lab manual -->
<nav>
<a href="labs.html">Labs</a>
<a href="sections.html">Sections</a>
<a href="semesters.html">Semesters</a>
<a href="faculty.html">Faculty</a>
</nav>
<!-- Main content explaining what this lab manual covers -->
<main>
<h2>Department Information</h2>
<p>This is the landing page for the Computer Science and Engineering department's lab manual.
Here, you can
navigate to learn about labs, sections, semester-wise subjects, and the faculty involved in
teaching these
courses.</p>
<p><b>Vision & Mission:</b>Describe the department's vision to develop skilled professionals
and its mission to 10
provide a high-quality
education and foster research in the field.</p>
<p><b>Goals:</b> List out the primary goals, like enhancing employability, promoting
innovation, and
contributing to industry needs.</p>
</main>
This page gives information about the various labs in the department. The navigation links at the top
allow the user to switch between different sections of the lab manual.
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Labs - CSE Lab Manual</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
</body>
</html>
```
This page explains the various sections in the department, typically for different groups of students.
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sections - CSE Lab Manual</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
</body>
</html>
```
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Semesters - CSE Lab Manual</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
</body>
</html>
```
This page provides the details of the faculty members in the department.
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Faculty - CSE Lab Manual</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
</body>
</html> 14
```
### 6. **CSS File (style.css)**
This is the shared CSS file that gives a consistent look and feel to all pages.
```css
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
margin: 0;
padding: 0;
}
header {
background-color: #004080;
color: white;
text-align: center;
padding: 1rem;
}
nav {
background-color: #333;
overflow: hidden;
}
nav a {
float: left;
color: white;
text-align: center;
padding: 14px 20px;
text-decoration: none;
}
nav a:hover {
background-color: #ddd;
color: black;
}
main {
padding: 20px;
margin: 0 auto;
}
footer {
background-color: #004080;
color: white;
text-align: center;
padding: 1rem;
position: absolute;
width: 100%;
bottom: 0;
} 15
```
Output:
Viva Questions:
1. What is HTML Tag ?
2. What is purpose of <li>tag ?
3. Why we use tag <p>?
4. What is Image tag<img>?
5. What is Anchor tag<a>?
16
EXPERIMENT NO. - 2
17
element and <option> element. The option elements within the <select> element define each
list item.
Submit and Reset Buttons- A submit button is used to send the form data to a web server.
When submit button is clicked the form data is sent to the file specified in the form's action
attribute to process the submitted data. A reset button resets all the forms control to default
values.
Code/Method:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="form.css">
</head>
<body>
<form>
<div class="main">
<h1>Entry form</h1><br>
<label class="name">Select Entry Type:</label>
<select id="entryType" name="entryType" required>
<option value="">--Select--</option>
<option value="student">Student</option>
<option value="employee">Employee</option>
<option value="faculty">Faculty</option>
</select><br>
<div class="name">
<div>
<label>Name :</label>
</div>
<input type="text" placeholder="first name">
<input type="text" placeholder="middle name">
<input type="text" placeholder="last name">
</div>
<div class="email">
<div>
<label>Email :</label>
</div>
<input type="text" placeholder="enter your email">
</div>
<div class="email">
<div>
<label>DOB :</label>
</div>
<input type="date" placeholder="enter your email">
18
</div>
<div class="email">
<div>
<label>Phone Number:</label>
</div>
<input type="tel" placeholder="XXXXXXXXXX">
</div>
<div class="gender">
<div>
<label>Gender :</label>
</div>
<input type="radio" name="gender">Male
<input type="radio" name="gender">Female
</div>
<div class="email">
<div>
<label>Address :</label>
</div>
<textarea name="message" id="message" placeholder="enter your message here" rows="3"
cols="50"></textarea>
</div>
<div class="email">
<div>
<label>Student Details:</label>
</div>
<textarea name="message" id="message" placeholder="enter your message here" rows="3"
cols="50"></textarea>
</div>
<button>SUBMIT</button>
</div>
</form>
</body>
</html>
*{
margin: 0;
padding: 0;
}
body {
background-color: white;
}
h1 {
color: black;
text-align: center;
}
.main {
width: 50%; 19
border: 2px solid rgb(52, 193, 244);
border-radius: 10px;
padding: 20px 50px;
margin: 20px 300px;
background-color: rgb(113, 206, 227);
}
.name,
.email,
.phone,
.gender {
color: black;
font-size: larger;
padding: 10px 0px 10px 0px;
font-weight: 600;
}
.name input {
height: 30px;
border-radius: 10px;
width: 30.9%;
padding: 0px 0px 0px 10px;
margin-top: 10px;
font-size: medium;
}
#entryType {
height: 30px;
border-radius: 10px;
width: 98%;
padding: 0px 0px 0px 10px;
margin-top: 10px;
margin-left: 10px;
font-size: medium;
}
.email input {
height: 30px;
border-radius: 10px;
width: 97%;
padding: 0px 10px 0px 10px;
margin-top: 10px;
font-size: medium;
}
.gender input {
height: 20px;
border-radius: 10px;
width: 10%;
align-items: center;
margin-top: 10px;
}
.email textarea { 20
height: 30px;
border-radius: 10px;
width: 97%;
height: 10%;
padding: 10px 10px 0px 10px;
margin-top: 10px;
font-size: 17px;
}
button {
padding: 10px 100px 10px 100px;
border-radius: 10px;
border: 2px solid rgb(20, 25, 27);
color: white;
background-color: black;
transition: 0.9s all ease;
font-weight: 800;
}
button:hover {
background-color: rgb(33, 176, 228);
color: black;
}
21
Output:
Viva Questions-
1. What is element and attributes in HTML?
2. What is purpose of <td> and <tr> Tag?
3. What is Heading Tag<h1> ..... <h6>?
4. What is Table Tag?
5. Define row * column <tr><td>.
22
EXPERIMENT NO. - 3
AIM- Develop a responsive website using CSS and HTML. Website may be for
tutorial/blogs/commercial website.
Objective:
To design and implement a responsive website that adjusts its layout based on the screen size of the
device, such as a desktop, tablet, or mobile phone.
Responsive web design refers to building websites that adapt to different screen sizes and device
orientations to ensure a consistent user experience. The key to responsiveness lies in the use of flexible
grid layouts, media queries, and dynamic content resizing.
Procedure:
Step 3: Test the website layout on various devices (desktop, tablet, and mobile).
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Responsive Page</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
</body>
</html>
Styles.css
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
24
body {
color: #333;
line-height: 1.6;
/* Header */
header {
text-align: center;
padding: 2em;
background-color: #f5f5f5;
header h1 {
font-size: 2em;
header p {
margin-top: 0.5em;
color: #666;
/* Cards Section */
#cards {
display: flex;
flex-direction: column;
gap: 1em;
padding: 2em;
.card {
25
padding: 1.5em;
border-radius: 8px;
background-color: #fff;
text-align: center;
/* Content Section */
#content {
text-align: center;
padding: 2em;
#content h2 {
font-size: 1.8em;
margin-bottom: 0.5em;
/* Footer */
footer {
text-align: center;
padding: 1em;
background-color: #333;
color: #fff;
font-size: 0.9em; }
/* Responsive Styles */
#cards {
flex-direction: row;
26
justify-content: space-between;
.card {
flex: 1;
margin: 0 1em;
• Navigation Bar:
The nav element contains an unordered list of links that allow users to navigate between
different sections of the webpage. On smaller screens, the navigation adjusts to become
vertically aligned.
• The first media query (max-width: 768px) adjusts the layout for tablet-sized devices by making
the navigation items stack vertically and reducing padding.
• The second media query (max-width: 480px) is used for mobile screens. It further reduces the
font sizes and margin/padding to fit smaller screens.
27
Output:
Viva Questions:
1. What is the difference between <div> and <section> tags in HTML?
2. What is the role of the <meta charset="UTF-8"> tag in an HTML document?
3. Explain the box model in CSS and how margins, padding, and borders affect the layout of elements.
4. What are the advantages of using external CSS compared to inline or internal CSS?
5. What is a media query in CSS?
28
EXPERIMENT NO. - 4
AIM- Write programs using HTML and Java Script for validation of input data.
Procedure:
To validate user input in an HTML form using JavaScript. The form will check for required
fields, email format, and specific password rules before submitting the data.
Form validation is an important part of web development, ensuring that users provide correct and
complete information before submitting data to the server. Client-side validation using JavaScript
allows for immediate feedback without requiring server communication, improving the user
experience. Common validation techniques include checking for empty fields, validating email
format, and password strength.
Step 1: Create an HTML form with fields for a username, email, and password.
Step 2: Write JavaScript functions to validate the form data (checking if fields are empty, ensuring the
email is valid, and the password meets specific criteria).
Step 3: Link the JavaScript file or embed the JavaScript code in the HTML file to ensure the validation
occurs when the form is submitted.
Step 4: Test the form by submitting invalid and valid data to observe the validation process.
Code/Method: form_validation.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
<style>
/* Basic styling for form and error messages */
body {
font-family: Arial, sans-serif;
margin: 50px;
}
.error {
color: red;
font-size: 0.9em;
}
form {
background-color: #f9f9f9;
padding: 20px;
border-radius: 5px;
max-width: 400px;
margin: auto;
}
input[type="text"], input[type="email"], input[type="password"] {
width: 100%;
padding: 10px; 29
margin: 10px 0;
}
input[type="submit"] {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<script>
// JavaScript function to validate form inputs
function validateForm() {
// Get form inputs
var username = document.getElementById("username").value;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
// Validation flags
var valid = true;
</body>
</html>
Output:
31
EXPERIMENT NO. - 5
Procedure:
XML Document Type Declaration, commonly known as DTD, is a way to describe precisely
the XML language. DTDs check the validity of structure and vocabulary of an XML document
against the grammatical rules of the appropriate XML language. An XML document can be
defined as:
• Well-formed: If the XML document adheres to all the general XML rules such as tags must
be properly nested, opening and closing tags must be balanced, and empty tags must end with
'/>', then it is called as well-formed.
OR
• Valid: An XML document said to be valid when it is not only well-formed, but it also
conforms to available DTD that specifies which tags it uses, what attributes those tags can
contain, and which tags can occur inside other tags, among other properties.
Types:
DTD can be classified on its declaration basis in the XML document, such as:
• Internal DTD
• External DTD
When a DTD is declared within the file it is called Internal DTD and if it is declared in a
separate file it is called External DTD.
We will learn more about these in the chapter DTD Syntax.
Syntax
Basic syntax of a DTD is as follows:
<!DOCTYPE element DTD identifier
[ declaration1
declaration2
........
]>
In the above syntax
• DTD starts with <!DOCTYPE> delimiter.
• An element tells the parser to parse the document from the specified root element.
• DTD identifier is an identifier for the document type definition, which may be the path to a
file on the system or URL to a file on the internet. If the DTD is pointing to external path, it
is called external subset.
• The square brackets [ ] enclose an optional list of entity declarations called internal subset.
Code/Method:
32
Employee
2. {
3. background-color: pink;
4. }
5. firstname,lastname,email
6. {
7. font-size:25px;
8. display:block;
9. color: blue;
10. margin-left: 50px;
11. }
employee.dtd
employee.xml
1. <?xml version="1.0"?>
2. <?xml-stylesheet type="text/css" href="cssemployee.css"?>
3. <!DOCTYPE employee SYSTEM "employee.dtd">
4. <employee>
5. <firstname>vimal</firstname>
6. <lastname>jaiswal</lastname>
7. <email>[email protected]</email>
8. </employee>
Output:
Viva Questions:
1. What is xml?
2. Define DTD.
3. Differentiate b/w internal dtd & external dtd.
4. What is xmlschema?
5. What is internal DTD?
33
EXPERIMENT NO. - 6
AIM - Create a Java Bean for Employee information (EmpID, Name, Salary,
Designation and Department)
Objective:
To create a Java Bean that encapsulates employee information such as EmpID, Name, Salary,
Designation, and Department. The bean should follow the Java Bean conventions and
include getter and setter methods for accessing and modifying the fields.
Theory:
• Encapsulation: The properties of the bean are private and accessed via getter and setter methods.
• No-argument constructor: A default constructor is provided for easy instantiation.
• Serializable: The bean implements the Serializable interface to support saving the state of the
object and later retrieving it.
• Getter and Setter Methods: These methods provide controlled access to the bean’s properties,
allowing external programs to read or update the values.
Procedure:
EmployeeBean.java
import java.io.Serializable;
EmployeeTest.java
Output:
When the EmployeeTest program is run, the following output will be displayed:
Viva Questions:
EXPERIMENT NO. - 7
36
AIM - Build a command-line utility using Node.js that performs a specific
task, such as converting text to uppercase, calculating the factorial of a
number, or generating random passwords.
Objective:
To create a command-line utility using Node.js that performs a specific task. In this
experiment, we will develop a utility that can perform one of the following operations based
on user input:
Theory:
Node.js is a JavaScript runtime built on Chrome's V8 engine. It is widely used for creating
server-side and networking applications. With Node.js, we can also create command-line
utilities that take input from users, perform specific tasks, and output the results directly to the
terminal.
In this experiment, we will build a basic command-line utility using Node.js. The utility will
use core modules such as process to handle input/output from the terminal.
Procedure:
1. Step 1: Install Node.js from the official website if not already installed.
2. Step 2: Create a new project folder for the utility.
3. Step 3: Initialize the project using the npm init command to create a package.json file.
4. Step 4: Create a JavaScript file, e.g., cli-utility.js, and implement the required
functionality.
5. Step 5: Write code to handle command-line arguments and perform the following tasks:
o Convert text to uppercase.
o Calculate the factorial of a number.
o Generate random passwords.
6. Step 6: Test the utility by running the program with different command-line arguments.
Code:
mkdir cli-utility
cd cli-utility
Npm init –y
cli-utility.js
37
#!/usr/bin/env node
if (args.length < 2) {
console.log("Usage:");
console.log(" uppercase <text>");
console.log(" factorial <number>");
console.log(" password <length>");
process.exit(1); // Exit with failure
}
switch (command) {
case "uppercase":
console.log("Uppercase:", convertToUpper(value));
break;
case "factorial":
38
const num = parseInt(value);
if (isNaN(num) || num < 0) {
console.log("Please provide a valid non-
negative integer.");
} else {
console.log(`Factorial of ${num}:`,
factorial(num));
}
break;
case "password":
const length = parseInt(value);
if (isNaN(length) || length <= 0) {
console.log("Please provide a valid positive
integer for password length.");
} else {
console.log(`Generated Password:`,
generatePassword(length));
}
break;
default:
console.log("Unknown command. Please use
'uppercase', 'factorial', or 'password'.");
}
}
To run the utility, open the terminal in the project directory and execute the following commands
based on the desired functionality:
arduino
Copy code
node cli-utility.js uppercase "hello world"
Output:
makefile
Copy code
Uppercase: HELLO WORLD
• Calculate factorial:
Copy code
node cli-utility.js factorial 5
Output:
mathematica
Copy code
Factorial of 5: 120
Output:
yaml
Copy code
Generated Password: aZ3rT1yU0p
Viva Questions:
1. What is Node.js?
2. How does process.argv work in Node.js?
3. What is the purpose of the #!/usr/bin/env node line?
4. How does recursion work in the factorial calculation?
5. How does the random password generation function work?
40
EXPERIMENT NO. - 8
Objective:
Theory:
MongoDB Aggregation Framework is a powerful tool for performing data processing and
transformation operations on documents in a collection. It allows for tasks such as filtering,
grouping, sorting, and calculating averages in a flexible and efficient manner.
MongoDB uses a pipeline approach for aggregation, where each stage processes the
documents and passes the results to the next stage.
Procedure:
1. Step 1: Set up a MongoDB database and a users collection with relevant fields (name, age, city).
2. Step 2: Install the MongoDB Node.js driver to connect to the MongoDB database from a Node.js
application.
3. Step 3: Write a Node.js script that connects to MongoDB and performs aggregation operations like
grouping, filtering, and sorting.
4. Step 4: Run the script and verify the output, which should provide the average age of users in
different cities.
Code/Method:
PROGRAM:
Users.json
[
{ "name": "John Doe", "age": 28, "city": "New York" },
{ "name": "Jane Smith", "age": 32, "city": "San Francisco" },
{ "name": "Mike Davis", "age": 21, "city": "New York" },
{ "name": "Sara Johnson", "age": 30, "city": "San Francisco" },
{ "name": "Chris Brown", "age": 25, "city": "Chicago" }
41
]
Install Dependencies
npm init -y
npm install mongodb
aggregateUsers.js
const { MongoClient } = require('mongodb');
try {
// Connect to the MongoDB server
await client.connect();
console.log("Connected successfully to MongoDB");
} catch (err) {
console.error(err); 42
} finally {
// Close the MongoDB connection
await client.close();
}
}
aggregateUserData();
Output:
Node aggregateUsers.js
Viva Questions:
43
EXPERIMENT NO. - 9
AIM- Assume four users user1, user2, user3 and user4 having the passwords pwd1,
pwd2, pwd3 and pwd4 respectively. Write a servlet for doing the following: 1. Create a
Cookie and add these four user id’s and passwords to this Cookie. 2. Read the user id and
passwords entered in the Login form and authenticate with the values available in the
cookies.
Procedure:
JSP scripting elements let you insert Java code into the servlet that will be generated from the
current JSP page. There are three forms:
Expressions of the form <%= expression %> that are evaluated and inserted into the output,
Scriptlets of the form <% code %> that are inserted into the servlet's service method, and
Declarations of the form <%! code %> that are inserted into the body of the servlet class,
outside of any existing methods.Each of theseis described in more detail below.JSP Expressions
A JSP expression is used to insert Java values directly into the output. It has the following form:
<%= Java Expression %>
The Java expression is evaluated, converted to a string, and inserted in the page. This evaluation
is performed at run-time (when the page is requested), and thus has full access to information
about the request. For example, the following showsthe date/time that the page was requested:
Current time: <%= new java.util.Date() %>
To simplify these expressions, there are a number of predefined variables that you can use. These
implicit objects are discussed in more detail later, but for the purpose of expressions, the most
important ones are:
request, the HttpServletRequest; response, the HttpServletResponse;
session, the HttpSession associated with the request (if any); and
out, the PrintWriter (a buffered version of type JspWriter) used to send output to the client.JSP
Scriptlets
If you want to do something more complex than insert a simple expression, JSP scriptlets let you
insert arbitrary code into the servlet method that will be built to generate the page. Scriptlets have
the following form:
<% Java Code %>
Scriptlets have access to the same automatically defined variables as expressions. So, for
example, if you want output to appear in the resultant page, you would use the out variable.
<%
String queryData = request.getQueryString(); out.println("Attached GET data: " +
queryData);
%>
Note that code inside a scriptlet gets inserted exactly as written, and any static HTML (template
text) before or after a scriptlet gets converted to print statements. This means that scriptlets need
not contain complete Java statements, and blocks left open can affect the static HTML outside
of the scriptlets.
JSP Declarations
A JSP declaration lets you define methods or fields that get inserted into the main body of the
servlet class (outside of the service method processing
44
the request). It has the following form:
<%! Java Code %>
Since declarations do not generate any output, they are normally used in conjunction with JSP
expressions or scriptlets. For example, here is a JSP fragment that prints out the number of times
the current page has been requested since the server booted (or the servlet class was changed and
reloaded):
<%! privateintaccessCount = 0; %>
Code/Method:
Login.html:
<!--Home.html-->
<html><body>
<center><h1>XYZ Company Ltd.</h1></center>
<table border="1" width="100%" height="100%">
<tr>
<td valign="top" align="center"><br/>
<form action="auth.jsp"><table>
<tr>
<td colspan="2" align="center"><b>Login Page</b></td>
</tr>
<tr>
<td colspan="2" align="center"><b> </td>
</tr>
<tr>
<td>User Name</td>
<td><input type="text" name="user"/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pwd"/></td>
</tr>
<tr>
<td> </td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>
Auth.jsp:
<%@page import="java.sql.*;"%> 45
<html>
<head>
<title>
This is simple data base example in JSP</title>
</title>
</head>
<body bgcolor="yellow">
<%!Stringuname,pwd;%>
<%
uname=request.getParameter("user");
pwd=request.getParameter("pwd");
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@195.100.101.158:1521
:CCLAB","scott","tiger");
Statement st=con.createStatement();
ResultSetrs=st.executeQuery("select name,password from personal where name='"+uname+"'
and password='"+pwd+"'");
if(rs.next())
{
out.println("Authorized person");
}
else
{
out.println("UnAuthorized person");
}
con.close();}
catch(Exception e){out.println(""+e);}
%></body></html>
46
Output:
47
Viva Questions:
1. What is class?
2. Define Method and property.
3. What is Constructor?
4. Define types of Constructor.
5. Define the copy Constructor.
48
EXPERIMENT NO. - 10
AIM: Create a table which should contain at least the following fields: name,
password, email-id, phone number Write Servlet/JSP to connect to that database
and extract data from the tables and display them. Insert the details of the users
who register with the web site, whenever a new user clicks the submit button in
the registration page.
Procedure:
1. Create Maven Project
2.Click Next button to select Archetype for project
3.Click Next button and enter Project Information:
Group Id: LearnJSPServletWithRealApps
Artifact Id: LearnJSPServletWithRealApps
Package: com.demo
Code/Method:
Configure pom.xml-
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>LearnJSPServletWithRealApps</groupId>
<artifactId>LearnJSPServletWithRealApps</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Learn JSP-Servlet with Real Apps</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>javax.servlet.jsp.jstl-api</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
49
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>LearnJSPServletWithRealApps</finalName>
</build>
</project>
Configure web.xml-
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Redirect Page
Create new JSP file named index.jsp in src\main\webapp folder. This file will redirect to
ProductServlet as below:
}
Item Entity
Create new Java class named Item.java as 51
below:
packagecom.demo.entities;
public Item() {
}
publicintgetQuantity() {
return quantity;
}
}
Create Servlets
Create new package named com.demo.servlets. In this package, create new Servlets as
below:
Product Servlet
In com.demo.servlets package, create new Servlet named ProductServlet as below:
packagecom.demo.servlets;
importjava.io.IOException;
importjavax.servlet.ServletException; 52
importjavax.servlet.annotation.WebServlet;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importcom.demo.models.ProductModel;
@WebServlet("/product")
public class ProductServlet extends HttpServlet {
publicProductServlet() {
super();
}
}
Cart Servlet
In com.demo.servlets package, create new Servlet named CartServlet as below:
packagecom.demo.servlets;
importjava.io.IOException;
importjava.util.ArrayList;
importjava.util.List;
importjavax.servlet.ServletException;
importjavax.servlet.annotation.WebServlet;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importjavax.servlet.http.HttpSession;
53
importcom.demo.entities.Item;
importcom.demo.models.ProductModel;
@WebServlet("/cart")
public class CartServlet extends HttpServlet {
publicCartServlet() {
super();
}
}
Create Product Pages
Create new folder named product in src\main\webapp folder. In this folder, create new
JSP file named index.jsp as below:
</body>
</html>
Create Cart Pages
Create new folder named cart in src\main\webapp folder. In this folder, create new JSP
file named index.jsp as below:
</body>
</html>
Output:
57
Viva Questions:
1. What is Servlet?
2. What is JSP?
3. What are uses of XML file?
4. Define JSP Tag.
5. Define Implicit object.
58
EXPERIMENT NO. - 11
AIM- Write a JSP which insert the details of the 3 or 4 users who register with the web
site by using registration form. Authenticate the user when he submits the login form
using the user name and password from the database.
Procedure:
Code/Method:
packagecom.cse;
public class JumpString {
Output:
The given strings are: food and door
The string after concatination are:
VIVA Questions:
59
EXPERIMENT NO. - 12
AIM- Design and implement a simple shopping cart example with session tracking API.
Procedure:
Objective:
To design and implement a simple shopping cart application using Node.js and Express.js
that allows users to add items to their cart, view the cart contents, and manage session
tracking to maintain the cart's state.
Theory:
Key Concepts:
Procedure:
Code/Method:
Step 1: Set Up a New Node.js Project
mkdir shopping-cart
cd shopping-cart
60
2. Initialize a new Node.js project:
npm init –y
// Middleware
app.use(bodyParser.json());
app.use(session({
secret: 'your_secret_key', // Replace with a secure key in production
resave: false,
saveUninitialized: true,
cookie: { secure: false } // Set to true if using HTTPS
}));
// Sample product data (in a real application, this could be retrieved from a database)
const products = [
{ id: 1, name: 'Laptop', price: 50000 },
{ id: 2, name: 'Mobile Phone', price: 15000 },
{ id: 3, name: 'Headphones', price: 2000 }
];
if (product) {
req.session.cart.push(product);
res.json({ message: 'Product added to cart', cart: req.session.cart });
} else {
res.status(404).json({ message: 'Product not found' });
}
});
node app.js
62
Expected Response:
Viva Questions:
63