0% found this document useful (0 votes)
12 views64 pages

WebTech Lab Mannual

guyg

Uploaded by

shashwat garg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views64 pages

WebTech Lab Mannual

guyg

Uploaded by

shashwat garg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

LIST OF PRACTICALS

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. Develop a responsive website using CSS and HTML. Website may be for tutorial/blogs/commercial website.

4. Write programs using HTML and Java Script for validation of input data.

5. Writing 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. 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.

9. Assume four users user1, user2, user3 and user4 having the passwords pwd1, pwd2,
pwd3 and pwd4 respectively. Write a servlet for doing the following. Create a Cookie and add
these four user ids 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.

10. Install a database (MySQL or Oracle). Create a table which should contain at least the
following fields: name, password, and email-id, phone number Write a java
program/servlet/JSP toconnect to that database and extract data from the tables and display
them. Insert the details ofthe users who register with the web site, whenever a new user clicks
the submit button in the registration page.

11. 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

12. Design and implement a simple shopping cart example with session tracking API.

Value Addition

Design and implement a simple shopping cart example with session tracking API.
Lab Outcome

¬ Students are able to develop a dynamic webpage by the use of java script and DHTML

¬ Students will be able to write a well formed / valid XML document.

¬ Students will be able to connect a java program to a DBMS and perform insert, update and
delete operations on DBMS table.
¬ Students will be able to write a server side java application called Servlet to catch form data
sent from client, process it and store it on database.
PROGRAM 1

Objective: Write HTML program for designing your institute website. Display
departmental information of your institute on the website.

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. Many editors exist to create Web Pages – Word, Front
Page, 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,
blue etc)
● 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)
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Institute Website</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f4;
}

header {
background-color: #003366;
color: #fff;
padding: 20px 0;
text-align: center;
}

header h1 {
margin: 0;
}

nav {
background-color: #005b99;
padding: 10px;
}

nav ul {
list-style-type: none;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
}

nav ul li {
margin: 0 15px;
}

nav ul li a {
color: white;
text-decoration: none;
font-weight: bold;
}

nav ul li a:hover {
text-decoration: underline;
}

section {
padding: 20px;
}

h2 {
color: #003366;
}

.department {
background-color: #fff;
padding: 15px;
margin-bottom: 15px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
</style>
</head>

<body>

<header>
<h1>Welcome to ABC Institute</h1>
</header>

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

<section id="home">
<h2>About Our Institute</h2>
<p>ABC Institute is committed to providing top-tier education and research opportunities. Explore our diverse
range of departments and programs below.</p>
</section>

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

<div class="department">
<h3>Department of Computer Science</h3>
<p>The Department of Computer Science offers courses in software development, data science, artificial
intelligence, and more. We prepare students to excel in the tech-driven world.</p>
</div>
<div class="department">
<h3>Department of Mechanical Engineering</h3>
<p>The Mechanical Engineering department provides students with hands-on experience in designing and
manufacturing machines. Our program is rooted in both theory and practical applications.</p>
</div>

<div class="department">
<h3>Department of Electrical Engineering</h3>
<p>The Electrical Engineering department focuses on developing skills in electronics, communication systems,
and power systems. Students gain exposure to cutting-edge technology and research.</p>
</div>

<div class="department">
<h3>Department of Civil Engineering</h3>
<p>The Civil Engineering department is dedicated to training students in the art of designing and
constructing infrastructure. Students participate in real-world projects and gain industry experience.</p>
</div>

<div class="department">
<h3>Department of Management Studies</h3>
<p>The Management Studies department provides a foundation in business administration, finance, marketing,
and leadership. Our graduates are prepared to lead in a global business environment.</p>
</div>
</section>

<footer>
<p>&copy; 2024 ABC Institute. All rights reserved.</p>
</footer>

</body>

</html>

Output:
PROGRAM-2

Objective: Write HTML program to design an entry form for student details/employee
information/faculty details

Theory:

HTML Forms
HTML Forms are required to collect different kinds of user inputs, such as contact details like
name, email address, phone numbers, or details like credit card information, etc.
Forms contain special elements called controls like inputbox, checkboxes, radio-buttons, submit
buttons, etc. Users generally complete a form by modifying its controls e.g. 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 element can be of type
text field, checkbox, password field, radio button, submit button, reset button, etc. and several
new input types introduced in HTML5.
The most used input types are described below.

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

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 whose
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 options. It is
created using an <input> element whose type attribute has a value of checkbox.
File Select box

The file fields allow a user to browse for a local file and send it as an attachment to the form
data. It normally rendered as a text box with a button that enables the user to browse for a file.
However, the user can also type the path and name of the file in the text box.This is also created
using an <input> element, whose type attribute value is set to file.
Textarea

Textarea is a multiple-line text input control that allows a user to enter more than one line of text.
Multi-line text input controls are created using an <textarea> element.
Select Boxes
A select box is a drop down list of options that allows user to select one or more option from a
pull-down list of options. Select box is created using the <select> 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.
Most frequently used form attributes are:

Name The name of the form.


action URL of the program that processes the information submitted via form.
method The HTTP method that the browser uses to submit the form. Possible values are get
and post.
target A name or keyword indicating the target page where the result of the script will be displayed

CODE:-

1. HTML Form (student_form.html)

This HTML form collects student details like name, age, gender, and course.

<!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;
background-color: #f4f4f9;
margin: 0;
padding: 0;
}
.container {
width: 50%;
margin: 50px auto;
padding: 20px;
background-color: #fff;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
}
h2 {
text-align: center;
}
label {
display: block;
margin: 10px 0 5px;
}
input, select {
width: 100%;
padding: 8px;
margin: 5px 0 15px;
border: 1px solid #ddd;
border-radius: 4px;
}
button {
width: 100%;
padding: 10px;
background-color: #5cb85c;
border: none;
color: white;
font-size: 16px;
cursor: pointer;
border-radius: 4px;
}
button:hover {
background-color: #4cae4c;
}
</style>
</head>
<body>

<div class="container">
<h2>Student Entry Form</h2>
<form action="submit_form.php" method="POST">
<label for="name">Full Name</label>
<input type="text" id="name" name="name" required>

<label for="age">Age</label>
<input type="number" id="age" name="age" required>

