0% found this document useful (0 votes)
6 views

WebTech Lab

The document outlines practical exercises for a Web Technology Lab course at JMS Institute of Technology, covering HTML, CSS, JavaScript, XML, and Node.js. It includes objectives for creating web pages, forms, and scripts for data validation, as well as examples of code for a student entry form and a responsive website. The document serves as a practical guide for students to develop web applications and understand web technologies.

Uploaded by

nadeemmehraj368
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

WebTech Lab

The document outlines practical exercises for a Web Technology Lab course at JMS Institute of Technology, covering HTML, CSS, JavaScript, XML, and Node.js. It includes objectives for creating web pages, forms, and scripts for data validation, as well as examples of code for a student entry form and a responsive website. The document serves as a practical guide for students to develop web applications and understand web technologies.

Uploaded by

nadeemmehraj368
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

JMS INSTITUTE OF TECHNOLOGY GHAZIABAD

Department of Computer Science & Engineering

Practical File
Web Technology Lab (BCS 552)
Session 2024-25

SUBMITTED BY SUBMITTED TO
S. NO EXPERIMENT TITLE DATE SIGNATURE
1. Write HTML program
for designing your
institute
website. Display departmental
information of your institute
on
the website
2. Write HTML program to
design an entry form for
student
details/employee
information/faculty
details.
3. Write programs using HTML
and Java Script for validation
of input data
4. Develop a responsive website
using CSS and HTML.
Websitemay be for
tutorial/blogs/commercial
website.
5. Write a program in XML for
creation of DTD, which
specifies set of rules. Create a
style sheet in CSS/ XSL &
display the
document in internet explorer.
6. Create a Java Bean for
Employee information (EmpID,
Name, Salary, Designation
and Department)
7. 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
8 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
9 Develop a script that
uses MongoDB's
aggregation framework
to perform
operations like
grouping, filtering, and
sorting. For
instance, aggregate user data
to find the average age of
users in different cities.
10 Design and implement a
simple shopping cart example
with
session tracking API.
PROGRAM No.: -1
1.1 OBJECTIVE : Write HTML program for designing your institute website. Display
departmental information of your institute on the website
1.2 Theory :
Introduction:
HTML stands for Hyper Text Markup Language. HTML is the computer language that is used to
create documents for display on the web stary editors exist to create Web Pages - Word, Front
Page, and Draam 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 Leaming HTML involves finding out what
togs are used to mark the parts of a document and how these tags are med 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.
1. BGCOLOR="white" Sets the background color (other color names red, black, blue etc.)
2. TEXT-"black" Sets the body text color
3. LINK "blue" Sets the unvisited hypertext links
4. VLINK="purple" Sets the visited hypertext links
5.
ALINK="red" Sets the active hypertext links (the color of the hypertext link when you have your
mouse button depressed)
1.3 Code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AKTU Institute Website</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f9;
color: #333;
}
header {
background-color: #004080;
color: white;
padding: 20px;
text-align: center;
}
nav {
background-color: #0066cc;
padding: 10px;
text-align: center;
}
nav a {
color: white;
margin: 0 15px;
text-decoration: none;
font-weight: bold;
}
nav a:hover {
text-decoration: underline;
}
section {
padding: 20px;
}
.department {
border: 1px solid #ddd;
padding: 15px;
margin: 15px 0;
background-color: white;
border-radius: 8px;
}
.department h3 {
color: #004080;
}
footer {
background-color: #004080;
color: white;
text-align: center;
padding: 10px 0;
position: fixed;
bottom: 0;
width: 100%;
}
</style>
</head>
<body>
<header>
<h1>Welcome to AKTU Institute</h1>
<p>Your Gateway to Excellence in Education</p>
</header>

<nav>
<a href="#about">About Us</a>
<a href="#departments">Departments</a>
<a href="#contact">Contact</a>
</nav>

<section id="about">
<h2>About AKTU Institute</h2>
<p>AKTU Institute is a premier educational institution dedicated to providing quality
education and fostering innovation. We offer a wide range of programs across various disciplines
to shape future leaders and innovators.</p>
</section>

