0% found this document useful (0 votes)
3 views36 pages

PSIT Internet of Things Department Overview

The document contains multiple HTML experiments showcasing different web development concepts, including a home page for Pranveer Singh Institute of Technology, a student details entry form, a tech tutorials blog, a registration form with validation, and XML with DTD and XSL for displaying student information. Additionally, it includes a Node.js script for various functionalities like text conversion, factorial calculation, and password generation, as well as a MongoDB aggregation example. Each experiment serves to illustrate specific programming and web design techniques.

Uploaded by

manjarishukla492
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)
3 views36 pages

PSIT Internet of Things Department Overview

The document contains multiple HTML experiments showcasing different web development concepts, including a home page for Pranveer Singh Institute of Technology, a student details entry form, a tech tutorials blog, a registration form with validation, and XML with DTD and XSL for displaying student information. Additionally, it includes a Node.js script for various functionalities like text conversion, factorial calculation, and password generation, as well as a MongoDB aggregation example. Each experiment serves to illustrate specific programming and web design techniques.

Uploaded by

manjarishukla492
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

EXPERIMENT -1

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Pranveer Singh Institute of Technology (PSIT) - Home</title>
</head>
<body style="font-family: Arial, sans-serif;">

<!-- Header -->


<header style="background-color:#003366; color:white; padding:15px;">
<h1>Pranveer Singh Institute of Technology (PSIT)</h1>
<p>Center of Excellence in Engineering and Technology</p> </header>

<!-- Navigation -->


<nav style="background-color:#eee; padding:10px;">
<a href="#home">Home</a> |
<a href="#about">About</a> |
<a href="#departments">Departments</a> |
<a href="#contact">Contact</a>
</nav>

<!-- Main Content -->


<section id="home" style="padding:15px;">
<h2>Welcome to Pranveer Singh Institute of Technology (PSIT)</h2>
<p>PSIT offers quality education with a focus on innovation, research, and industryoriented
learning.</p> </section>

<section id="about" style="padding:15px;">


<h2>About Pranveer Singh Institute of Technology (PSIT)</h2> <p>PSIT is a
premier institute providing technical education with modern infrastructure, experienced
faculty, and strong placement records.</p> </section>

<!-- IoT Department Information -->


<section id="departments" style="padding:15px;">
<h2>Department of Internet of Things (IoT)</h2>

<p>
The IoT Department at PSIT focuses on connecting devices, sensors, and systems to create
smart solutions
for real-world problems in areas like smart cities, healthcare, agriculture, and
industry. </p>

<ul>
<li>Programs Offered: [Link] in IoT, electives and minor specializations in IoT.</li>
<li>Key Subjects: Sensor Networks, Embedded Systems, Cloud Computing, Data
Analytics for IoT.</li>
<li>Facilities: Dedicated IoT lab with microcontrollers, sensors, and development kits.</li>
<li>Activities: Workshops, hackathons, and industry collaborations on IoT
projects.</li> </ul> </section>

<!-- Contact Section -->


<section id="contact" style="padding:15px;">
<h2>Contact Us</h2>
<p>Pranveer Singh Institute of Technology (PSIT), Kanpur, Uttar Pradesh</p>
<p>Email: info@[Link] | Phone: +91-XXXXX-XXXXX</p> </section>

<!-- Footer -->


<footer style="background-color:#003366; color:white; text-align:center; padding:10px; margin-
top:20px;">
<p>&copy; 2025 Pranveer Singh Institute of Technology (PSIT). All rights reserved.</p>
</footer>

</body>
</html>
EXPERIMENT- 2

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Student Details Entry Form</title>
</head>
<body style="font-family: Arial, sans-serif;">

<h2>Student Details Entry Form</h2>


<form action="/submit" method="post" style="max-width:400px;">
<label for="name">Full Name:</label><br>
<input type="text" id="name" name="name" required style="width:100%;"><br><br>

<label for="roll">Roll Number:</label><br>


<input type="text" id="roll" name="roll" required style="width:100%;"><br><br>