<label for="gender">Gender</label>
<select id="gender" name="gender" required>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select>

<label for="course">Course</label>
<input type="text" id="course" name="course" required>

<button type="submit">Submit</button>
</form>
</div>
</body>
</html>

2. PHP Script (submit_form.php)

This PHP script receives the form data and stores it in a MySQL database. Make sure your database is set up with
the correct table to store the student data.

<?php
// Database connection details
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "school";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Get data from the form


$name = $_POST['name'];
$age = $_POST['age'];
$gender = $_POST['gender'];
$course = $_POST['course'];

// Prepare SQL query to insert data into the database


$sql = "INSERT INTO students (name, age, gender, course)
VALUES ('$name', '$age', '$gender', '$course')";

// Execute query
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

// Close connection
$conn->close();
?>

3. MySQL Database Setup

Before running the PHP script, ensure that you have a MySQL database set up. Here is an example of how to
create the students table:

CREATE DATABASE school;

USE school;

CREATE TABLE students (


id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
age INT NOT NULL,
gender VARCHAR(10) NOT NULL,
course VARCHAR(100) NOT NULL
);
Output:
PROGRAM 3

Objective: Develop a responsive website using CSS and HTML. Website may be for
tutorial/blogs/commercial website.

<!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>
<style>
*{
box-sizing: border-box;
margin: 0;
padding: 0;
}

body {
font-family: Arial, sans-serif;
line-height: 1.6;
background-color: #f4f4f4;
}

header {
background: #333;
color: #fff;
padding: 10px 0;
text-align: center;
}

header h1 {
margin: 0;
font-size: 2.5em;
}

nav {
display: flex;
justify-content: center;
background: #444;
padding: 10px;
}

nav ul {
list-style-type: none;
}

nav ul li {
display: inline;
margin: 0 15px;
}

nav ul li a {
color: #fff;
text-decoration: none;
}

nav ul li a:hover {
text-decoration: underline;
}

.container {
display: flex;
flex-wrap: wrap;
padding: 20px;
margin: 0 auto;
}