<section id="departments">
<h2>Departments</h2>

<div class="department">
<h3>Computer Science and Engineering</h3>
<p>Our CSE department focuses on cutting-edge technologies like AI, ML, and Data
Science. We aim to develop the next generation of tech leaders.</p>
</div>

<div class="department">
<h3>Electronics and Communication Engineering</h3>
<p>The ECE department emphasizes embedded systems, IoT, and wireless
communication, ensuring students are ready for industry challenges.</p>
</div>

<div class="department">
<h3>Mechanical Engineering</h3>
<p>Offering hands-on experience in CAD/CAM, robotics, and thermodynamics, our ME
department nurtures innovative mechanical engineers.</p>
</div>

<div class="department">
<h3>Civil Engineering</h3>
<p>With expertise in structural design, water resources, and sustainable construction, our
CE department builds a better future.</p>
</div>

<div class="department">
<h3>Management Studies</h3>
<p>Our management programs blend theoretical knowledge with practical insights to
prepare students for leadership roles.</p>
</div>
</section>

<section id="contact">
<h2>Contact Us</h2>
<p>Address: AKTU Institute, Knowledge Park, Lucknow, UP</p>
<p>Email: [email protected]</p>
<p>Phone: +91-123-456-7890</p>
</section>

<footer>
<p>&copy; 2024 AKTU Institute. All Rights Reserved.</p>
</footer>
</body>
</html>
1.4 Output:
PROGRAM No -2
2.1 OBJECTIVE : Write HTML program to design an entry form for student
details/employee information/faculty details
2.2 Theory :
Introduction:
HTML Forms
HTML Forms are required to collect different kinds of user inputs, such as contact details like
name, email address, phone numbers, or detach like credit card information, etc.
Forms contain special elements called controls like input box, checkboxes, radio-buttons, submit
buttons, etc. Users generally complete a form by modifying as controls eg. entering text selecting
items, etc. and submitting this form to a web server for processing
The <form> tag is used to create an HTML form. Here's a simple example of a login form

Input Element
This is the most commonly used element within HTML forms. It allows you to specify various
types of user input fields, depending on the type attribute. An input clement can be of type test
field, checkbox, password field, radio button, submit button, react button, etc. and several age input
types introduced in HTML5
Text Fields Text fields are one line areas that allow the user to input text Single-line text input
controls are created using an input element, whose type attribute has a value of text. Here's an
example of a single-line text input used to take full Name
Password Field
Password fields are similar to text fields. The only difference is, characters in a password field are
masked i.e. shown as asterisks or dots. This is to prevent others from reading the password on the
screen. This is also a single-line text input controls created using an input element where type
attribute has a value of password
Here's an example of a single-line password input used to take user password
Radio Buttons
Radio buttons are used to let the user select exactly one option from a pre-defined set of options It
is created using an <input> element whose type attribute has a value of radio
Checkboxes
Checkboxes allows the user to select one or more option from a pre-defined set of optans . It is
created using an <input> element whose type attribute has a value of checkbox
2.3 Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Entry Form</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
form {
max-width: 400px;
margin: 0 auto;
}
label {
display: block;
margin: 10px 0 5px;
}
input, select, button {
width: 100%;
padding: 8px;
margin-bottom: 10px;
}
.gender-options {
display: flex;
justify-content: space-between;
}
.gender-options label {
display: inline;
margin-right: 10px;
}
</style>
</head>
<body>
<h1>Student Entry Form</h1>
<form action="#" method="post">
<label for="student-name">Student Name:</label>
<input type="text" id="student-name" name="studentName" required>

<label for="father-name">Father's Name:</label>


<input type="text" id="father-name" name="fatherName" required>

<label>Sex:</label>
<div class="gender-options">
<label><input type="radio" name="gender" value="Male" required> Male</label>
<label><input type="radio" name="gender" value="Female"> Female</label>
<label><input type="radio" name="gender" value="Other"> Other</label>
</div>

<label for="password">Password:</label>
<input type="password" id="password" name="password" required>