<label for="department">Department:</label><br>
<select id="department" name="department" required style="width:100%;">
<option value="">--Select Department--</option>
<option value="CSE">Computer Science & Engineering</option>
<option value="ECE">Electronics & Communication Engineering</option>
<option value="ME">Mechanical Engineering</option>
<option value="IoT">Internet of Things</option> </select><br><br>

<label for="email">Email:</label><br>
<input type="email" id="email" name="email" required style="width:100%;"><br><br>

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


<input type="tel" id="phone" name="phone" pattern="[0-9]{10}" placeholder="10-digit
number" required style="width:100%;"><br><br>

<label for="address">Address:</label><br>
<textarea id="address" name="address" rows="3" style="width:100%;"></
textarea><br><br>

<input type="submit" value="Submit" style="background-color:#003366; color:white;


padding:8px 16px; border:none;"> </form>

</body>
</html>
EXPERIMENT-3

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Tech Tutorials Blog</title>
<style> /* Base
Styles */ body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana,
sans-serif; margin: 0; line-height: 1.6; backgroundcolor:
#f4f4f4; color: #333;
}

header { background-color:
#00509e; color: white;
padding: 20px 10px; text-align:
center;
}

nav { background:
#002d62;
display: flex; justifycontent:
center;
flex-wrap: wrap;
}

nav a { color: white;


padding: 14px 20px;
textdecoration: none;
font-weight: bold;
transition: background 0.3s ease;
}

nav a:hover { background:


#004080;
}

/* Main container */
.container { display:
flex; max-
width: 1100px;
margin: 20px auto;
gap: 20px;
padding: 0 15px;
}
/* Main content */
.maincontent { flex: 3;
background: white;
padding: 20px;
box-shadow: 0 0 8px rgba(0,0,0,0.1);
}
.main-content h2 { margin-top:
0;
}

/* Sidebar */ .sidebar { flex: 1;


background: white; padding:
20px; box-shadow: 0 0 8px
rgba(0,0,0,0.1);
}

.sidebar h3 { margin-top: 0; border-bottom: 2px


solid #00509e; padding-bottom: 8px;
}

.sidebar ul { list-
styletype: none;
padding-left: 0;
}

.sidebar ul li { margin:
10px 0;
}

.sidebar ul li a { color:
#002d62; text-
decoration: none;
}

.sidebar ul li a:hover { text-decoration:


underline;
}

/* Footer */ footer {
backgroundcolor:
#00509e; color: white;
text-align: center;
padding: 15px 10px;
margin-top: 20px;
}

/* Responsive adjustments */ @media


(max-width:
768px) { .container { flex-direction:
column;
} nav
{
justify-content: space-around;
}
}
</style>
</head>
<body>

<header>
<h1>Tech Tutorials Blog</h1> <p>Learn coding, web development, and technology tips</p>
</header>

<nav>
<a href="#home">Home</a>
<a href="#tutorials">Tutorials</a>
<a href="#reviews">Reviews</a>
<a href="#about">About</a>
<a href="#contact">Contact</a>
</nav>

<div class="container">
<div class="main-content">
<article>
<h2>Getting Started with HTML and CSS</h2>
<p>HTML and CSS are the building blocks of web development. In this tutorial, you'll learn
how to create your first responsive website...</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur non libero at lorem
consequat interdum. Nullam posuere scelerisque elit, a lacinia est.</p> </article>

<article>
<h2>JavaScript Basics for Beginners</h2>
<p>JavaScript is a powerful language to make your websites interactive. Understand basic
syntax, variables, and functions in this guide...</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras fermentum quam et diam
imperdiet, nec cursus massa feugiat.</p>
</article>
</div>
<aside class="sidebar">
<h3>Popular Tutorials</h3>
<ul>
<li><a href="#">Responsive Design with CSS Grid</a></li>
<li><a href="#">Introduction to ReactJS</a></li>
<li><a href="#">Backend API with [Link]</a></li>
<li><a href="#">Deploy your Website</a></li> </ul>
<h3>Subscribe</h3>
<form>
<input type="email" placeholder="Your email" style="width: 100%; padding: 8px;
marginbottom: 8px;" required>
<input type="submit" value="Subscribe" style="width: 100%; background:#00509e;
color:white; border:none; padding:10px;">
</form>
</aside>
</div>