.main-content {
flex: 3;
background: white;
padding: 20px;
margin-right: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.sidebar {
flex: 1;
background: white;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.main-content h2,
.sidebar h3 {
color: #333;
}

.main-content p {
margin-bottom: 20px;
}

footer {
background: #333;
color: #fff;
text-align: center;
padding: 10px 0;
margin-top: 20px;
}
/* Responsive Design */
@media (max-width: 768px) {
.container {
flex-direction: column;
}

.main-content,
.sidebar {
margin: 0 0 20px 0;
}
}

@media (max-width: 600px) {


header h1 {
font-size: 1.8em;
}

nav ul li {
display: block;
text-align: center;
margin: 5px 0;
}
}
</style>
</head>

<body>

<header>
<h1>My Awesome Blog</h1>
</header>

<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#blog">Blog</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>

<div class="container">
<div class="main-content">
<h2>Welcome to My Blog</h2>
<p>Welcome to my blog where I share my thoughts on web development, programming, and
technology. Stay tuned
for updates on the latest trends in the tech industry and helpful tutorials for developers of all skill
levels.</p>
<h2>Latest Blog Post</h2>
<p>In today's post, we will dive into the world of responsive design. A responsive website is
designed to
provide an optimal viewing experience, regardless of the device used to access it. Whether you're on
a
desktop, tablet, or smartphone, your website should look and function seamlessly. Follow along as
we
explore the best practices in responsive web development.</p>
</div>

<div class="sidebar">
<h3>Recent Posts</h3>
<ul>
<li><a href="#">Understanding Flexbox</a></li>
<li><a href="#">CSS Grid: A Comprehensive Guide</a></li>
<li><a href="#">JavaScript ES6 Features</a></li>
<li><a href="#">Top 5 Web Design Trends in 2024</a></li>
</ul>
</div>
</div>

<footer>
<p>&copy; 2024 My Awesome Blog. All Rights Reserved.</p>
</footer>

</body>

OUTPUT :
PROGRAM 4

Objective: Write programs using HTML and Java Script for validation of input data.

<!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>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
padding: 20px;
}

.container {
max-width: 600px;
margin: 0 auto;
background-color: #fff;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

h2 {
text-align: center;
color: #333;
}

label {
font-weight: bold;
display: block;
margin-top: 10px;
}

input[type="text"],
input[type="email"],
input[type="password"],
input[type="tel"],
select {
width: 100%;
padding: 10px;
margin-top: 5px;
border: 1px solid #ccc;
border-radius: 5px;
}
input[type="submit"] {
background-color: #005b99;
color: white;
padding: 10px;
border: none;
border-radius: 5px;
margin-top: 20px;
font-size: 16px;
cursor: pointer;
}

input[type="submit"]:hover {
background-color: #003366;
}

.error {
color: red;
font-size: 14px;
}
</style>
</head>

<body>

<div class="container">
<h2>Input Validation Form</h2>
<form id="myForm" 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 your password">
<span id="passwordError" class="error"></span>

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


<input type="tel" id="phone" name="phone" placeholder="Enter your phone number">
<span id="phoneError" class="error"></span>

<label for="department">Department:</label>
<select id="department" name="department">
<option value="">Select department</option>
<option value="computer_science">Computer Science</option>
<option value="mechanical_engineering">Mechanical Engineering</option>
<option value="electrical_engineering">Electrical Engineering</option>
<option value="civil_engineering">Civil Engineering</option>
</select>
<span id="departmentError" class="error"></span>

<input type="submit" value="Submit">


</form>
</div>

<script>
function validateForm() {
let isValid = true;

// Name Validation
const name = document.getElementById("name").value;
if (name === "") {
document.getElementById("nameError").innerText = "Name is required.";
isValid = false;
} else {
document.getElementById("nameError").innerText = "";
}

// Email Validation
const email = document.getElementById("email").value;
const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
if (email === "") {
document.getElementById("emailError").innerText = "Email is required.";
isValid = false;
} else if (!emailPattern.test(email)) {
document.getElementById("emailError").innerText = "Please enter a valid email address.";
isValid = false;
} else {
document.getElementById("emailError").innerText = "";
}

// Password Validation
const password = document.getElementById("password").value;
if (password.length < 6) {
document.getElementById("passwordError").innerText = "Password must be at least 6 characters.";
isValid = false;
} else {
document.getElementById("passwordError").innerText = "";
}

// Phone Number Validation


const phone = document.getElementById("phone").value;
const phonePattern = /^[0-9]{10}$/;
if (!phonePattern.test(phone)) {
document.getElementById("phoneError").innerText = "Phone number must be 10 digits.";
isValid = false;
} else {
document.getElementById("phoneError").innerText = "";
}
// Department Validation
const department = document.getElementById("department").value;
if (department === "") {
document.getElementById("departmentError").innerText = "Please select a department.";
isValid = false;
} else {
document.getElementById("departmentError").innerText = "";
}

return isValid;
}
</script>

</body>

</html>

OUTPUT:
PROGRAM 5

Objective: Writing 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.

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 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
Types: attributes those tags can contain, and
which tags can occur inside other
tags, among other properties.
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:

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.

Internal DTD
A DTD is referred to as an internal DTD if elements are declared within the XML files. To
reference it 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:

where root-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:

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

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 .dtd 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:

where file-namen is the file with .dtd extension.

Example
The following example shows external DTD usage:

<!DOCTYPE address SYSTEM "address.dtd">


<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>

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

<!ELEMENT name (#PCDATA)>


<!ELEMENT company (#PCDATA)>

XSLT
EXtensible Stylesheet Language Transformation commonly known as XSLT is a way to
transform the XML document into other formats such as XHTML.
<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.

Declaration
Following is the syntax declaration of <xsl:for-each> element
<xsl:for-each
select = Expression >
</xsl: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-expressionlang = {
nmtoken }
data-type = { "text" | "number" | QName }order = {
"ascending" | "descending" }
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 specifies a multiple conditional tests against the content of nodes in
conjunction with the <xsl:otherwise> and <xsl:when> elements.

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 Tyler
2.XML

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


<!DOCTYPE note SYSTEM "Note.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
DTD:
<!DOCTYPE note
[
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)><!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>

OUTPUT:
PROGRAM 6

Objective: Create a Java Bean for Employee information (EmpID, Name, Salary,
Designation and Department).

Employee.java

import java.io.Serializable;

public class Employee implements Serializable {

// Private member variables for Employee Information


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 for EmpID


public int getEmpID() {
return empID;
}

public void setEmpID(int empID) {


this.empID = empID;
}
// Getter and Setter methods for Name
public String getName() {
return name;
}

public void setName(String name) {


this.name = name;
}

// Getter and Setter methods for Salary


public double getSalary() {
return salary;
}

public void setSalary(double salary) {


this.salary = salary;
}

// Getter and Setter methods for Designation


public String getDesignation() {
return designation;
}

public void setDesignation(String designation) {


this.designation = designation;
}

// Getter and Setter methods for Department


public String getDepartment() {
return department;
}

public void setDepartment(String department) {


this.department = department;
}

// Method to display Employee Information


@Override
public String toString() {
return "Employee [EmpID=" + empID + ", Name=" + name + ",
Salary=" + salary
+ ", Designation=" + designation + ", Department=" + department +
"]";
}
}
Main.java
public class Main {
public static void main(String[] args) {
// Creating an Employee object using the parameterized constructor
Employee emp1 = new Employee(101, "Alice Smith", 60000,
"Software Engineer", "IT");

// Displaying the employee information


System.out.println(emp1.toString());

// Using setters to modify employee information


emp1.setSalary(65000);
emp1.setDesignation("Senior Software Engineer");

// Using getters to retrieve specific information


System.out.println("Updated Employee Information: ");
System.out.println("Name: " + emp1.getName());
System.out.println("Designation: " + emp1.getDesignation());
System.out.println("Salary: " + emp1.getSalary());
}
}

Output
PROGRAM 7

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.

Step 1: Set Up Your Node.js Environment


Make sure you have Node.js installed on your machine. You can check by running:
node -v
If you don’t have it installed, download it from nodejs.org.
Step 2: Create the Project Directory
1. Create a new directory for your project:
mkdir factorial-cli
cd factorial-cli
2. Initialize a new Node.js project:
npm init -y
Step 3: Create the Utility Script
1. Create a file named factorial.js:
touch factorial.js
2. Open factorial.js in your text editor and add the following code:
// factorial.js

// Function to calculate the factorial of a number


function factorial(n) {
if (n < 0) {
return "Factorial is not defined for negative numbers.";
}
if (n === 0 || n === 1) {
return 1;
}
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}

// Get the command line argument


const args = process.argv.slice(2);
const number = parseInt(args[0]);

// Calculate and display the factorial


if (isNaN(number)) {
console.log("Please provide a valid number.");
} else {
const result = factorial(number);
console.log(`The factorial of ${number} is ${result}.`);
}
Step 4: Run the Utility
1. In your terminal, run the following command to execute the script with a number:
node factorial.js 5
This should output:
The factorial of 5 is 120.
Step 5: Test the Utility
You can test the utility with different numbers:
• For zero:
node factorial.js 0
Output:
The factorial of 0 is 1.
• For negative numbers:
node factorial.js -3
Output:
Factorial is not defined for negative numbers.
• For non-numeric input:
node factorial.js hello
Output:
Please provide a valid number.
PROGRAM 8

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

Step 1: Set Up Your Environment


1. Install MongoDB: Make sure you have MongoDB installed and running on your machine. If you haven't
installed it yet, you can find installation instructions on the MongoDB website.
2. Install Node.js: If you don't have Node.js installed, download it from nodejs.org.
3. Create a New Project:
mkdir mongodb-aggregation
cd mongodb-aggregation
npm init -y
4. Install the MongoDB Driver:
npm install mongodb

Step 2: Create the User Data


Let's create a script to insert sample user data into a MongoDB collection.
1. Create a file named insertUsers.js:
touch insertUsers.js
2. Add the following code to insertUsers.js:
// insertUsers.js
const { MongoClient } = require('mongodb');

async function run() {


const client = new MongoClient('mongodb://localhost:27017');
try {
await client.connect();
const database = client.db('userDB');
const users = database.collection('users');

// Sample user data


const userData = [
{ name: 'Alice', age: 30, city: 'New York' },
{ name: 'Bob', age: 25, city: 'Los Angeles' },
{ name: 'Charlie', age: 35, city: 'New York' },
{ name: 'David', age: 40, city: 'Chicago' },
{ name: 'Eve', age: 22, city: 'Los Angeles' },
{ name: 'Frank', age: 28, city: 'Chicago' },
{ name: 'Grace', age: 35, city: 'New York' },
];

// Insert user data into the collection


const result = await users.insertMany(userData);
console.log(`${result.insertedCount} users were inserted.`);
} finally {
await client.close();
}
}
run().catch(console.dir);

Step 3: Run the User Data Insertion Script


1. Execute the script to insert users:
node insertUsers.js
Output:
7 users were inserted.

Step 4: Create the Aggregation Script


1. Create a file named aggregateUsers.js:
touch aggregateUsers.js
2. Add the following code to aggregateUsers.js:
// aggregateUsers.js
const { MongoClient } = require('mongodb');

async function run() {


const client = new MongoClient('mongodb://localhost:27017');
try {
await client.connect();
const database = client.db('userDB');
const users = database.collection('users');

// Aggregation pipeline
const pipeline = [
{
$group: {
_id: '$city', // Group by city
averageAge: { $avg: '$age' }, // Calculate average age
count: { $sum: 1 } // Count number of users in the city
}
},
{
$sort: { averageAge: 1 } // Sort by average age ascending
}
];

const result = await users.aggregate(pipeline).toArray();


console.log('Average age of users by city:');
result.forEach(city => {
console.log(`City: ${city._id}, Average Age: ${city.averageAge}, Count: ${city.count}`);
});
} finally {
await client.close();
}
}

run().catch(console.dir);

Step 5: Run the Aggregation Script


1. Execute the aggregation script:
node aggregateUsers.js
Output:
Average age of users by city:
City: Los Angeles, Average Age: 23.5, Count: 2
City: Chicago, Average Age: 34, Count: 2
City: New York, Average Age: 31.666666666666668, Count: 3
PROGRAM 9

Objective: Assume four users user1, user2, user3 and user4 having the passwords pwd1,
pwd2, pwd3 and pwd4 respectively. Write a servlet for doing the following.
i. Create a Cookie and add these four user id’s and passwords to this Cookie.
ii. Read the user id and passwords entered in the Login form (week1) and authenticate with
the values (user id and passwords) available in the cookies.
AIM:
User Authentication:
Assume four users user1, user2, user3 and user4 having the passwords pwd1, pwd2,
pwd3 and pwd4 respectively. Write a servelet 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 (week1) and authenticate
with the values (user id and passwords) available in the cookies.
If he is a valid user (i.e., user-name and password match) you should welcome him by
name (user-name) else you should display “You are not an authenticated user “. Use
init-parameters to do this. Store the user-names and passwords in the web.xml and
access them in the servlet by using the getInitParameters() method.
DESCRIPTION:
Servlet Life cycle:
1. Servlet class loading
2. Servlet Instantiation
3. call the init method
4. call the service method
5. call destroy method
Class loading and instantiation
If you consider a servlet to be just like any other Java program, except that it runs within a servlet
container, there has to be a process of loading the class and making it ready for requests. Servlets do not have
the exact equivalent of a main method that causes them to start execution.
When a web container starts it searches for the deployment descriptor (WEB.XML) for each of its web
applications. When it finds a servlet in the descriptor it will create an instance of the servlet class. At this
point the class is considered to be loaded (but not initialized).
The init method
The HttpServlet class inherits the init method from GenericServlet. The init method performs a role
slightly similar to a constructor in an “ordinary” Java program in that it allows initialization of an instance at
start up. It is called automatically by the servlet container and as it causes the application context
(WEB.XML) to be parsed and any initialization will be performed. It comes in two versions, one with a zero
parameter constructor and one that takes a ServletConfig parameter.
The servlet engine creates a request object and a response object. The servlet engine invokes the
servlet service() method, passing the request and response objects. Once the init method returns
the servlet is said to be placed into service. The process of using init to initialize servlets means
that it is possible to change configuration details by modifying the deployment descriptor without
having them hard coded in with your Java source and needing a re-compilation.
void init(ServletConfig sc)
Calling the service method
The service() method gets information about the request from the request object, processes
the request, and uses methods of the response object to create the client response. The service
method can invoke other methods to process the request, such as doGet(), doPost(), or methods
you write. The service method is called for each request processed and is not normally overridden
by the programmer.
The code that makes a servlet “go” is the. servlet
void service(ServletRequest req,ServletResponse res)
The destroy Method
Two typical reasons for the destroy method being called are if the container is shutting down or if the
container is low on resources. This can happen when the container keeps a pool of instances of servlets to
ensure adequate performance. If no requests have come in for a particular servlet for a while it may destroy it to
ensure resources are available for the servlets that are being requested. The destroy method is called only once,
before a servlet is unloaded and thus you cannot be certain when and if it is called.

void destroy()

ServletConfig Class
ServletConfig object is used by the Servlet Container to pass information to the Servlet during it's
initialization. Servlet can obtain information regarding initialization parameters and their values using
different methods of ServletConfig class initialization parameters are name/value pairs used to provide basic
information to the Servlet during it's initialization like JDBC driver name, path to database, username,
password etc.

Methods of ServletConfig class


Following are the four methods of this class :
● getInitParameter(String paramName) Returns value of the given parameter. If value of parameter
could not be found in web.xml file then a null value is returned.
● getInitParameterNames() Returns an Enumeration object containing all the names of initialization
parameters provided for this Servlet.
● getServletContext() Returns reference to the ServletContext object for this Servlet. It is similar to
getServletContext() method provided by HttpServlet class.
● getServletName() Returns name of the Servlet as provided in the web.xml file or if none is provided
then returns complete class path to the Servlet.

PROGRAM:
cologin.html:
<html>
<head>
<title> login Page </title>
<p style= "background:yellow; top:100px; left:250px; position:absolute; ">
</head>
<body>
<form ACTION="clogin">
<label> Login </label>
<input type="text" name="usr" size="20"> <br> <br>
<label> Password </label>
<input type="password" name="pwd" size="20"> <br> <br>
<input type="submit" value="submit">
</form>
</body>
</html>
cologin1.html
<html>
<head>
<title> login Page </title>
<p style= "background:yellow; top:100px; left:250px; position:absolute; ">
</head>
<body>
<form ACTION="clogin1">
<label> Login </label>
<input type="text" name="usr" size="20"> <br> <br>
<label> Password </label>
<input type="password" name="pwd" size="20"> <br> <br>
<input type="submit" value="submit">
</form>
</body>
</html>

Addcook.java:
import javax.servlet.* ;
import javax.servlet.http.*;
import java.io.*;
public class Addcook extends HttpServlet
{
String user,pas;
public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
Cookie c1=new Cookie("usr1","suni");
Cookie p1=new Cookie("pwd1","ani");
Cookie c2=new Cookie("usr2","abc");
Cookie p2=new Cookie("pwd2","123");
Cookie c3=new Cookie("usr3","def");
Cookie p3=new Cookie("pwd3","456");
Cookie c4=new Cookie("usr4","mno");
Cookie p4=new Cookie("pwd4","789");
res.addCookie(c1);
res.addCookie(p1);
res.addCookie(c2);
res.addCookie(p2);
res.addCookie(c3);
res.addCookie(p3);
res.addCookie(c4);
res.addCookie(p4);
out.println("COOKIE ADDED");
}
}
Clogin.java:
import javax.servlet.* ;
import javax.servlet.http.*;
import java.io.*;
public class Clogin extends HttpServlet
{
String user,pas;
public void service(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
user=req.getParameter("usr");
pas=req.getParameter("pwd");
Cookie[] c=req.getCookies();
for(int i=0;i<c.length;i++)
{
if((c[i].getName().equals("usr1")&&c[i+1].getName().equals("pwd1"))|| c[i].getName().equals("usr2")
&&c[i+1].getName().equals("pwd2"))||(c[i].getName().equals("usr3")&&
c[i+1].getName().equals("pwd3"))||(c[i].getName().equals("usr4")&& c[i+1].getName().equals("pwd4") ))
{
if((user.equals(c[i].getValue()) && pas.equals(c[i+1].getValue())) )
{
//RequestDispatcher rd=req.getRequestDispatcher("/cart.html");
rd.forward(req,res);
}
else
{
out.println("YOU ARE NOT AUTHORISED USER ");
//res.sendRedirect("/cookdemo/cologin.html");
}
}
}
}
}

Web.xml:
<web-app>
<servlet>
<servlet-name>him</servlet-name>
<servlet-class>Clogin</servlet-class>
</servlet>
<servlet>
<servlet-name>him1</servlet-name>
<servlet-class>Addcook</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>him</servlet-name>
<url-pattern>/clogin</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>him1</servlet-name>
<url-pattern>/clogin1</url-pattern>
</servlet-mapping>
</web-app>

OUTPUT:
2. Read the user id and passwords entered in the Login form (week1) and authenticate with the values (user id
and passwords) available in the cookies.
If he is a valid user (i.e., user-name and password match) you should welcome him by name (user-name) else
you should display “You are not an authenticated user “.
Use init-parameters to do this. Store the user-names and passwords in the webinf.xml and access them in the
servlet by using the getInitParameters() method.
home.html:
<html>
<head>
<title>Authentication</title>
</head>
<body>
<form action="ex1">
<label>Username </label>
<input type="text"size="20" name="user"><br><br>
password<input type="text" size="20" name="pwd"><br><br>
<input type="submit" value="submit">
</form>
</body>
</html>
Example1.java
import javax.servlet.*;
import java.io.*;
public class Example1 extends GenericServlet
{
private String user1,pwd1,user2,pwd2,user3,pwd3,user4,pwd4,user5,pwd5;
public void init(ServletConfig sc)
{
user1=sc.getInitParameter("username1");
pwd1=sc.getInitParameter("password1");

user2=sc.getInitParameter("username2");
pwd2=sc.getInitParameter("password2");
user3=sc.getInitParameter("username3");
pwd3=sc.getInitParameter("password3");
user4=sc.getInitParameter("username4");
pwd4=sc.getInitParameter("password4");
}
Public void service(ServletRequest req,ServletResponse res)throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
user5=req.getParameter("user");
pwd5=req.getParameter("pwd");

if((user5.equals(user1)&&pwd5.equals(pwd1))||(user5.equals(user2)&&pwd5.equals(pwd2))||(user5.equals(use
r3)&&pwd5.equals(pwd3))||(user5.equals(user4)&&pwd5.equals(pwd4)))
out.println("<p> welcome to"+user5.toUpperCase());
else
out.println("You are not authorized user");
}
}
web.xml:
<web-app>
<servlet>
<servlet-name>Example</servlet-name>
<servlet-class>Example1</servlet-class>
<init-param>
<param-name>username1</param-name>
<param-value>pvpsit</param-value>
</init-param>
<init-param>
<param-name>password1</param-name>
<param-value>cse</param-value>
</init-param>
<init-param>
<param-name>username2</param-name>
<param-value>1234</param-value>
</init-param>
<init-param>
<param-name>password2</param-name>
<param-value>4567</param-value>
</init-param>
<init-param>
<param-name>username3</param-name>
<param-value>cse</param-value>
</init-param>
<init-param>
<param-name>password3</param-name>
<param-value>pvpsit</param-value>
</init-param>
<init-param>
<param-name>username4</param-name>
<param-value>wt</param-value>
</init-param>
<init-param>
<param-name>password4</param-name>
<param-value>lab</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Example</servlet-name>
<url-pattern>/ex1</url-pattern>
</servlet-mapping>
</web-app>

OUTPUT
PROGRAM 10:

Objective: 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.

Theory:

CREATE TABLE "REGISTERUSER"


( "NAME" VARCHAR2(4000),
"PASS" VARCHAR2(4000),
"EMAIL" VARCHAR2(4000),
"PHONE" VARCHAR2(4000),
)
Example of Registration form in servlet

In this example, we have created the three pages.

● register.html
● Register.java
● web.xml

Register.html
In this page, we have getting input from the user using text fields and combobox. The information entered by
the user is forwarded to Register servlet, which is responsible to store the data into the database.

<html>
<body>
<form action="servlet/Register" method="post">

Name:<input type="text" name="userName"/><br/><br/>


Password:<input type="password" name="userPass"/><br/><br/>
Email Id:<input type="text" name="userEmail"/><br/><br/>
Phone Number:<input type="text" name="userPhone"/><br/><br/>

<br/><br/>
<input type="submit" value="register"/>

</form>
</body>
</html>
Register.java
This servlet class receives all the data entered by user and stores it into the database. Here, we are performing
the database logic. But you may separate it, which will be better for the web application.

import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class Register extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String in=request.getParameter("userName");
String p=request.getParameter("userPass");
String e=request.getParameter("userEmail");
String p=request.getParameter("userPhone");

try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

PreparedStatement ps=con.prepareStatement(
"insert into registeruser values(?,?,?,?)");

ps.setString(1,n);
ps.setString(2,p);
ps.setString(3,e);
ps.setString(4,p);

int i=ps.executeUpdate();
if(i>0)
out.print("You are successfully registered...");

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

out.close();
}