<label for="dob">Date of Birth:</label>


<input type="date" id="dob" name="dob" required>
<label for="state">State:</label>
<select id="state" name="state" required>
<option value="">--Select State--</option>
<option value="State1">State 1</option>
<option value="State2">State 2</option>
<option value="State3">State 3</option>
<option value="State4">State 4</option>
</select>

<button type="submit">Submit</button>
</form>
</body>
</html>
2.4 Output
PROGRAM -3
3.1 OBJECTIVE : Write programs using HTML and Java Script for validation of input
data

3.2 Introduction:
HTML Forms
HTML Forms are required to collect different kinds of user inputs, such as contact details like
name, email address, phone numbers, or detach like credit card information, etc.
Forms contain special elements called controls like input box, checkboxes, radio-buttons, submit
buttons, etc. Users generally complete a form by modifying as controls eg. entering text selecting
items, etc. and submitting this form to a web server for processing
The <form> tag is used to create an HTML form. Here's a simple example of a login form

Input Element
This is the most commonly used element within HTML forms. It allows you to specify various
types of user input fields, depending on the type attribute. An input clement can be of type test
field, password field, submit button, , etc. and several age input types introduced in HTML5
Password Field
Password fields are similar to text fields. The only difference is, characters in a password field are
masked i.e. shown as asterisks or dots. This is to prevent others from reading the password on the
screen. This is also a single-line text input controls created using an input element where type
attribute has a value of password
3.3 Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Input Validation Form</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
background-color: #f9f9f9;
}
form {
max-width: 400px;
margin: auto;
padding: 20px;
background: white;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
input {
width: 100%;
padding: 10px;
margin: 10px 0;
border: 1px solid #ccc;
border-radius: 4px;
}
button {
padding: 10px 20px;
background-color: #28a745;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #218838;
}
.error {
color: red;
font-size: 0.9em;
}
</style>
</head>
<body>
<h2 style="text-align: center;">Registration Form</h2>
<form id="registrationForm" onsubmit="return validateForm()">
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your name">
<span id="nameError" class="error"></span>

<label for="email">Email:</label>
<input type="email" id="email" name="email" placeholder="Enter your email">
<span id="emailError" class="error"></span>

<label for="password">Password:</label>
<input type="password" id="password" name="password" placeholder="Enter a strong
password">
<span id="passwordError" class="error"></span>

<label for="phone">Phone Number:</label>


<input type="text" id="phone" name="phone" placeholder="Enter your phone number">
<span id="phoneError" class="error"></span>
<button type="submit">Submit</button>
</form>
<script>
function validateForm() {
let isValid = true;
// Clearing previous error messages
document.getElementById("nameError").innerText = "";
document.getElementById("emailError").innerText = "";
document.getElementById("passwordError").innerText = "";
document.getElementById("phoneError").innerText = "";
// Fetching input values
const name = document.getElementById("name").value.trim();
const email = document.getElementById("email").value.trim();
const password = document.getElementById("password").value.trim();
const phone = document.getElementById("phone").value.trim();
// Name Validation
if (name === "") {
document.getElementById("nameError").innerText = "Name is required.";
isValid = false;
}
// Email Validation
const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
if (!emailPattern.test(email)) {
document.getElementById("emailError").innerText = "Enter a valid email address.";
isValid = false;
}
// Password Validation
if (password.length < 6) {
document.getElementById("passwordError").innerText = "Password must be at least 6
characters long.";
isValid = false;
}
// Phone Number Validation
const phonePattern = /^[0-9]{10}$/;
if (!phonePattern.test(phone)) {
document.getElementById("phoneError").innerText = "Enter a valid 10-digit phone
number.";
isValid = false;
}
return isValid;
}
</script>
</body>
</html>

3.4 Output
PROGRAM No -4
4.1 OBJECTIVE : Develop a responsive website using CSS and HTML. Website may be for
tutorial/blogs/commercial website.

4.2 Theory
Introduction:
Responsive web design is a technique used to create web pages that adjust their layout and content
dynamically based on the screen size and resolution of the user's device. This ensures optimal
viewing experiences across desktops, tablets, and mobile devices. CSS media queries play a crucial
role in designing responsive websites by allowing styles to be applied conditionally.
In this experiment, we will develop a responsive website suitable for a blog/tutorial platform. The
site will include a header, navigation menu, main content area, and a footer. The design will adapt
to different screen sizes for better usability.

HTML Structure
HTML provides the semantic structure of a web page. A basic responsive webpage has the
following main components:
1. Header: Contains the website logo and navigation menu.
2. Main Content: Includes articles, blog posts, or tutorials.
3. Sidebar (Optional): Displays additional links or ads.
4. Footer: Includes contact information and copyright notice
CSS and Media Queries
CSS is used to style the webpage, including layout adjustments, font styling, and colors. Media
queries are used to apply different styles depending on the screen size.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Blog</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<div class="logo">My Blog</div>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
</header>
<main>
<section class="content">
<h1>Welcome to My Blog</h1>
<p>This is a responsive website designed to adjust to any screen size. It includes a header,
navigation, content section, and a footer.</p>
</section>
<aside class="sidebar">
<h2>Sidebar</h2>
<ul>
<li><a href="#">Recent Posts</a></li>
<li><a href="#">Categories</a></li>
<li><a href="#">Archives</a></li>
</ul>
</aside>
</main>
<footer>
<p>&copy; 2024 My Blog. All rights reserved.</p>
</footer>
</body>
</html>
4.3 Cascading style sheet:
/* General Reset */
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
line-height: 1.6;
margin: 0;
padding: 0;
}
/* Header Styles */
header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px;
background: #333;
color: white;
}