<footer>
<p>&copy; 2025 Tech Tutorials Blog. All rights reserved.</p> </footer>

</body>
</html>
EXPERIMENT-4

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Form Validation Example</title>
<script> function validateForm() { const name =
[Link]('name').[Link](); const email =
[Link]('email').[Link](); const phone =
[Link]('phone').[Link](); const password =
[Link]('password').value;

// Name validation (nonempty)


if (name === '') {
alert('Please enter your name.');
return false;
}

// Email validation (basic pattern)


const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-
zAZ]{2,6}$/; if (![Link](email)) { alert('Please enter
a valid email address.');
return false;
}

// Phone number validation (digits only, length


10) const phonePattern = /^\d{10}$/; if
(![Link](phone)) { alert('Please enter a
10-digit phone number.');
return false;
}

// Password validation (min length 6) if ([Link] <


6) { alert('Password should be at least 6 characters long.');
return false;
}

// If all validations pass alert('Form


submitted successfully!');
return true;
}
</script>
</head>
<body style="font-family: Arial, sans-serif;">
<h2>Registration Form with Validation</h2>

<form onsubmit="return validateForm();">


<label for="name">Name:</label><br />
<input type="text" id="name" name="name" /><br /><br />

<label for="email">Email:</label><br />


<input type="text" id="email" name="email" /><br /><br />

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


<input type="text" id="phone" name="phone" placeholder="10 digits only" /><br /><br />
<label for="password">Password:</label><br />
<input type="password" id="password" name="password" /><br /><br />

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


</form>

</body>
</html>
EXPERIMENT - 5

#XML Document ([Link])


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE students SYSTEM "[Link]">
<?xml-stylesheet type="text/xsl" href="[Link]"?>
<students>
<student>
<id>101</id>
<name>Rajesh Kumar</name>
<department>Computer Science</department>
</student>
<student>
<id>102</id>
<name>Anita Shah</name>
<department>Electronics</department>
</student>
</students>

#DTD File ([Link])