web.xml file
This is the configuration file, providing information about the servlet.

<web-app>

<servlet>
<servlet-name>Register</servlet-name>
<servlet-class>Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/servlet/Register</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>register.html</welcome-file>
</welcome-file-list>
</web-app>

Output:

Authenticating the user when he submits the login form using the username and password.
Experiment No.: 11
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.
we will see how to develop the Registration and Login Form in JSP. To develop a registration form we will
need to connect our JSP application with the database. Here we are using the MySQL database. First, we will
create a database name students. The SQL statement will be: Create database students;
Now, create the users table inside the students database as follows:
CREATE TABLE users (
fname varchar(45),
lname varchar(45),
email varchar(100),
userid varchar(45),
password varchar(45)
);
In this example, we will create four pages:
1. Index.html
2. Login.jsp
3. Register.html
4. registrationProcess.jsp

index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="login.jsp" method="post">
User name :<input type="text" name="usr" /><br><br> password :<input
type="password" name="password" /><br> <br><input type="submit" />
</form>
<p>
New user. <a href="register.html">Login Here</a>
</body>
</html>
login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@page import="java.sql.*,java.util.*"%>
<%
String userid = request.getParameter("userid");
session.putValue("userid", userid);
String password = request.getParameter("password");
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/students", "root",
"root");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from users where userid='" + userid + "' and password='" + password
+ "'");
try {
rs.next();
if (rs.getString("password").equals(password) && rs.getString("userid").equals(userid)) {
out.println("<h2>Welcome " + fname "</h2>");
} else {
out.println("Invalid password or username.");
}
} catch (Exception e) {
e.printStackTrace();
}
%>