header .logo {
font-size: 1.5em;
font-weight: bold;
}
header nav ul {
list-style: none;
display: flex;
}
header nav ul li {
margin-left: 20px;
}
header nav ul li a {
text-decoration: none;
color: white;
padding: 5px 10px;
}
header nav ul li a:hover {
background: #555;
border-radius: 5px;
}
/* Main Content Styles */
main {
display: flex;
justify-content: space-between;
margin: 20px;
gap: 20px;
}
.content {
flex: 3;
padding: 20px;
background: #f9f9f9;
border-radius: 8px;
}
.sidebar {
flex: 1;
padding: 20px;
background: #efefef;
border-radius: 8px;
}

/* Footer Styles */
footer {
text-align: center;
padding: 20px;
background: #333;
color: white;
margin-top: 20px;
}
/* Responsive Design */
@media (max-width: 768px) {
header {
flex-direction: column;
text-align: center;
}
header nav ul {
flex-direction: column;
margin-top: 10px;
}
main {
flex-direction: column;
}
.content, .sidebar {
flex: 1;
}
}

4.4 Output
Program No - 5
5.1 Objective : Write a program in XML for creation of DTD, which specifies set of rules.
Create a style sheet in CSS/ XSL & display the document in internet explorer.

5.2 Theory:

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 emply 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
5.3 Types:

DTD can be classified on its declaration basis in the XML document, such as
1.Internal DTD
2.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 elensent DTD identifier

declaration)

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 identifiers: 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, is called external subset
• The square brackets[] enclose an optional list of entity declarations called internal
subset
Internal DTD:
A DTD a referred to as an internal DTD if elements are declared within the XML files. To reference
a as internal DTD, standalone attribute in XML declaration must be set to yes. This means the
declaration works independent of external source
Syntax
The syntax of internal DTD is as shown:

<!DOCTYPE root-element [element-declarations]>

where rood-element is the name of root element and element-declarations is where you declare the
elements
Example
Following is a simple example of internal DTD

xml version="1.0" encoding="UTF-8" standalone = "yes"?>