<!ELEMENT students (student+)>
<!ELEMENT student (id, name, department)>
<!ELEMENT id (#PCDATA)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT department (#PCDATA)>

#XSL Stylesheet ([Link])


<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet
version="1.0"
xmlns:xsl="[Link]

<xsl:template match="/">
<html>
<head>
<title>Students List</title>
<style> table { border-collapse: collapse; width: 60%; }
th, td { border: 1px solid black; padding: 8px; text-align: left;}
th { background-color: #4CAF50; color: white;}
</style>
</head>
<body>
<h2>Students Information</h2>
<table>
<tr>
<th>Student ID</th>
<th>Name</th>
<th>Department</th>
</tr>
<xsl:for-each select="students/student">
<tr>
<td><xsl:value-of select="id"/></td>
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="department"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Experiment - 6

#!/usr/bin/env node const readline =

require('readline');

const rl = [Link]({
input: [Link],
output: [Link]
});

// Function to convert text to uppercase function


toUppercase(text) {
return [Link]();
}

// Function to calculate factorial function


factorial(num) {
if (num < 0) return 'Number must be non-
negative'; if (num === 0) return 1; let result =
1; for (let i = 1; i <= num;
i++) {
result *= i;
}
return result;
}

// Function to generate a random password of given length function generatePassword(length = 8)


{ const chars =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!
@#$%^&*()_+[]{}|;:,.<>?'; let
password = '';
for (let i = 0; i < length; i++) { password +=
[Link]([Link]([Link]() * [Link]));
}
return password;
}

[Link]('Choose an option:');
[Link]('1. Convert text to uppercase');
[Link]('2. Calculate factorial');
[Link]('3. Generate random password');

[Link]('Enter option number (1/2/3): ', (option) => { switch([Link]()) {


case '1':
[Link]('Enter text to convert: ', (text) => {
[Link]('Uppercase:', toUppercase(text));
[Link]();
});
break;
case '2':
[Link]('Enter a non-negative integer: ', (num)
=> { const number = parseInt(num); if
(isNaN(number) || number < 0) { [Link]('Please enter a
valid non-negative integer.');
} else { [Link](`Factorial of ${number} is`,
factorial(number));
}
[Link]();
}); break;
case '3':
[Link]('Enter password length (default 8): ',
(len) => { const length = parseInt(len); if
(isNaN(length) || length <= 0) {
[Link]('Password:', generatePassword());
} else {
[Link]('Password:', generatePassword(length));
} [Link]();
});
break;
default: [Link]('Invalid
option.');
[Link]();
}
});
Experiment- 7

const { MongoClient } = require("mongodb");

async function runAggregation() {


const uri =
"mongodb://localhost:27017"; const client =
new MongoClient(uri); try {
await [Link](); const database =
[Link]("yourDatabaseName");
const collection = [Link]("users");

const pipeline = [
{
$group: {
_id: "$city", averageAge:
{ $avg: "$age" }
}
},
{ $sort: { averageAge: -1 } }
];

const results = await [Link](pipeline).toArray();

if ([Link] === 0) { [Link]("No


data found in aggregation.");
} else { [Link]("Aggregation
results:");
[Link](result => {
[Link](`City: ${result._id}, Average Age: ${[Link](2)}`);
});
}
} catch (error) { [Link]("Aggregation
error:", error);
} finally { await
[Link]();
}
}

runAggregation();
Experiment - 8

[Link]
import
[Link]; a
public class MainTest { public
static void main(String[] args) {
Employee emp = new Employee();
[Link](101);
[Link]("Aishwary Shreykar Singh");
[Link](55000); [Link]("Software
Engineer"); [Link]("IT");

[Link](emp);
}
}

[Link] package
[Link];

import [Link];

public class Employee implements Serializable


{ private int empId; private String name;
private double salary; private String
designation;
private String department;

public Employee() {} public Employee(int empId, String name, double salary, String
designation, String
department) { [Link] = empId; [Link] = name; [Link] = salary;
[Link] = designation;
[Link] = department;
}

public int getEmpId() {


return empId;
}

public void setEmpId(int empId) {


[Link] = empId;
}

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}

public double getSalary() {


return salary;
}

public void setSalary(double salary) {


[Link] = salary;
}

public String getDesignation() {


return designation;
}

public void setDesignation(String designation) {


[Link] = designation;
}

public String getDepartment() {


return department;
}
public void setDepartment(String department) { [Link]
= department;
}
@Override public
String toString() {
return "Employee [EmpID=" + empId + ", Name=" + name + ", Salary=" + salary +
", Designation=" + designation + ", Department=" + department
+ "]"; }}
Experiment 9

[Link]:
<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>

[Link]
<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>

[Link]:
import [Link].* ;
import [Link].*;
import [Link].*;
public class Addcook extends HttpServlet
{
String user,pas;
public void service(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
[Link]("text/html");
PrintWriter out=[Link]();
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");
[Link](c1);
[Link](p1);
[Link](c2);
[Link](p2);
[Link](c3);
[Link](p3);
[Link](c4);
[Link](p4);
[Link]("COOKIE ADDED");
}
}
[Link]:
import [Link].* ; import [Link].*; import [Link].*;
public class Clogin extends HttpServlet
{
String user,pas;
public void service(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
[Link]("text/html"); PrintWriter out=[Link](); user=[Link]("usr");
pas=[Link]("pwd"); Cookie[] c=[Link](); for(int i=0;i<[Link];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(([Link](c[i].getValue()) && [Link](c[i+1].getValue())) )
{
//RequestDispatcher rd=[Link]("/[Link]"); [Link](req,res);
}
else
{
[Link]("YOU ARE NOT AUTHORISED USER ");
//[Link]("/cookdemo/[Link]");
}
}
}
}
}

[Link]:
<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>
Experiment 10

CREATE DATABASE user_registration_db;

USE user_registration_db;

CREATE TABLE users (


id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
password VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
phone_number VARCHAR(15) NOT NULL
);

Step 2: Create the Registration JSP Page ([Link])


This page will allow users to register by submitting their details.

<!DOCTYPE html>
<html>
<head>
<title>Registration Page</title>
</head>
<body>
<h2>Register Here</h2>
<form action="RegisterServlet" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" 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" required><br><br>

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


<input type="text" id="phone_number" name="phone_number" required><br><br>

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


</form>
</body>
</html>

Step 3: Create the Servlet ([Link])


This servlet handles form submission, connects to the database, inserts the user's data, and redirects
to a success page
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Collect form data


String name = [Link]("name");
String password = [Link]("password");
String email = [Link]("email");
String phone_number = [Link]("phone_number");

// Database connection details


String jdbcUrl = "jdbc:mysql://localhost:3306/user_registration_db";
String jdbcUsername = "root"; // Change as per your DB configuration
String jdbcPassword = ""; // Change as per your DB configuration

Connection conn = null;


PreparedStatement ps = null;

try {
// Step 1: Register JDBC driver
[Link]("[Link]");

// Step 2: Open a connection


conn = [Link](jdbcUrl, jdbcUsername, jdbcPassword);

// Step 3: Prepare a SQL query


String sql = "INSERT INTO users (name, password, email, phone_number) VALUES (?, ?,
?, ?)";
ps = [Link](sql);
[Link](1, name);
[Link](2, password);
[Link](3, email);
[Link](4, phone_number);

// Step 4: Execute the query


int row = [Link]();

// Step 5: Process the response


if (row > 0) {
[Link]("[Link]");
} else {
[Link]().print("Error inserting data.");
}
} catch (SQLException | ClassNotFoundException e) {
[Link]();
} finally {
try {
if (ps != null) [Link]();
if (conn != null) [Link]();
} catch (SQLException e) {
[Link]();
}
}
}
}

<!DOCTYPE html>
<html>
<head>
<title>Registration Success</title>
</head>
<body>
<h2>Registration Successful!</h2>
<a href="ViewUsersServlet">View All Registered Users</a>
</body>
</html>

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@WebServlet("/ViewUsersServlet")
public class ViewUsersServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();

// Database connection details


String jdbcUrl = "jdbc:mysql://localhost:3306/user_registration_db";
String jdbcUsername = "root"; // Change as per your DB configuration
String jdbcPassword = ""; // Change as per your DB configuration

Connection conn = null;


Statement stmt = null;
ResultSet rs = null;

try {
// Step 1: Register JDBC driver
[Link]("[Link]");

// Step 2: Open a connection


conn = [Link](jdbcUrl, jdbcUsername, jdbcPassword);

// Step 3: Execute a query


stmt = [Link]();
String sql = "SELECT * FROM users";
rs = [Link](sql);

// Step 4: Process the result set


[Link]("<h2>Registered Users</h2>");
[Link]("<table border='1'><tr><th>ID</th><th>Name</th><th>Email</th><th>Phone
Number</th></tr>");

while ([Link]()) {
int id = [Link]("id");
String name = [Link]("name");
String email = [Link]("email");
String phone_number = [Link]("phone_number");

[Link]("<tr><td>" + id + "</td><td>" + name + "</td><td>" + email + "</td><td>"


+ phone_number + "</td></tr>");
}
[Link]("</table>");

} catch (Exception e) {
[Link]();
} finally {
try {
if (rs != null) [Link]();
if (stmt != null) [Link]();
if (conn != null) [Link]();
} catch (Exception e) {
[Link]();
}
}
}
}

Web Configuration ([Link])


If you're not using annotations for servlet mapping, configure the servlets in [Link].
<web-app xmlns="[Link] version="3.1">
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/RegisterServlet</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>ViewUsersServlet</servlet-name>
<servlet-class>ViewUsersServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ViewUsersServlet</servlet-name>
<url-pattern>/ViewUsersServlet</url-pattern>
</servlet-mapping>
</web-app>
Experiment 11

[Link]:
<!--[Link]-->
<html><body>
<center><h1>XYZ Company Ltd.</h1></center>
<table border="1" width="100%" height="100%">
<tr>
<td valign="top" align="center"><br/>
<form action="[Link]"><table>
<tr>
<td colspan="2" align="center"><b>Login Page</b></td>
</tr>
<tr>
<td colspan="2" align="center"><b>&nbsp;</td>
</tr>
<tr>
<td>User Name</td>
<td><input type="text" name="user"/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pwd"/></td>
</tr>
<tr>
<td>&nbsp;</td>

<td colspan="2" align="center"><input type="submit" value="LogIN"/></td>


<td>&nbsp;</td></tr><tr>

</tr>
</table>
</form>
</td>
</tr>
</table>
</body>
</html> [Link]:
<%@page import="[Link].*;"%>
<html>
<head>
<title>
This is simple data base example in JSP</title>
</title>
</head>
<body bgcolor="yellow">
<%!Stringuname,pwd;%>
<%
uname=[Link]("user"); pwd=[Link]("pwd"); try
{
[Link]("[Link]"); Connection
con=[Link]("jdbc:oracle:thin:@[Link]:1521
:CCLAB","scott","tiger"); Statement st=[Link]();
ResultSetrs=[Link]("select name,password from personal where name='"+uname+"' and
password='"+pwd+"'");
if([Link]())
{
[Link]("Authorized person");
}
else
{
[Link]("UnAuthorized person");
}
[Link]();}

catch(Exception e){[Link](""+e);}
%></body></html>
Experiment 12

Configure [Link]-
<project xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link] [Link]
v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>LearnJSPServletWithRealApps</groupId>
<artifactId>LearnJSPServletWithRealApps</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Learn JSP-Servlet with Real Apps</name>
<url>[Link]
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>[Link]-api</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>[Link]-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>LearnJSPServletWithRealApps</finalName>
</build>
</project>
Configure [Link]-
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"[Link] >

<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
Redirect Page
Create new JSP file named [Link] in src\main\webapp folder. This file will redirect to
ProductServlet as below:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<jsp:forward page="product"></jsp:forward>
Add Image Files
Create new folder named assets in src\main\webapp folder. In assets folder, create new folder
named images and copy images need use in project to images folder.
Create Entities
Create new package named [Link]. In this package, create new Java classes as below:
Product Entity
Create new Java class named [Link] as below:
[Link];

public class Product {

private String id;


private String name;
private double price;
private String photo;

public Product() {
}

public Product(String id, String name, String photo, double price) {


[Link] = id;
[Link] = name;
[Link] = price;
[Link] = photo;
}

public String getId() {


return id;
}
public void setId(String id) {
[Link] = id;
}

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}

public double getPrice() {


return price;
}

public void setPrice(double price) {


[Link] = price;
}

public String getPhoto() {


return photo;
}

public void setPhoto(String photo) {


[Link] = photo;
}

}
Item Entity
Create new Java class named [Link] as below:

[Link];

public class Item {

private Product product;


privateint quantity;

public Item() {
}

public Item(Product product, int quantity) {


[Link] = product;
[Link] = quantity;
}

public Product getProduct() {


return product;
}

public void setProduct(Product product) {


[Link] = product;
}

publicintgetQuantity() {
return quantity;
}

public void setQuantity(int quantity) {


[Link] = quantity;
}

}
Create Servlets
Create new package named [Link]. In this package, create new Servlets as below:

Product Servlet
In [Link] package, create new Servlet named ProductServlet as below:

[Link];

[Link];

[Link];
[Link];
[Link];
[Link];
[Link];

[Link];

@WebServlet("/product")
public class ProductServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

publicProductServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
ProductModelproductModel = new ProductModel();
[Link]("products", [Link]());
[Link]("product/[Link]").forward(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throwsServletException, IOException {
}

}
Cart Servlet
In [Link] package, create new Servlet named CartServlet as below:

[Link];

[Link];
[Link];
[Link];

[Link];
[Link];
[Link];
[Link];
[Link];
[Link];

[Link];
[Link];

@WebServlet("/cart")
public class CartServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

publicCartServlet() {
super();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throwsServletException, IOException {
String action = [Link]("action");
if (action == null) {
doGet_DisplayCart(request, response);
} else {
if ([Link]("buy")) {
doGet_Buy(request, response);
} else if ([Link]("remove")) {
doGet_Remove(request, response);
}
}
}

protected void doGet_DisplayCart(HttpServletRequest request, HttpServletResponse


response)
throwsServletException, IOException {
[Link]("cart/[Link]").forward(request, response);
}

protected void doGet_Remove(HttpServletRequest request, HttpServletResponse response)


throwsServletException, IOException {
HttpSession session = [Link]();
List<Item> cart = (List<Item>) [Link]("cart");
int index = isExisting([Link]("id"), cart);
[Link](index);
[Link]("cart", cart);
[Link]("cart");
}

protected void doGet_Buy(HttpServletRequest request, HttpServletResponse response)


throwsServletException, IOException {
ProductModelproductModel = new ProductModel();
HttpSession session = [Link]();
if ([Link]("cart") == null) {
List<Item> cart = new ArrayList<Item>();
[Link](new Item([Link]([Link]("id")), 1));
[Link]("cart", cart);
} else {
List<Item> cart = (List<Item>) [Link]("cart");
int index = isExisting([Link]("id"), cart);
if (index == -1) {
[Link](new Item([Link]([Link]("id")),
1));
} else {
int quantity = [Link](index).getQuantity() + 1;
[Link](index).setQuantity(quantity);
}
[Link]("cart", cart);
}
[Link]("cart");
}

privateintisExisting(String id, List<Item> cart) {


for (int i = 0; i <[Link](); i++) {
if ([Link](i).getProduct().getId().equalsIgnoreCase(id)) {
return i;
}
}
return -1;
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throwsServletException, IOException {
}

}
Create Product Pages
Create new folder named product in src\main\webapp folder. In this folder, create new JSP file
named [Link] as below:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%@ taglib prefix="c" uri="[Link]
<html>
<head>
<title>Product Page</title>
</head>
<body>

<table cellpadding="2" cellspacing="2" border="1">


<tr>
<th>Id</th>
<th>Name</th>
<th>Photo</th>
<th>Price</th>
<th>Buy</th>
</tr>
<c:forEachvar="product" items="${products }">
<tr>
<td>${[Link] }</td>
<td>${[Link] }</td>
<td>
<imgsrc="${[Link]
}/assets/images/${[Link] }" width="120">
</td>
<td>${[Link] }</td>
<td align="center">
<a href="${[Link]
}/cart?&action=buy&id=${[Link] }">Buy</a>
</td>
</tr>
</c:forEach>
</table>

</body>
</html>
Create Cart Pages
Create new folder named cart in src\main\webapp folder. In this folder, create new JSP file named
[Link] as below:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%@ taglib prefix="c" uri="[Link]
<html>
<head>
<title>Cart Page</title>
</head>
<body>

<table cellpadding="2" cellspacing="2" border="1">


<tr>
<th>Option</th>
<th>Id</th>
<th>Name</th>
<th>Photo</th>
<th>Price</th>
<th>Quantity</th>
<th>Sub Total</th>
</tr>
<c:setvar="total" value="0"></c:set>
<c:forEachvar="item" items="${[Link] }">
<c:setvar="total" value="${total + [Link] * [Link]
}"></c:set>
<tr>
<td align="center">
<a href="${[Link]
}/cart?action=remove&id=${[Link] }"
onclick="return confirm('Are you sure?')">Remove</a>
</td>
<td>${[Link] }</td>
<td>${[Link] }</td>
<td>
<imgsrc="${[Link]
}/assets/images/${[Link] }" width="120">
</td>
<td>${[Link] }</td>
<td>${[Link] }</td>
<td>${[Link] * [Link] }</td>
</tr>
</c:forEach>
<tr>
<td colspan="6" align="right">Total</td>
<td>${total }</td>
</tr>
</table>
<br>
<a href="${[Link] }/product">Continue Shopping</a>

</body>
</html>

You might also like