register.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="registrationProcess.jsp" method="post">
First name :<input type="text" name="fname" /> <br><br>Last name :<input
type="text" name="lname" /> <br><br>Email ID :<input type="text"
name="email" /><br><br> User name :<input type="text" name="userid" /><br><br>
password :<input type="password" name="password" /> <br><br><input
type="submit" />
</form>
</body>
</html>

registrationProcess.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@page import="java.sql.*,java.util.*"%>
<%
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
String email = request.getParameter("email");
String userid = request.getParameter("userid");
String password = request.getParameter("password");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/students", "root", "root");
Statement st = conn.createStatement();
int i = st.executeUpdate("insert into users(fname,lname,email,userid,password)values('" + fname + "','" +
lname
+ "','" + email + "','" + userid + "','" + password + "')");
out.println("Thank you for register ! Please <a href='index.html'>Login</a> to continue.");
} catch (Exception e) {
System.out.print(e);
e.printStackTrace();
}
%>
Output
Experiment No.: 12

Design and implement a simple shopping cart example with session tracking API.
Session tracking methods:
1. User authorization
2. Hidden fields
3. URL rewriting
4. Cookies
5. Session tracking API
The first four methods are traditionally used for session tracking in all the server-side technologies. The session
tracking API method is provided by the underlying technology (java servlet or PHP or likewise). Session tracking
API is built on top of the first four methods.
1. User Authorization
Users can be authorized to use the web application in different ways. Basic concept is that the user will provide
username and password to login to the application. Based on that the user can be identified and the session can be
maintained.
2. Hidden Fields
<INPUT TYPE=”hidden” NAME=”technology” VALUE=”servlet”>
Hidden fields like the above can be inserted in the webpages and information can be sent to the server for session
tracking. These fields are not visible directly to the user, but can be viewed using view source option from the
browsers. This type doesn’t need any special configuration from the browser of server and by default available to
use for session tracking. This cannot be used for session tracking when the conversation included static resources
lik html pages.
3. URL Rewriting
Original URL: http://server:port/servlet/ServletName
Rewritten URL: http://server:port/servlet/ServletName?sessionid=7456
When a request is made, additional parameter is appended with the url. In general added additional parameter will
be sessionid or sometimes the userid. It will suffice to track the session. This type of session tracking doesn’t need
any special support from the browser. Disadvantage is, implementing this type of session tracking is tedious. We
need to keep track of the parameter as a chain link until the conversation completes and also should make sure
that, the parameter doesn’t clash with other application parameters.
4. Cookies
Cookies are the mostly used technology for session tracking. Cookie is a key value pair of information, sent by
the server to the browser. This should be saved by the browser in its space in the client computer. Whenever the
browser sends a request to that server it sends the cookie along with it. Then the server can identify the client
using the cookie.
In java, following is the source code snippet to create a cookie:
Cookie cookie = new Cookie(“userID”, “7456”);
res.addCookie(cookie);
Session tracking is easy to implement and maintain using the cookies. Disadvantage is that, the users can opt to
disable cookies using their browser preferences. In such case, the browser will not save the cookie at client
computer and session tracking fails.
5. Session tracking API
Session tracking API is built on top of the first four methods. This is inorder to help the developer to minimize the
overhead of session tracking. This type of session tracking is provided by the underlying technology. Lets take the
java servlet example. Then, the servlet container manages the session tracking task and the user need not do it
explicitly using the java servlets. This is the best of all methods, because all the management and errors related to
session tracking will be taken care of by the container itself.
Every client of the server will be mapped with a javax.servlet.http.HttpSession object. Java servlets can use the
session object to store and retrieve java objects across the session. Session tracking is at the best when it is
implemented using session tracking api.
The following will be approximate directory structure of the ShoppingCart project.
ShoppingCart
- ModelList.jsp
- ShoppingCart.jsp
WEB-INF
src
- in.techfreaks.shoppingcart.beans.CartBean.java
- in.techfreaks.shoppingcart.beans.CartItemBean.java
- in.techfreaks.shoppingcart.servlet.CartController.java
classes
lib
- jstl.jar
-standard.jar
CartItemBean:
package in.techfreaks.shoppingcart.beans;