<!DOCTYPE address [
<TELEMENT address (name, company, phone
<!ELEMENT name (#PCDATA)
<!ELEMENT company (#PCDATA)
<!ELEMENT phone (#PCDATA)
]>
<address>
<name>Tanmay Patil/name>
<company Tutorials Point company>
<phone (011) 123-4567</phone
<address>

5.4 External DTD:


In external DTD elements are declared outside the XML file. They are accessed by specifying the
system attributes which may be either the legal did file or a valid URL. To reference it as external
DTD, standalone attribute in the XML declaration must be set as no. This means, declaration
includes information from the external source
Syntax
Following is the syntax for external DTD

<!DOCTYPE root-element SYSTEM "file-name">


where file-name is the file with did extension

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

<!DOCTYPE address SYSTEM "address.dtd">

<address>

<name>Tanmay Patil</name>

<company>Tutorials Point/company

<phone>(011) 123-4567</phone>

</address>

The content of the DTD file address.dtd are as shown

<'ELEMENT address (name, company, phone)>

<'ELEMENT name (#PCDATA)>

<'ELEMENT company (#PCDATA)

<!ELEMENT phone (#PCDATA)>

5.5 XSLT : Extensible Stylesheet Language Transformation commonly awn as XBLT is a way to
transform the XML documents the forms such HTML as
<xsl: template> defines a way to reuse templates in order to generate the desired output for nodes
of a particular type/context .various template are used with the template like name, match, mode
priority.
<xsl: value-of> tag puts the value of the selected node as per XPath expression, as text.
Declaration : Following is the syntax declaration of <xsl:value-of> element.
<xsl :value-of
select Expression
disable - output-escaping = “Yes” | “no”>
</xsl :value-of>
<xsl:for - each> tag applies a template repeatedly for each node.
5.6 Declaration: Following is the syntax declaration of <xsl:for-each> element
<xsl:for- each
select Expression >
</xal:for- each>
<xsl:sort> tag specifies a sort criteria on the nodes.
Declaration
Following is the syntax declaration of <xsl: sort> element.
<xsl:sort
select string-expression
lang= { nmtoken }
data-type("text" | "number" | Qname }
order={“ascending”|”decending”}
Case-Order={“Upper-first” |”Lower – first”}>
</xsl:sort>
<xsl:if> tag specifies a conditional test against the content of nodes
Declaration
Following is the syntax declaration of <xsl:if> element.
<xsl:if
test = boolean-expression >
</xsl:if>
<xsl : choose> tag specified a multiple condition tests against the content of nodes in conjuction
with the <xsl : when > element .
Declaration Following is the syntax declaration of <xsl : choose> element
<xsl : choose>
</xsl : choose>
Output: In Internet Explorer
Title Artist
Empire Burlesque Bob Dylan
Hide your heart Bonnie Tyer
5.7 XML

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


<!DOCTYPE note SYSTEM “Note.dtd”>
<note>
<to>Tove</to>
<form>Janie</form>
<heading> Reminder</heading>
<body>Don’t forget me this weekend !</body>
</note>

5.8 DTD

<!DOCTYPE note
[
!ELEMENT note (to ,form,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCADATA)><!ELEMENT heading (#(PCDATA)>
<!ELEMENT body (#PACDATA)>
]>

5.9 Output
This XML file does not appear to have any style information associated with it .The document tree
is shown below
<note>
<to> Tove </to>
,<from> Janir</from>
<heading> Reminder</heading>
<body> Don’t forget to me this weekend</body>
<footer> Writer : Donald Duck . copyright : W3school .</footer>
</note>
Program No 6
6.1 Objective : Create a Java Bean for Employee information (EmpID, Name, Salary,
Designation and Department)
6.2 Code
// Employee.java
import java.io.Serializable;

public class Employee implements Serializable {


private int empID;
private String name;
private double salary;
private String designation;
private String department;

// Default Constructor
public Employee() {
}

// Parameterized Constructor
public Employee(int empID, String name, double salary, String designation, String department)
{
this.empID = empID;
this.name = name;
this.salary = salary;
this.designation = designation;
this.department = department;
}

// Getter and Setter Methods


public int getEmpID() {
return empID;
}

public void setEmpID(int empID) {


this.empID = empID;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public double getSalary() {


return salary;
}

public void setSalary(double salary) {


this.salary = salary;
}

public String getDesignation() {


return designation;
}

public void setDesignation(String designation) {


this.designation = designation;
}

public String getDepartment() {


return department;
}

public void setDepartment(String department) {


this.department = department;
}

// toString Method for Displaying Employee Information


@Override
public String toString() {
return "Employee [EmpID=" + empID + ", Name=" + name + ", Salary=" + salary +
", Designation=" + designation + ", Department=" + department + "]";
}
}

// Employee.java
import java.io.Serializable;

public class Employee implements Serializable {


private int empID;
private String name;
private double salary;
private String designation;
private String department;
// Default Constructor
public Employee() {
}

// Parameterized Constructor
public Employee(int empID, String name, double salary, String designation, String department)
{
this.empID = empID;
this.name = name;
this.salary = salary;
this.designation = designation;
this.department = department;
}

// Getter and Setter Methods


public int getEmpID() {
return empID;
}

public void setEmpID(int empID) {


this.empID = empID;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public double getSalary() {


return salary;
}

public void setSalary(double salary) {


this.salary = salary;
}

public String getDesignation() {


return designation;
}

public void setDesignation(String designation) {


this.designation = designation;
}

public String getDepartment() {


return department;
}

public void setDepartment(String department) {


this.department = department;
}

// toString Method for Displaying Employee Information


@Override
public String toString() {
return "Employee [EmpID=" + empID + ", Name=" + name + ", Salary=" + salary +
", Designation=" + designation + ", Department=" + department + "]";
}
}
6.3 Output
Program No - 7
7.1 Objective : 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.
What is a Command-Line Utility: A command-line utility is a program designed to be executed
directly in the command line or terminal.
7.2 Key Concepts in Building Node.js Utilities:
a) Command-Line Arguments
• Process Object: Node.js provides the process.argv array to access arguments passed to the
script.
b) Argument Parsing
• Libraries like commander or yargs simplify argument parsing, allowing options and flags.
c) File System Operations
• The fs module in Node.js allows reading, writing, and modifying files
d) Asynchronous Operations
• Many Node.js functions are asynchronous. For example, fetching data or reading files can
use callbacks, promises, or async/await.
e) Making Scripts Executable
• Add a shebang (#!/usr/bin/env node) to the top of the file.
• Use chmod +x script.js to make the file executable.
f) Global Installation
• Packaging the script and installing it globally via npm install -g allows the utility to run
from anywhere without typing node.

3. Common Tasks for Command-Line Utilities


1. Text Manipulation: Convert text to uppercase, lowercase, or perform search and replace.
2. Mathematical Calculations: Calculate factorials, Fibonacci numbers, or perform basic
arithmetic.
3. Data Generation: Generate random passwords, UUIDs, or mock data for testing.
4. File Operations: Read, write, or manipulate files.
5. API Interaction: Fetch data from APIs and display it in the terminal.
7.3 Code

#!/usr/bin/env node

const { Command } = require('commander');


const program = new Command();

// Utility function to generate a random password


function generatePassword(length, useNumbers, useSpecial) {
const alphabets = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
const numbers = '0123456789';
const specialChars = '!@#$%^&*()_+-=[]{}|;:,.<>?';

let characters = alphabets;


if (useNumbers) characters += numbers;
if (useSpecial) characters += specialChars;

let password = '';


for (let i = 0; i < length; i++) {
const randomIndex = Math.floor(Math.random() * characters.length);
password += characters[randomIndex];
}
return password;
}

// Configure the command-line tool


program
.version('1.0.0')
.description('A simple random password generator')
.option('-l, --length <number>', 'Length of the password', '16')
.option('-n, --numbers', 'Include numbers in the password')
.option('-s, --special', 'Include special characters in the password')
.action((options) => {
const length = parseInt(options.length, 10);
const password = generatePassword(length, options.numbers, options.special);
console.log(`Generated Password: ${password}`);
});

// Parse command-line arguments


program.parse(process.argv);

for Running The Node :


After That you will show
in your Command line :

Now Run your Java Script using the node


File_Name.js
7.4 Output:
Program No 8
8.1 Objective : 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

8.2 What is the Goal of this Application?


The application:
1. Registers users by collecting their information through a form and storing it in a database.
2. Authenticates users by verifying their credentials (username and password) during login.
3. Key Concepts in this Application
a) Registration
• What happens?
o The user enters details like username, password, email, and phone.
o The form sends this data to the server when the user clicks "Submit."
b) Login and Authentication
• What happens?
o The user provides a username and password.
o The server compares this information against stored data in the database.
d) MySQL Database
• Purpose: To store user information like username, password, email, and phone.
• Structure: A users table with fields for each piece of user information.
e) JDBC (Java Database Connectivity)
• Purpose: To connect the JSP application to the MySQL database.
• How it works?
o JDBC API allows sending SQL queries to the database.
o Queries include inserting new user data or selecting user data for authentication.
8.3 Code
Step 1: Database Setup
CREATE DATABASE user_db;

USE user_db;

CREATE TABLE users (


id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
email VARCHAR(100),
phone VARCHAR(15)
);

Step 2 : Registration Page


<!DOCTYPE html>
<html>
<head>
<title>Registration</title>
</head>
<body>
<h1>Register Here</h1>
<form action="register_process.jsp" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<label for="phone">Phone:</label>
<input type="text" id="phone" name="phone"><br><br>
<button type="submit">Register</button>
</form>
</body>
</html>

Step 3: Registration Processing Page (register_process.jsp)


<%@ page import="java.sql.*" %>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
String email = request.getParameter("email");
String phone = request.getParameter("phone");

Connection conn = null;


PreparedStatement stmt = null;

try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user_db", "root",
"yourpassword");

String sql = "INSERT INTO users (username, password, email, phone) VALUES (?, ?, ?, ?)";
stmt = conn.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2, password);
stmt.setString(3, email);
stmt.setString(4, phone);

int rows = stmt.executeUpdate();

if (rows > 0) {
out.println("<h2>Registration successful!</h2>");
} else {
out.println("<h2>Registration failed. Please try again.</h2>");
}
} catch (Exception e) {
out.println("<h2>Error: " + e.getMessage() + "</h2>");
} finally {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
}
%>
<a href="login.jsp">Go to Login</a>