public class CartItemBean {


private String strPartNumber;
private String strModelDescription;
private double dblUnitCost;
private int iQuantity;
private double dblTotalCost;

public String getPartNumber() {


return strPartNumber;
}
public void setPartNumber(String strPartNumber) {
this.strPartNumber = strPartNumber;
}
public String getModelDescription() {
return strModelDescription;
}
public void setModelDescription(String strModelDescription) {
this.strModelDescription = strModelDescription;
}
public double getUnitCost() {
return dblUnitCost;
}
public void setUnitCost(double dblUnitCost) {
this.dblUnitCost = dblUnitCost;
}
public int getQuantity() {
return iQuantity;
}
public void setQuantity(int quantity) {
iQuantity = quantity;
}
public double getTotalCost() {
return dblTotalCost;
}
public void setTotalCost(double dblTotalCost) {
this.dblTotalCost = dblTotalCost;
}
}
CartBean:
package in.techfreaks.shoppingcart.beans;

import java.util.ArrayList;

public class CartBean {


private ArrayList alCartItems = new ArrayList();
private double dblOrderTotal ;

public int getLineItemCount() {


return alCartItems.size();
}

public void deleteCartItem(String strItemIndex) {


int iItemIndex = 0;
try {
iItemIndex = Integer.parseInt(strItemIndex);
alCartItems.remove(iItemIndex - 1);
calculateOrderTotal();
} catch(NumberFormatException nfe) {
System.out.println("Error while deleting cart item: "+nfe.getMessage());
nfe.printStackTrace();
}
}

public void updateCartItem(String strItemIndex, String strQuantity) {


double dblTotalCost = 0.0;
double dblUnitCost = 0.0;
int iQuantity = 0;
int iItemIndex = 0;
CartItemBean cartItem = null;
try {
iItemIndex = Integer.parseInt(strItemIndex);
iQuantity = Integer.parseInt(strQuantity);
if(iQuantity>0) {
cartItem = (CartItemBean)alCartItems.get(iItemIndex-1);
dblUnitCost = cartItem.getUnitCost();
dblTotalCost = dblUnitCost*iQuantity;
cartItem.setQuantity(iQuantity);
cartItem.setTotalCost(dblTotalCost);
calculateOrderTotal();
}
} catch (NumberFormatException nfe) {
System.out.println("Error while updating cart: "+nfe.getMessage());
nfe.printStackTrace();
}

public void addCartItem(String strModelNo, String strDescription,


String strUnitCost, String strQuantity) {
double dblTotalCost = 0.0;
double dblUnitCost = 0.0;
int iQuantity = 0;
CartItemBean cartItem = new CartItemBean();
try {
dblUnitCost = Double.parseDouble(strUnitCost);
iQuantity = Integer.parseInt(strQuantity);
if(iQuantity>0) {
dblTotalCost = dblUnitCost*iQuantity;
cartItem.setPartNumber(strModelNo);
cartItem.setModelDescription(strDescription);
cartItem.setUnitCost(dblUnitCost);
cartItem.setQuantity(iQuantity);
cartItem.setTotalCost(dblTotalCost);
alCartItems.add(cartItem);
calculateOrderTotal();
}

} catch (NumberFormatException nfe) {


System.out.println("Error while parsing from String to primitive types: "+nfe.getMessage());
nfe.printStackTrace();
}
}

public void addCartItem(CartItemBean cartItem) {


alCartItems.add(cartItem);
}

public CartItemBean getCartItem(int iItemIndex) {


CartItemBean cartItem = null;
if(alCartItems.size()>iItemIndex) {
cartItem = (CartItemBean) alCartItems.get(iItemIndex);
}
return cartItem;
}

public ArrayList getCartItems() {


return alCartItems;
}
public void setCartItems(ArrayList alCartItems) {
this.alCartItems = alCartItems;
}
public double getOrderTotal() {
return dblOrderTotal;
}
public void setOrderTotal(double dblOrderTotal) {
this.dblOrderTotal = dblOrderTotal;
}

protected void calculateOrderTotal() {


double dblTotal = 0;
for(int counter=0;counter<alCartItems.size();counter++) {
CartItemBean cartItem = (CartItemBean) alCartItems.get(counter);
dblTotal+=cartItem.getTotalCost();

}
setOrderTotal(dblTotal);
}

CartController:
package in.techfreaks.shoppingcart.servlet;

import in.techfreaks.shoppingcart.beans.CartBean;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CartController extends HttpServlet {

//public static final String addToCart

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

String strAction = request.getParameter("action");

if(strAction!=null && !strAction.equals("")) {


if(strAction.equals("add")) {
addToCart(request);
} else if (strAction.equals("Update")) {
updateCart(request);
} else if (strAction.equals("Delete")) {
deleteCart(request);
}
}
response.sendRedirect("../ShoppingCart.jsp");
}

protected void deleteCart(HttpServletRequest request) {


HttpSession session = request.getSession();
String strItemIndex = request.getParameter("itemIndex");
CartBean cartBean = null;

Object objCartBean = session.getAttribute("cart");


if(objCartBean!=null) {
cartBean = (CartBean) objCartBean ;
} else {
cartBean = new CartBean();
}
cartBean.deleteCartItem(strItemIndex);
}

protected void updateCart(HttpServletRequest request) {


HttpSession session = request.getSession();
String strQuantity = request.getParameter("quantity");
String strItemIndex = request.getParameter("itemIndex");

CartBean cartBean = null;

Object objCartBean = session.getAttribute("cart");


if(objCartBean!=null) {
cartBean = (CartBean) objCartBean ;
} else {
cartBean = new CartBean();
}
cartBean.updateCartItem(strItemIndex, strQuantity);
}

protected void addToCart(HttpServletRequest request) {


HttpSession session = request.getSession();
String strModelNo = request.getParameter("modelNo");
String strDescription = request.getParameter("description");
String strPrice = request.getParameter("price");
String strQuantity = request.getParameter("quantity");

CartBean cartBean = null;

Object objCartBean = session.getAttribute("cart");

if(objCartBean!=null) {
cartBean = (CartBean) objCartBean ;
} else {
cartBean = new CartBean();
session.setAttribute("cart", cartBean);
}
cartBean.addCartItem(strModelNo, strDescription, strPrice, strQuantity);
}

ModelList.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>www.tech-freaks.in - Model List</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<p><font size="3" face="Verdana, Arial, Helvetica, sans-serif"><strong>Model List
</strong></font></p>
<a href="/ShoppingCart.jsp" mce_href="ShoppingCart.jsp">View Cart</a>
<p/>
<table width="75%" border="1">
<tr>
<td><form name="modelDetail1" method="POST" action="servlet/CartController">
<font size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong>Model:</strong>
TF-Model1</font><input type="hidden" name="modelNo" value="TF-MODEL1">
<p><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong>Description:</strong>
Tech-Freaks imaginary model 1. </font><input type="hidden" name="description" value="Tech-Freaks
imaginary model 1."></p>
<p><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong>Quantity:<input type="text"
size="2" value="1" name="quantity"></strong></font></p>
<p><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong>Price:</strong>
$10.00</font><input type="hidden" name="price" value="10"></p><input type="hidden" name="action"
value="add"><input type="submit" name="addToCart" value="Add To Cart">
</form></td>
<td><form name="modelDetail2" method="POST" action="servlet/CartController"><font size="2"
face="Verdana, Arial, Helvetica, sans-serif"><strong>Model</strong>:
TF-Model2 </font><input type="hidden" name="modelNo" value="TF-MODEL2">
<font face="Verdana, Arial, Helvetica, sans-serif">
<p><font size="2"><strong>Description</strong>: Tech-Freaks imaginary model
2. </font><input type="hidden" name="description" value="Tech-Freaks imaginary model 2."></p>
<p><font size="2"><strong>Quantity</strong>: <input type="text" size="2" value="1"
name="quantity"></font></p>
<p><font size="2"><strong>Price</strong>: $20.00<input type="hidden" name="price"
value="20"></font></p>
<input type="hidden" name="action" value="add">
<input type="submit" name="addToCart" value="Add To Cart">
</font></form></td>
</tr>
<tr>
<td><form name="modelDetail3" method="POST" action="servlet/CartController"><p><font size="2"
face="Verdana, Arial, Helvetica, sans-serif"><strong>Model:</strong>
TF-Model3</font><input type="hidden" name="modelNo" value="TF-MODEL3"></p>
<p><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong>Description:</strong>
Tech-Freaks imaginary model 3. </font><input type="hidden" name="description" value="Tech-Freaks
imaginary model 3."></p>
<p><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong>Quantity:</strong></font> <input
type="text" size="2" value="1" name="quantity"></p>
<p><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong>Price:
$30.00</strong></font><input type="hidden" name="price" value="30"></p> <input type="hidden"
name="action" value="add">
<input type="submit" name="addToCart" value="Add To Cart">
</form></td>
<td><form name="modelDetail4" method="POST" action="servlet/CartController"><p><font size="2"
face="Verdana, Arial, Helvetica, sans-serif"><strong>Model</strong>:
TF-Model4</font><input type="hidden" name="modelNo" value="TF-MODEL4"></p>
<p><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong>Description</strong>:
Tech-Freaks imaginary model 4. </font><input type="hidden" name="description" value="Tech-Freaks
imaginary model 4."></p>
<p><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong>Quantity</strong>:</font> <input
type="text" size="2" value="1" name="quantity"></p>
<p><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><strong>Price</strong>:
$40.00</font><input type="hidden" name="price" value="40"></p>
<input type="hidden" name="action" value="add"><input type="submit" name="addToCart" value="Add To
Cart"></form></td>
</tr>
</table>
<p> </p>
</body>
</html>

ShoppingCart.jsp
For iterating the elements in the cart session, we are using simple JSTL tags with EL.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>www.tech-freaks.in - Shopping Cart</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<p><font face="Verdana, Arial, Helvetica, sans-serif"><strong>Shopping Cart</strong></font></p>
<p><a href="/ModelList.jsp" mce_href="ModelList.jsp">Model List</a> </p>
<table width="75%" border="1">
<tr bgcolor="#CCCCCC">
<td><strong><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Model
Description</font></strong></td>
<td><strong><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Quantity</font></strong></td>
<td><strong><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Unit
Price</font></strong></td>
<td><strong><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Total</font></strong></td>
</tr>
<jsp:useBean id="cart" scope="session" class="in.techfreaks.shoppingcart.beans.CartBean" />
<c:if test="${cart.lineItemCount==0}">
<tr>
<td colspan="4"><font size="2" face="Verdana, Arial, Helvetica, sans-serif">- Cart is currently empty -<br/>
</tr>
</c:if>
<c:forEach var="cartItem" items="${cart.cartItems}" varStatus="counter">
<form name="item" method="POST" action="servlet/CartController">
<tr>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><b><c:out
value="${cartItem.partNumber}"/></b><br/>
<c:out value="${cartItem.modelDescription}"/></font></td>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif"><input type='hidden' name='itemIndex'
value='<c:out value="${counter.count}"/>'><input type='text' name="quantity" value='<c:out
value="${cartItem.quantity}"/>' size='2'> <input type="submit" name="action" value="Update">
<br/> <input type="submit" name="action" value="Delete"></font></td>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">$<c:out
value="${cartItem.unitCost}"/></font></td>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">$<c:out
value="${cartItem.totalCost}"/></font></td>
</tr>
</form>
</c:forEach>
<tr>
<td colspan="2"> </td>
<td> </td>
<td><font size="2" face="Verdana, Arial, Helvetica, sans-serif">Subtotal: $<c:out
value="${cart.orderTotal}"/></font></td>
</tr>
</table>
</body>
</html>
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">

<display-name>Shopping Cart</display-name>
<description>
Simple Shopping Cart
</description>

<servlet>
<servlet-name>CartController</servlet-name>
<servlet-class>in.techfreaks.shoppingcart.servlet.CartController</servlet-class>
</servlet>

<!-- Define the Manager Servlet Mapping -->


<servlet-mapping>
<servlet-name>CartController</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>

</web-app>

You might also like