Step 4: Login Page


<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login Here</h1>
<form action="login_process.jsp" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<button type="submit">Login</button>
</form>
</body>
</html>

Step 5: Login Processing Page


<%@ page import="java.sql.*" %>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");

Connection conn = null;


PreparedStatement stmt = null;
ResultSet rs = null;

try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user_db", "root",
"yourpassword");

String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2, password);

rs = stmt.executeQuery();

if (rs.next()) {
out.println("<h2>Welcome, " + username + "!</h2>");
} else {
out.println("<h2>Invalid username or password. Please try again.</h2>");
}
} catch (Exception e) {
out.println("<h2>Error: " + e.getMessage() + "</h2>");
} finally {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
}
%>
<a href="login.jsp">Go Back</a>
OutPut:
Program No : 9
9.1 Objective : Develop a script that uses MongoDB's aggregation framework to perform
operations like grouping, filtering, and sorting. For instance, aggregate user data to find the
average age of users in different cities.
const { MongoClient } = require('mongodb');

async function aggregateUserData() {


const url = 'mongodb://localhost:27017'; // MongoDB connection string
const dbName = 'myDatabase'; // Your database name
const client = new MongoClient(url);

try {
// Connect to the MongoDB server
await client.connect();
console.log('Connected to MongoDB');

const db = client.db(dbName);
const usersCollection = db.collection('users'); // 'users' collection

// MongoDB Aggregation Pipeline


const pipeline = [
// Match stage: filter users who are older than 18
{
$match: {
age: { $gt: 18 }
}
},
// Group stage: group by city and calculate the average age
{
$group: {
_id: '$city', // Group by city
averageAge: { $avg: '$age' }, // Calculate average age
userCount: { $sum: 1 } // Count number of users in each city
}
},
// Sort stage: sort by average age in descending order
{
$sort: {
averageAge: -1 // Descending order of average age
}
}
];
// Execute aggregation
const result = await usersCollection.aggregate(pipeline).toArray();

console.log('Aggregation Result:', result);


} catch (err) {
console.error('Error occurred during aggregation:', err);
} finally {
// Close the MongoDB client connection
await client.close();
}
}

// Call the function to perform the aggregation


aggregateUserData();
Mongo Db
{
"_id": ObjectId("..."),
"name": "John Doe",
"age": 25,
"city": "New York"
}

9.2 Output
Program No - 10
10.1 Objective : Design and implement a simple shopping cart example with session tracking
API.
1. Session Management
Sessions allow the server to store user-specific data temporarily, such as the contents of their
shopping cart.
In this example, express-session is used to create and manage sessions for each user.
Each user's session is identified by a unique session ID, typically stored in a browser cookie

2. API Design
RESTful APIs are used to handle cart-related actions like adding items, removing items, and
viewing the cart.
Endpoints should be intuitive and follow HTTP methods (GET, POST, DELETE) for respective
operations.

3. Shopping Cart Data


A shopping cart is typically a collection of items stored in the user's session.
Each item in the cart includes product details like id, name, price, and quantity.

4.Server-Side State Management


The shopping cart data is stored server-side within the session object, ensuring the data persists
across multiple requests during a user's session.
This approach is safer than storing the cart directly on the client side.

5. Middleware
Middleware functions (like body parsers) process incoming requests to extract data or initialize
sessions.

const express = require('express'); // Import Express


const session = require('express-session'); // Import Express-session
const bodyParser = require('body-parser'); // Import Body-parser
const app = express(); // Create Express App
const PORT = 3000; // Define Port Number
// Middleware for Parsing and Sessions
app.use(bodyParser.urlencoded({ extended: true })); // Parse form
app.use(
session({
secret: 'simple_cart_secret', // Secret key for sessions
resave: false, // Do not save unchanged sessions
saveUninitialized: true, // Save new sessions
})
);
// Example Products
const products = [
{ id: 1, name: 'Pen', price: 10 },
{ id: 2, name: 'Notebook', price: 50 },
{ id: 3, name: 'Bag', price: 500 },
];
// Middleware to Set Up an Empty Cart if None Exists
app.use((req, res, next) => {
if (!req.session.cart) {
req.session.cart = []; // Initialize cart
}
next();
});
// Route: Homepage with Product List
app.get('/', (req, res) => {
let productList = products
.map(
(product) => `
<li>
${product.name} - ₹${product.price}
<form action="/add-to-cart" method="POST" style="display:inline;">
<input type="hidden" name="productId" value="${product.id}" />
<button type="submit">Add to Cart</button>
</form>
</li>
`
)
.join('');
res.send(`
<h1>Simple Shopping Cart</h1>
<ul>${productList}</ul>
<a href="/cart">Go to Cart</a>
`);
});
// Route: Add Product to Cart
app.post('/add-to-cart', (req, res) => {
const productId = parseInt(req.body.productId); // Get Product ID from Form
const product = products.find((p) => p.id === productId); // Find the Product
if (product) {
req.session.cart.push(product); // Add Product to Cart
}
res.redirect('/'); // Redirect to Homepage
});
// Route: View Cart
app.get('/cart', (req, res) => {
if (req.session.cart.length === 0) {
return res.send('<h1>Your Cart is Empty</h1><a href="/">Continue Shopping</a>');
}
const cartItems = req.session.cart
.map((item) => `<li>${item.name} - ₹${item.price}</li>`)
.join('');
const total = req.session.cart.reduce((sum, item) => sum + item.price, 0);
res.send(`
<h1>Your Cart</h1>
<ul>${cartItems}</ul>
<h3>Total: ₹${total}</h3>
<form action="/clear-cart" method="POST">
<button type="submit">Clear Cart</button>
</form>
<a href="/">Continue Shopping</a>
`);
});
// Route: Clear Cart
app.post('/clear-cart', (req, res) => {
req.session.cart = []; // Empty the Cart
res.redirect('/cart'); // Refresh Cart Page
});

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

10.2 Output

You might also like