[go: up one dir, main page]

0% found this document useful (0 votes)
1K views56 pages

KCS-652-WT LAB Manual-2021-22

The document contains the lab manual for the Web Technologies lab at PSIT-Pranveer Singh Institute of Technology. It lists 10 experiments to be performed as part of the lab curriculum. The experiments cover topics like HTML, CSS, JavaScript, Java applets, TCP/IP sockets, JDBC, servlets, JSP, database connectivity and CRUD operations. It also lists 5 extra programs covering additional topics like billing calculation, color mixer, TCP/IP communication, batch transactions, and student marks sheet using servlets and databases. The document provides the objectives and instructions for the university programs to be implemented in the lab.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views56 pages

KCS-652-WT LAB Manual-2021-22

The document contains the lab manual for the Web Technologies lab at PSIT-Pranveer Singh Institute of Technology. It lists 10 experiments to be performed as part of the lab curriculum. The experiments cover topics like HTML, CSS, JavaScript, Java applets, TCP/IP sockets, JDBC, servlets, JSP, database connectivity and CRUD operations. It also lists 5 extra programs covering additional topics like billing calculation, color mixer, TCP/IP communication, batch transactions, and student marks sheet using servlets and databases. The document provides the objectives and instructions for the university programs to be implemented in the lab.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 56

PSIT-Pranveer Singh Institute of Technology

Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

WEB TECHNOLOGIES LAB MANUAL


LAB PLAN
List of Experiments as per AKTU

Lab No. Lab Experiment Corresponding


CO
1 Write HTML/Java scripts to display your CV in navigator, CO2
your Institute website, Department Website and Tutorial
website for specific subject.
2 Write an HTML program to design an entry form of student CO2
details
3 Write program using Java script for Web Page to display CO1
browsers information.
4 Write a Java applet/AWT to display the Application Program CO2
screen i.e. calculator and other.
5 Write a program using TCP/IP socket between client and CO1
server and perform two-way communication
6 Write a program to illustrate JDBC connectivity and perform CO2
CRUD operation on a table student/employee (at least 5
attributes)
7 Write a program to illustrate Batch Transaction with CO2
prepared statement.
8 Design and implement a simple servlet for an entry form of CO2
student details and send it to store at database server like
SQL, Oracle or MS Access.
9 Install a database (Mysql or Oracle). Create a table which CO2
should contain at least the following fields: name, password,
email-id, phone number Write a java program/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.
10 Write a JSP which insert the details of the 3 or 4 users who CO2
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

Extra Programs:

S. Correspondin
Objectives
No. g CO
1 A super class Detail has been defined to store the details of CO1
a customer. Define a subclass Bill to compute the monthly

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

telephone charge of the customer as per the chart given


below:
Number of Calls Rate
1 – 100 Only Rental charge
101 – 200 60 paisa per call + rental charge
201 – 300 80 paisa per call + rental charge
Above 300 1 rupee per call + rental charge
Write a Java applet to display the Application Program screen
2 i.e. Colour mixer pallet
CO1
Write a program using TCP/IP socket between client and
3 CO1
server and perform two-way communication.
Write a program to illustrate Batch Transaction with
4 CO2
prepared statement
To Develop a student Marks sheet by using Servlet and
5 CO2
HTML with database Oracle.

Content Beyond Syllabus:

Store 5 Students (name, branch, rollno, age) objects in list.


Perform any sorting technique so as to display list in
1 CO1
ascending order of rollno and display in descending order of
age.
Perform union (AUB), intersection and difference (A-B)
2 CO1
operations using set collection.
Create a Map that consists of Country-Capital pair to store
information about various countries along with their capital
3 CO1
name. Display the entries in sorted order of Country and
Capital.

Experiments objective/instructions
University Programs
Program 1: - Write HTML/Java scripts to display your CV in navigator, your
Institute website, Department Website and Tutorial website for specific
subject

Description: - Designing of CV and an institute website will contain all the required tags of
HTML and external CSS. This CV can be viewed in browser.

Program: -

<!DOCTYPE html>
<html>

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

<head>
<title>Resume Prac_1</title>
<link rel="stylesheet" type="text/css" href="prac.css">
</head>
<body>
<fieldset id="fieldset1">
<div class="h1_div_1"><h1>Abhishek Kumar Dwivedi</h1>

<strong>Citizenship:</strong> India |
<strong>D.O.B.</strong> 16/07/1997
<br>
<strong>Contact:</strong> 9087654320 |
<strong>Email</strong> eagleakku@gmail.com
</div>
<img src="anonymous.jpg">
</fieldset>

<fieldset>
<h4>Profile</h4>
<div id="divleft">
<em>Key Aspect</em>
</div>
<span>
I have leadership skills, technical skills. I am comfortable in
coding in multiple languages. Java and Python are my favourites.
</span>
</fieldset>
<fieldset>
<h4>Key Details</h4>
<table>
<tr class="trOrange">
<td><strong>Operating System</strong></td>
<td><strong>Language</strong></td>
<td><strong>Database</strong></td>
<td><strong>Web Technologies</strong></td>
</tr>
<tr>
<td>Windows XP/7/8/10</td>
<td>C/C++,Java,J2EE</td>
<td>MySQL,Oracle</td>
<td>HTML5,CSS3,JavaScript</td>
</tr>
<tr>
<td>RedHat,CentOS</td>
<td>PHP,Python</td>
<td>BigData</td>
<td>AJAX,JSON</td>
</tr>
</table>
</fieldset>
<fieldset>
<h4>Academic Qualification</h4>

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

<table>
<tr>
<td><strong>S.No.</strong></td>
<td><strong>Qualification</strong></td>
<td><strong>College/University</strong></td>
<td><strong>Year</strong></td>
<td><strong>Percentage</strong></td>
</tr>
<tr>
<td>1</td>
<td>High School</td>
<td>D.A.V</td>
<td>2016</td>
<td>60%</td>
</tr>
<tr>
<td>2</td>
<td>Intermediate</td>
<td>D.A.V</td>
<td>2018</td>
<td>60%</td>
</tr>
<tr>
<td>3</td>
<td>Graduation</td>
<td>PSIT</td>
<td>2022</td>
<td>70%</td>
</tr>
<tr>
<td>4</td>
<td>Post Graduation</td>
<td>PSIT</td>
<td>2024</td>
<td>70%</td>
</tr>
</table>
</fieldset>
<fieldset>
<h4>Strength and Weakness</h4>
<table>
<tr class="trOrange">
<td class="tdhalf"><strong>Strength</strong></td>
<td class="tdhalf"><strong>Weakness</strong></td>
</tr>
<tr>
<td class="tdhalf">
<ol>
<li>Coding</li>
<li>Chess</li>
</ol>
</td>

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

<td class="tdhalf">
<ol>
<li>Bad Handwriting</li>
<li>Sleepy</li>
</ol>
</td>
</tr>
</table>
</fieldset>
<fieldset>
<h4>Declaration</h4>
<p>I hereby declare that all the information given in this form is true
till date.</p>
<div id="lastdiv">
<strong>Place: </strong>Kanpur
<br>
<strong>Date: </strong>09-09-2018
</div>
<strong id="righth3"><h3>Abhishek Kumar
Dwivedi</h3></strong>
</fieldset>

</body>
</html>

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

CSS

fieldset {
margin: 15px auto;
padding: 0 0 0 0;
background-color: white;
}

h4 {
margin: 0 auto;
background-color: orange;
}

body,.trOrange {
background-color: #c1820dbd;
}

#divleft {
padding-right: 20%;
float: left;
margin: 20px auto;
}

#fieldset1 {
background-color: orange;
}

table {
width: 100%;
height: 100%;
}

td {
text-align: center;
}
.tdhalf{
width: 50%;
}

li {
text-align: left;
}

.h1_div_1 {
margin-bottom: 21.44px;
margin-right: 0;
float: left;
}

#righth3 {
float: right;
}

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

h3 {
padding: 0 auto;
margin: 0 auto;
}

#lastdiv {
float: left;
margin-bottom: 0;
}

p{
margin-top: 0;
}

img {
height: 100%;
width: 138.313px;
float: right;
}

<html>
<head>

<link href="web.css" type="text/css" rel="stylesheet"/>


</head>
<body>
<div id="outer">

<div id="header">
<div id="logo">
<img src=".\psit.jpg" width="300px" height="200px"/>
</div>
<div id="data">
<h1>
Pranveer Singh Institute of Technology Kanpur<br></h1>

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

</div>
</div>

<div id="main" >


<div id="lmain">
<h1><u>DEPARTMENT</u></h1><br>
<a href="cse.html" target=_blank>COMPUTER SCIENCE & ENGG.</a><br><br>
<a href="it.html" target=_blank>INFORMATION TECHNOLOGY</a><br><br>
<a href="ec.html" target=_blank>ELECTRONICS & COMMUNICATION ENGG.</a><br>
</div>
<div id="rmain" style=background-image:url("1.jpg ")>
<h1><center>
About<br></center></h1>
<h2>
Pranveer Singh Institute of Technology
University in Bhautipratappur, Uttar Pradesh
Pranveer Singh Institute of Technology is an engineering institute in Kanpur, Uttar Pradesh,
India. The institute is approved by the All India Council For Technical Education and
affiliated to Uttar Pradesh Technical University.</h2>
</div>
<div id="lmain">
<h1 style="color:red;","font-size:40px;"><b><center>
NEWS</center></b></h1>
<marquee direction ="up" height="600px" onmouseover="stop();" onmouseout="start()">
<h3 style="font-size:20px;">
&nbsp;&nbsp; 1. AMCAT TEST FOR B.TECH THIRD YEAR<img src=".\new.gif"
height="25px" width="50px"/><br><br>
&nbsp;&nbsp; 2. 8 SEPTEMBER IS OBSERVED AS A WORKING DAYS<img src=".\
new.gif" height="25px" width="50px"/><br>
</h3>
</marquee>
</div>
</div>
<div id="foter">
<div id="rfoter"><div style="float:left">
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs
p;&nbsp;
Devloped By : Divya Bansal</b>
<br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
College :PSIT
<br><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n
bsp;&nbsp;
Copyright &copy;<a href="http://www.gamil.com" style="color:white; text-
decoration:none;">
Agarwal And Company</a></div>&nbsp;&nbsp;
<img src=".\22736.jpg" width="90px" height="80px"style="border:1px solid blue;border-
radius:5px;" />
</div>
<div id="lfoter">
<h3>
Social Media<br/><br/>

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

<img src=".\fb.png" height="20px" width="20px" /> <a href =" http://facebook.com"


target=_blank style="color:white; text-decoration:none;">facebook</a>&nbsp;
<img src=".\twitter.gif" height="20px" width="20px"/> <a href =" http://Twitter.com"
target=_blank style="color:white; text-decoration:none;">Twitter</a>&nbsp;
<img src=".\google.jpg" height="20px" width="20px"/> <a href =" http://google.com"
target=_blank style="color:white; text-decoration:none;">Google</a>&nbsp;
</div>
</div>
</div>
</body>
</html>

CSS
#outer{
height:1000px;
width:1400px;
}
#header{
height:200px;
width:1400px;
}
#logo{
height:200px;
width:300px;
float:left;
background-color:#08347a;
}
#data{
height:200px;
width:1100px;
background-color:#08347a;
float:right;
font-weight:bold;
font-size:30px;
text-align:center;
color:white;

#main{
height:700px;
width:1400px;
background-color:#ffe6e6;

}
#lmain{
height:700px;
width:330px;
float:left;

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

text-decoration:underline;
background-color:#ffe6e6;
}
#rmain{
height:700px;
width:680px;
float:left;
padding-left:5px;
padding-right:5px;
line-height:57px;
text-decoration:underline;
}
#foter{
height:100px;
width:1400px;
}
#lfoter
{
height:90px;
width:690px;
background-color:#003399;
color:white;
padding-top:10px;
padding-left:10px;
float:left;
}
#rfoter{
height:90px;
padding-top:10px;
width:700px;
background-color:#003399;
color:white;
float:right;
}

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

Program 2: - 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.

Description: - Writing program in XML that contains the information about five books and
displaying the XML file using CSS in browser

Program: -

Books.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="classic.css"?>
<books>
<heading>Welcome </heading>
<book>
<title>Title -: Web Programming</title>
<author>Author -: Chrisbates</author>
<publisher>Publisher -: Wiley</publisher>
<edition>Edition -: 3</edition>
<price> Price -: 300</price>
</book>
<book>
<title>Title -: Internet world-wide-web</title>
<author>Author -: Ditel</author>
<publisher>Publisher -: Pearson</publisher>
<edition>Edition -: 3</edition>
<price>Price -: 400</price>
</book>
<book>
<title>Title -: Computer Networks</title>
<author>Author -: Foruouzan</author>
<publisher>Publisher -: Mc Graw Hill</publisher>
<edition>Edition -: 5</edition>
<price>Price -: 700</price>
</book>
<book>
<title>Title -: DBMS Concepts</title>
<author>Author -: Navath</author>
<publisher>Publisher -: Oxford</publisher>
<edition>Edition -: 5</edition>
<price>Price -: 600</price>
</book>
<book>
<title>Title -: Linux Programming</title>
<author>Author -: Subhitab Das</author>
<publisher>Publisher -: Oxford</publisher>
<edition>Edition -: 8</edition>
<price>Price -: 300</price>
</book>
</books>

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

Classic.css
books {
color: white;
background-color : gray;
width: 100%;
}
heading {
color: green;
font-size : 40px;
background-color : powderblue;
}
heading, title, author, publisher, edition, price {
display : block;
}
title {
font-size : 25px;
font-weight : bold;
}

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

Program 3: - Write a Java applet/AWT to display the Application Program screen i.e.
calculator and other.

Description: - Implementation of calculator using Applet.

Program: -

package webtech_lab;

import java.applet.Applet.*;
import java.awt.*;
import java.awt.event.*;
public class Cal implements ActionListener {

//Declaring Objects
Frame f=new Frame();
Label l1=new Label("First Number");
Label l2=new Label("Second Number");
Label l3=new Label("Result");

TextField t1=new TextField();


TextField t2=new TextField();
TextField t3=new TextField();
Label res=new Label();

Button b1=new Button("Add");


Button b2=new Button("Sub");
Button b3=new Button("Mul");
Button b4=new Button("Div");
Button b5=new Button("Cancel");

Cal()
{
//Giving Coordinates
l1.setBounds(50,100,100,20); l2.setBounds(50,140,100,20);
l3.setBounds(50,180,100,20);

t1.setBounds(200,100,100,20); t2.setBounds(200,140,100,20);
//t3.setBounds(200,180,100,20);
res.setBounds(200,180,100,20);
b1.setBounds(50,250,50,20); b2.setBounds(110,250,50,20);
b3.setBounds(170,250,50,20); b4.setBounds(230,250,50,20);
b5.setBounds(290,250,50,20);

//Adding components to the frame


f.add(l1); f.add(l2); f.add(l3);
f.add(t1); f.add(t2); f.add(t3);
f.add(res);
f.add(b1); f.add(b2); f.add(b3);
f.add(b4); f.add(b5);

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);

f.setLayout(null);
f.setVisible(true);
f.setSize(400,350);
}

public void actionPerformed(ActionEvent e)


{
int n1=Integer.parseInt(t1.getText());
int n2=Integer.parseInt(t2.getText());

if(e.getSource()==b1) { res.setText(String.valueOf(n1+n2)); }
if(e.getSource()==b2) { res.setText(String.valueOf(n1-n2)); }
if(e.getSource()==b3) { res.setText(String.valueOf(n1*n2)); }
if(e.getSource()==b4) { res.setText(String.valueOf(n1/n2)); }
if(e.getSource()==b5) { System.exit(0); }
}

public static void main(String...s)


{ new Cal(); }
}

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

Program 4: - Write programs using Java script for Web Page to display browsers
information.

Description: - Designing of Browser Navigator information using Javascript.

Program: -

<!DOCTYPE html>
<html>
<head>
<title>Browser Information</title>
<style type="text/css">
body { background-color: #b6e87e40; }
h1 { color: rgb(127,29,230); }
button { background-color: white;
border: 2px solid #4CAF50;
color: black;
padding: 16px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
transition-duration: 0.4s;
cursor: pointer;
border-style: groove; }
button:hover { background-color: #4CAF50;
color: white;
font-size: 20px; }
#divLeft{ float: left;
margin-left: 20%; }
#divRight{ float: right;
font-size: 205px;
text-align: left;
margin-right: 20%;
color: #05717d; }
span:hover{ font-size:215px; }
</style>
<script type="text/javascript">
function height(){ alert("Browser Height is: "+window.innerHeight); }
function width(){ alert("Browser Width is: "+window.innerWidth); }
function cPDepth(){
alert("Color Depth is: "+screen.colorDepth+"\nPixel Depth is:
"+screen.pixelDepth);}
function bName(){
alert("Current Browser appname is: "+navigator.appName+"\nCurrent
Browser appcode name is: "+navigator.appCodeName)
}
function pName(){alert("Product name of the browser engine is:
"+navigator.product);}

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

function appVer(){alert("Browser Version is:\n "+navigator.appVersion);


}
function platform(){alert("Browser Platform is: "+navigator.platform);
}
</script>
</head>
<body>
<div id="divLeft">
<h1>Browser Information using <br>Browser Object Model</h1>
<button onclick="height()">Display Height</button><br><br>
<button onclick="width()">Display Width</button><br><br>
<button onclick="cPDepth()">Display Screen Color and Pixel
Depth</button><br><br>
<button onclick="bName()">Display Browser appname and appcode
Name</button><br><br>
<button onclick="pName()">Product name of the browser
engine</button><br><br>
<button onclick="appVer()">Display Browser Version</button><br><br>
<button onclick="platform()">Browser Platform</button>
</div>
<div id="divRight">
<span>B</span><br><span>O</span><br><span>M</span>
</div>
</body>
</html>

OUTPUT

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

Program 5: - Write a program to illustrate JDBC connectivity and perform CRUD


operation on a table student/employee (at least 5 attributes).

Description: - Implementation of CRUD Operation on database using Java Program.

Program: -

package webtech;
import java.sql.*;
import java.io.*;
import oracle.jdbc.driver.DBConversion;

public class Jdbc {


static boolean db_created=false;
public static void main(String args[])
{ Connection con;
Statement state;
ResultSet rs;
int no;
int sal;
String name;
int ch;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("Driver Loaded");

con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","DIVYA"
,"divya");
do
{ System.out.println("\n");
System.out.println("Menu:");
System.out.println("1.Create table");
System.out.println("2.Insert Record into the Table");
System.out.println("3.Update The Existing Record.");
System.out.println("4.Display all the Records from the Table");
System.out.println("5.Delete");
System.out.println("6.Exit");
System.out.println("Enter your choice: ");

BufferedReader br=new BufferedReader(new


InputStreamReader(System.in));
ch=Integer.parseInt(br.readLine());

String sql;

switch(ch)
{ case 1:
Statement stmt=con.createStatement();
String ct="create table employee(emp_id number(5),emp_name
varchar2(30),emp_sal number(8,2))";

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

boolean b=stmt.execute(ct);
if(b==false) System.out.println("table not created");
else {db_created=true;}
stmt.close();
break;
case 2:
if(db_created==true){
state=con.createStatement();
int i,n;
System.out.println("enter the no of values you want
to insert");
n=Integer.parseInt(br.readLine());
for(i=0;i<n;i++)
{
System.out.println("Enter Employee Number: ");
no=Integer.parseInt(br.readLine());
System.out.println("Enter Employee Name: ");
name=br.readLine();
System.out.println("Enter Employee Salary: ");
sal=Integer.parseInt(br.readLine());
sql="insert into employee values(?,?,?)";
PreparedStatement p=con.prepareStatement(sql);
p.setInt(1,no);
p.setString(2,name);
p.setInt(3,sal);
p.executeUpdate();
System.out.println("Record Added");
p.close();
}}
else
System.out.println("create table first");
break;

case 3:
if(db_created==true){
state=con.createStatement();
System.out.println("Enter Employee Number for the record
you wish to Update: ");
no = Integer.parseInt(br.readLine());
System.out.println("Enter new Name: ");
name = br.readLine();
System.out.println("Enter new Salary: ");
sal = Integer.parseInt(br.readLine());
sql="update employee set Name=?, Salary=? where Code=?";
PreparedStatement p=con.prepareStatement(sql);
p.setString(1,name);
p.setInt(2,sal);
p.setInt(3,no);
p.executeUpdate();
System.out.println("Record Updated");
p.close(); }
else

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

System.out.println("create table first");


break;

case 4:
if(db_created==true){
state=con.createStatement();
sql="select * from employee";
rs=state.executeQuery(sql);
while(rs.next())
{
System.out.println("\n");
System.out.print("\t" +rs.getInt(1));
System.out.print("\t" +rs.getString(2));
System.out.print("\t" +rs.getInt(3));
} }
else
System.out.println("create table first");
break;

case 5:
if(db_created==true){
state=con.createStatement();
sql="delete from employee where emp_id='1'";
rs=state.executeQuery(sql);
state.close();
}
else
System.out.println("create table first");
break;
case 6:
System.exit(1);
break;
default:
System.out.println("Invalid Choice");
break;
}
}while(ch!=6);
con.close();
}catch(Exception e)
{
System.out.println(e);
}
} }

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

Program 6: - Write a simple servlet to design an entry form of student details and
send it to store at database server like SQL, Oracle or MS Access.

Description: - Implementation of CRUD Operation on database by a server side program


i.e. servlet program

Program: -

Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="./register" method="post">
<table>
<tr> <td>Roll Number:</td>
<td><input type="number" name="roll"></td>
</tr>
<tr> <td>student name:</td>
<td><input type="text" name="name"></td>
</tr>
<tr> <td>Course:</td>
<td><input type="text" name="course"></td>
</tr>
<tr> <td>branch:</td>
<td><input type="text" name="branch"></td>
</tr>
<tr> <td></td>
<td><input type="submit" value="add"></td>
</tr>
</table>
</form>
</body>
</html>

Connect.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Connect {


public static Connection conn() throws ClassNotFoundException,
SQLException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","akku1","akku
1");

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

return conn;
}
}

AddInDatabase.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// Servlet implementation class AddInDatabase

public class AddInDatabase extends HttpServlet {


private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
String roll = request.getParameter("roll");
String name = request.getParameter("name");
String course = request.getParameter("course");
String branch = request.getParameter("branch");
try {
Statement stmt = Connect.conn().createStatement();
String query = "insert into student
values("+roll+",'"+name+"','"+course+"','"+branch+"')";
stmt.executeQuery(query);
Connect.conn().close();
stmt.close();
out.println("Registration Successfull"); }
catch(java.sql.SQLIntegrityConstraintViolationException e) {
out.println("Error resgistering this student. A student with same roll number
exists!");
}
catch(Exception e) { out.println("Registration Unsuccessfull!");
System.out.println(e); }
finally { out.println("<br><a href='index.html'>Go to
home page</a>");
} } }

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-
app_2_4.xsd">
<display-name>Servlet Store student details in database</display-name>
<servlet>
<description>
</description>
<display-name>AddInDatabase</display-name>
<servlet-name>AddInDatabase</servlet-name>
<servlet-class>AddInDatabase</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddInDatabase</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

Program 7: - Install a database (MYSQL or Oracle). Create a table which should


contain at least the following fields: name, password, email-id, phone
number Write a java program/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.

Description: - Implementation of CRUD Operation on database by using JSP and HTML


page

Program: -

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1><a href="RegisterForm.html">Register new user</a><br>
<a href="Display.jsp">Display existing users</a></h1>

</body>
</html>

RegisterForm.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head> <body>
<form action="Register.jsp" method="post">
<table>
<tr> <td>Name:</td>
<td><input type="text" name="name"></td>
</tr>
<tr> <td>Password:</td>
<td><input type="text" name="password"></td>
</tr>
<tr> <td>Email:</td>
<td><input type="email" name="email"></td>
</tr>
<tr> <td>Phone Number:</td>
<td><input type="number" name="phone"></td>
</tr>
<tr> <td></td>

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

<td><input type="submit" value="Register"></td>


</tr>
</table>
</form>
</body> </html>

Register.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.Statement" %>
<%@ page import="connection.Connect" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<% String name = request.getParameter("name");
String password = request.getParameter("password");
String email = request.getParameter("email");
String phone = request.getParameter("phone");
try {
Statement stmt = Connect.conn().createStatement();
String query = "insert into users1
values('"+name+"','"+password+"','"+email+"',"+phone+")";
stmt.executeQuery(query);
Connect.conn().close();
stmt.close();
out.println("Registration Successfull"); }
catch(Exception e) {
out.println("Registration Unsuccessfull!");
System.out.println(e); }
finally {
out.println("<br><a href='index.html'>Go to home page</a>"); } %>
</body>
</html>

Display.jsp

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


pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*" %>
<%@ page import="connection.Connect" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

<body>
<% try{
Statement stmt =
Connect.conn().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("select * from users1");
if(!rs.next()){ out.println("No users registered!"); }
else{
%>

<h1>Users are:</h1><br>
<table border="1">
<thead>
<tr>
<td>Name</td>
<td>Password</td>
<td>Email</td>
<td>Phone</td>
</tr>
</thead>
<tbody>
<%
rs.previous();
while (rs.next()) {
String name = rs.getString(1);
String password = rs.getString(2);
String email = rs.getString(3);
int phone = rs.getInt(4);%>

<tr>
<td><%= name %></td>
<td><%= password %></td>
<td><%= email %></td>
<td><%= phone %></td>
</tr>
<%}}%>
</tbody>
</table>
<% }
catch(Exception e) {
System.out.println(e);
}
finally {
out.println("<br><a href='index.html'>Go to home page</a>");
}
%>
</body>
</html>

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

Connect.java

package connection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Connect {


public static Connection conn() throws ClassNotFoundException,
SQLException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","akku1","akku
1");
return conn;
}
}

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

Program 8: - Assumes four user user1, user2, user3 and user4 having a password
pwd1, pwd2, pwd3 and pwd4 respectively. Write a servlet for doing
the following. Create a cookie and these four-user id's and password to
this cookie. 2. Read the user id and passwords entered in the Login
form and authenticate with the values available in the cookies.

Description: - Implementation of Cookie using servlet life cycle.

Program: -

Servlet Life cycle:


1. Servlet class loading
2. Servlet Instantiation
3. call the init method
4. call the service method
5. call destroy method

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>

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

</html>

Addcook.java:
import javax.servlet.* ;
import javax.servlet.http.*;
import java.io.*;
public class Addcook extends HttpServlet
{
String user,pas;
public void service(HttpServletRequestreq,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(HttpServletRequestreq,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"))||

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

(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())) )
{
//RequestDispatcherrd=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>

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

OUTPUT

Cookie Added

Display of Cookie

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

Program 9: - 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

Description: - implementation of registration and authentication process by using JSP page,


HTML page and D/B

Program: -

Connect.java

package connection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Connect {


public static Connection conn() throws ClassNotFoundException, SQLException {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","akku1","akku1");
return conn; }
}

Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Login Page</h1>
<form action="Login.jsp" method="get">
<br>
<table>
<tr> <td>Username</td>
<td><input type="text" name="uname"></td> </tr>
<tr> <td>Password</td>
<td><input type="text" name="upass"></td> </tr>
<tr> <td></td>
<td><input type="submit" value="Login"></td> </tr>
<tr> <td></td>
<td><center><a href="RegisterForm.html">
New user? Register here.</a></center></td> </tr>
</table>
</form>
</body>

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

</html>

RegisterForm.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Registration Page</h1>
<form action="Register.jsp" method="post">
<br>
<table>
<tr> <td>Name</td>
<td><input type="text" name="name"></td> </tr>
<tr> <td>Username</td>
<td><input type="text" name="uname"></td> </tr>
<tr> <td>Password</td>
<td><input type="text" name="upass"></td> </tr>
<tr> <td>Email</td>
<td><input type="text" name="email"></td> </tr>
<tr> <td>Phone Number</td>
<td><input type="number" name="phone"></td></tr>
<tr> <td></td>
<td><input type="submit" value="Register here"></td>
</tr>
</table>
</form>
<a href="index.html">Go back to home page</a>
</body>
</html>

Login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*" %>
<%@ page import="connection.Connect" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
try{
boolean exist=false;
Statement stmt =
Connect.conn().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

ResultSet rs = stmt.executeQuery("select * from users");


if(!rs.next()){
%>
<h1>No users registered! Register first.</h1>
<%
}
else{
rs.previous();
String uname = request.getParameter("uname");
String password = request.getParameter("upass");
while (rs.next()) {
String name = rs.getString(2);
String pass = rs.getString(3);
if(uname.equals(name)&&password.equals(pass)) {
exist=true;
break; }
}
if(exist){ %>
<h1>You have successfully logged in <%= rs.getString(1) %></h1>
<br>
<strong>Your username is <%= rs.getString(2)%><br>
Your email is <%= rs.getString(4)%><br>
Your phone number is <%= rs.getInt(5)%></strong>
<% }
else{
%>
<h1>Wrong username or password!</h1>
<%
}
}}
catch(Exception e) {
System.out.println(e);
}
finally {
out.println("<br><a href='index.html'>Go to home page</a>");
}
%>
</body>
</html>

Register.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.Statement" %>
<%@ page import="connection.Connect" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

<body>
<%
String name = request.getParameter("name");
String uname = request.getParameter("uname");
String password = request.getParameter("upass");
String email = request.getParameter("email");
String phone = request.getParameter("phone");
try {
Statement stmt = Connect.conn().createStatement();
String query = "insert into users
values('"+name+"','"+uname+"','"+password+"','"+email+"',"+phone+")";
stmt.executeQuery(query);
Connect.conn().close();
stmt.close();
out.println("Registration Successfull");
}catch(java.sql.SQLIntegrityConstraintViolationException e) {
out.println("Error resgistering this user. A student with same username exists!");
}
catch(Exception e) {
out.println("Registration Unsuccessfull!");
System.out.println(e);
}
finally {
out.println("<br><a href='index.html'>Go to home page</a>");
} %>
</body>
</html>

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

Program 10: - Design and Implement a simple shopping cart example with session
tracking API.

Description: - To demonstrate how HTTPSession work

Program: -

CartServlet.java

package pack;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class CartServlet
*/
public class CartServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public CartServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
String itemName=request.getParameter("itemName");
String itemPrice=request.getParameter("itemPrice");
Item item = new Item(itemName,new Integer(Integer.parseInt(itemPrice)));
HttpSession session=request.getSession();
if(session.isNew()) {
ArrayList cart = new ArrayList();
cart.add(item);
session.setAttribute("cart",cart);
}
else {
ArrayList cart = (ArrayList)session.getAttribute("cart");
cart.add(item);
}

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

PrintWriter out = response.getWriter();


out.println("<h3>Selected item is successfully added to Cart</h3>");
out.println("<a href='ViewServlet'>View Cart</a>");
out.println("<a href='ItemServlet'>View Items</a>");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}

DeleteServlet.java

package pack;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class DeleteServlet
*/

public class DeleteServlet extends HttpServlet {


private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public DeleteServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
String item=request.getParameter("item");
System.out.println(item);
HttpSession session=request.getSession();
ArrayList cart = (ArrayList)session.getAttribute("cart");

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

Iterator itr = cart.iterator();


while(itr.hasNext()) {
Item i = (Item)itr.next();
String item1 = i.toString();
if(item.equals(item1)) {
out.println(i.getName()+" is deleated<br>");
//cart.remove(i);
itr.remove();
session.setAttribute("cart", cart);
}
}
out.println("<a href='ItemServlet'>View Items</a><br>");
out.println("<a href='ViewServlet'>View Cart</a><br>");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}

Item.java
package pack;
public class Item {

private String name;


private Integer price;
public Item() {
// TODO Auto-generated constructor stub
}
public Item(String name, Integer price) {
super();
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
}

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

ItemServlet.java

package pack;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class ItemServlet
*/
public class ItemServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ItemServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
PrintWriter out = response.getWriter();
ArrayList cItems=null;
ServletContext context=getServletConfig().getServletContext();
if(context.getAttribute("cItems")==null) {
ArrayList items = new ItemSvc().getItems();
context.setAttribute("cItems", items);
cItems=items;
}
else {
cItems = (ArrayList)context.getAttribute("cItems");
}
Iterator itr=cItems.iterator();
while(itr.hasNext()) {
Item item = (Item)itr.next();
out.println("<form action='CartServlet'>");
out.println("Name:- "+item.getName()+"\t Price:- "+item.getPrice());
out.println("<input type='hidden' value='"+item.getName()+"' name='itemName'>");
out.println("<input type='hidden' value='"+item.getPrice()+"' name='itemPrice'>");
out.println("<input type='submit' value='add to cart'>");
out.println("</form>");
}
out.println("<a href='index.html'>home</a><br>");

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}

ItemSvc.java
package pack;
import java.sql.*;
import java.util.ArrayList;
public class ItemSvc {

Connection c;
public ItemSvc() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
c = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","hr","psit123");
}catch(Exception e){
e.printStackTrace();
System.out.println(e.getMessage());
}
}
public ArrayList getItems()
{
ArrayList items = new ArrayList();
try {
PreparedStatement ps = c.prepareStatement("select * from items");
ResultSet rs = ps.executeQuery();
while(rs.next())
{
Item item=new Item(rs.getString(2),rs.getInt(3));
items.add(item);
//System.out.println(item.getName());
//System.out.println(item.getPrice());
}
c.close();
}catch(Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
return items;
}
}

ViewServlet.java
package pack;
import java.io.IOException;
import java.io.PrintWriter;

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class ViewServlet
*/
public class ViewServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public ViewServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
HttpSession session=request.getSession();
ArrayList cart = (ArrayList)session.getAttribute("cart");
Iterator itr = cart.iterator();
while(itr.hasNext()) {
Item item = (Item)itr.next();
out.println(item.getName()+"\t"+item.getPrice()+"<br>");
out.println("<form action='DeleteServlet'>");
out.println("Name:- "+item.getName()+"\t Price:- "+item.getPrice());
out.println("<input type='hidden' value='"+item+"' name='item'>");
out.println("<input type='submit' value='delete from cart'>");
out.println("</form>");
}
out.println("<a href='ItemServlet'>View Items</a><br>");
out.println("<a href='index.html'>home</a><br>");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

Extra Programs
Program 1: - A super class Detail has been defined to store the details of a customer.
Define a subclass Bill to compute the monthly telephone charge of the
customer as per the chart given below:
Number of Calls Rate
1 – 100 Only Rental charge
101 – 200 60 paisa per call + rental charge
201 – 300 80 paisa per call + rental charge
Above 300 1 rupee per call + rental charge

Description: - To demonstrate the concept of Inheritance

Program: -
/**
* The superclass Detail stores the details of a customer and the subclass Bill calculates the
telephone package com.corejava;
import java.io.*;
class Detail //superclass
{
String name, address;
long telno;
double rent;
Detail(String n1, String a1, long t1, double r1)
{
name = n1;
address = a1;
telno = t1;
rent = r1;
}

void show()
{
System.out.println("Name of customer = "+name);
System.out.println("Address = "+address);
System.out.println("Telephone Number = "+telno);
System.out.println("Monthly Rental = Rs. "+rent);
}
} //end of superclass Detail

class Bill extends Detail //subclass


{
int n;
double amt;

Bill(String n1, String a1, long t1, double r1, int c)


{
super(n1,a1,t1,r1); //initializing data members of superclass by calling its constructor

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

n = c;
amt = 0.0;
}

void cal()
{
if(n>=1 && n<=100)
amt = rent;
else if(n>=101 && n<=200)
amt = 0.6*n + rent;
else if(n>=201 && n<=300)
amt = 0.8*n + rent;
else amt = 1*n + rent; }

void show()
{
super.show(); //calling the superclass function show()
System.out.println("No. of calls = "+n);
System.out.println("Amount to be paid = Rs. "+amt);
}
} //end of subclass Bill

public class InheritanceDemo {


public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter the name : ");
String n1=br.readLine();
System.out.print("Enter the address : ");
String a1=br.readLine();
System.out.print("Enter the telephone number : ");
long t1=Long.parseLong(br.readLine());
System.out.print("Enter the monthly rental : ");
double r1=Double.parseDouble(br.readLine());
System.out.print("Enter the number of calls : ");
int c=Integer.parseInt(br.readLine());
Bill ob=new Bill(n1,a1,t1,r1,c); //creating object of subclass
System.out.println("*** Output ***");
ob.cal();
ob.show(); //calling show() function of subclass
}
}

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

Program 2: - Write a Java applet to display the Application Program screen i.e.
Colour mixer pallet.

Description: - Implementation of Colour mixer pallet using Applet.

Program: -

import java.awt.*;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;

public class ColorMix implements AdjustmentListener{


int r, g , b;
Frame f = new Frame();

Label l = new Label("Color");

Scrollbar s1 = new Scrollbar();


Scrollbar s2 = new Scrollbar();
Scrollbar s3 = new Scrollbar();

public ColorMix() {
f.setLayout(null);
f.setSize(1000,1000);

f.add(l);
f.add(s1);
f.add(s2);
f.add(s3);

l.setBounds(50, 100, 150, 200);


s1.setBounds(300,100, 50, 200);
s2.setBounds(500,100, 50, 200);
s3.setBounds(700,100, 50, 200);

s1.addAdjustmentListener(this);
s2.addAdjustmentListener(this);
s3.addAdjustmentListener(this);

l.setBackground(Color.WHITE);
l.setForeground(Color.BLACK);
s1.setBackground(Color.RED);
s2.setBackground(Color.GREEN);
s3.setBackground(Color.BLUE);
f.setBackground(Color.LIGHT_GRAY);

s1.setMaximum(265);

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

s2.setMaximum(265);
s3.setMaximum(265);

f.setVisible(true);

}
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
// TODO Auto-generated method stub
r = s1.getValue();
g = s2.getValue();
b = s3.getValue();
l.setBackground(new Color(r , g , b));
l.setText(String.valueOf(r) +"," + String.valueOf(g) +"," +
String.valueOf(b));

}
}

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

Program 3: - Write a program using TCP/IP socket between client and server and
perform two-way communication.

Description: - Developing client and server programs to implement two-way


communication using TCP/IP socket.

Program: -
Server Side-
import java.io.*;
import java.net.*;
public class Server {

public static void main(String[] args) {


// TODO Auto-generated method stub
try {
ServerSocket ss = new ServerSocket(1234);
Socket s = ss.accept();
DataInputStream din = new DataInputStream(s.getInputStream());
DataOutputStream dout = new
DataOutputStream(s.getOutputStream());
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str = "",str2="";
while(!str.equals("stop")) {
str = din.readUTF();
System.out.println("Client says: "+str);
str2 = br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } }

Client Side-
import java.io.*;
import java.net.*;
public class Client {

public static void main(String[] args) {


// TODO Auto-generated method stub
try {
Socket s = new Socket(InetAddress.getLocalHost(), 1234);
DataInputStream din = new DataInputStream(s.getInputStream());
DataOutputStream dout = new
DataOutputStream(s.getOutputStream());

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));
String str = "",str2="";
while(!str2.equals("stop")) {
str2 = br.readLine();
dout.writeUTF(str2);
dout.flush();
str = din.readUTF();
System.out.println("Server says: "+str);
}
din.close();
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } }

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

Program 4: - Write a program to illustrate Batch Transaction with prepared


statement.

Description: - Implementation of CRUD Operation in batch mode on database using Java


Program.

Program: -
BatchUpdateDemo_Connection.java
package webtech;
import java.sql.*;
public class BatchUpdateDemo_Connection {
public static Connection getOracleConnection()throws Exception{
String driver="oracle.jdbc.driver.OracleDriver";
String URL="jdbc:oracle:thin:@localhost:1521:xe";
String Username="DIVYA";
String password="divya";
Class.forName(driver);
return DriverManager.getConnection(URL,Username,password); } }

BatchUpdate.java
package webtech;
import java.sql.*;
public class BatchUpdate {
static Savepoint sp1;
public static void main(String args[]) throws Exception
{ Connection con=BatchUpdateDemo_Connection.getOracleConnection();
Statement stmt=null;
try{ con.setAutoCommit(false);
stmt=con.createStatement();
stmt.addBatch("delete from emplo");
stmt.addBatch("insert into emplo values(104,'ABC',5694)");
stmt.addBatch("insert into emplo values(105,'DEF',6694)");
int[] uc=stmt.executeBatch();
sp1 = con.setSavepoint("spv1");
stmt.addBatch("insert into emplo values(106,'GHI',7694)");
stmt.addBatch("insert into emplo2 values(107,'JKl',8694)");
int[] uc1=stmt.executeBatch();
System.out.println("...."+uc.length);
for(int i=0;i<uc.length;i++)
{ System.out.println(uc[i]); }
con.commit(); }
catch(BatchUpdateException e)
{ System.out.println(e);
int[] abc=e.getUpdateCounts();
System.out.println("...."+abc.length);
for(int i=0;i<abc.length;i++)
{ System.out.println(abc[i]); }
con.rollback(sp1);
con.commit(); } } }

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

Program 5: - To Develop a student Marks sheet by using Servlet and Html with
database Oracle.

Description: - Use JDBC API to develop student marksheet generation application

Program: -
Creating Database RESULT:
CREATE TABLE "RESULT"
( "ROLLNO" NUMBER,
"NAME" VARCHAR2(40),
"RESULT" VARCHAR2(40),
"GRADE" VARCHAR2(40),
CONSTRAINT "RESULT_PK" PRIMARY KEY ("ROLLNO") ENABLE
)
/

index.html
<html>
<body>
<form action="servlet/Search">
Enter your Rollno:<input type="text" name="roll"/><br/>

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


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

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

public class Search extends HttpServlet {


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

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

String rollno=request.getParameter("roll");
int roll=Integer.valueOf(rollno);

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

PreparedStatement ps=con.prepareStatement("select * from result where rollno=?");


ps.setInt(1,roll);

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

out.print("<table width=50% border=1>");


out.print("<caption>Result:</caption>");

ResultSet rs=ps.executeQuery();

/* Printing column names */


ResultSetMetaData rsmd=rs.getMetaData();
int total=rsmd.getColumnCount();
out.print("<tr>");
for(int i=1;i<=total;i++)
{
out.print("<th>"+rsmd.getColumnName(i)+"</th>");
}

out.print("</tr>");

/* Printing result */

while(rs.next())
{
out.print("<tr><td>"+rs.getInt(1)+"</td><td>"+rs.getString(2)+"
</td><td>"+rs.getString(3)+"</td><td>"+rs.getString(4)+"</td></tr>");

}
out.print("</table>");
}catch (Exception e2) {e2.printStackTrace();}
finally{out.close();}

}
}
web.xml
<web-app>

<servlet>
<servlet-name>Search</servlet-name>
<servlet-class>Search</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Search</servlet-name>
<url-pattern>/servlet/Search</url-pattern>
</servlet-mapping>

</web-app>

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

Content Beyond Syllabus


Program 1: - Store 5 Students (name, branch, rollno, age) objects in list. Perform any
sorting technique so as to display list in ascending order of rollno and display in
descending order of age.
Description: - Implementation of Comparator Interface and TreeSet of Collection API.
Program:
import java.util.*;
public class StudentListTest
{
public static void main(String[] args)
{
TreeSet<Student> s1 = new TreeSet<Student>(new RollComparator());
TreeSet<Student> s2 = new TreeSet<Student>(new AgeComparator());

s1.add(new Student("Ajay Singh","CSE",10001,21));


s1.add(new Student("Ajay Sharma","ME",30001,22));
s1.add(new Student("Ajay Yadav","EC",20001,23));
s1.add(new Student("Ajay Jha ","EE",40001,22));

s2.add(new Student("Ajay Singh","CSE",10001,21));


s2.add(new Student("Ajay Sharma","ME",30001,24));
s2.add(new Student("Ajay Yadav","EC",20001,23));
s2.add(new Student("Ajay Jha ","EE",40001,22));

Iterator i1 = s1.iterator();
Iterator i2 = s2.iterator();

System.out.println(); System.out.println(); System.out.println();


System.out.println("According to Roll Number(Ascending Order)");

while(i1.hasNext())
{
Student e = (Student) i1.next();
System.out.println(e);
}
System.out.println(); System.out.println(); System.out.println();
System.out.println("According to Age(Descending Order)");

while(i2.hasNext())
{
Student e = (Student) i2.next();
System.out.println(e);
}
}
}

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

class Student
{
String name,branch;
Integer roll,age;

public Student(String name,String branch,Integer roll,Integer age)


{
this.name=name;
this.branch=branch;
this.roll=roll;
this.age=age;
}
public String toString()
{
return "Name:- "+name+"\t Branch:- "+branch+"\t RollNo:- "+roll+"\t
Age:-"+age;
}
}
class RollComparator implements Comparator<Student>
{
public int compare(Student s1,Student s2)
{
return s1.roll.compareTo(s2.roll);
}
}
class AgeComparator implements Comparator<Student>
{
public int compare(Student s1,Student s2)
{
return s2.age.compareTo(s1.age);
}
}

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

Program 2: - Perform union (AUB), intersection and difference (A-B) operations


using set collection.
Description: - Implementation of Mathematical set operation using TreeSet of Collection
API.
Program:
package com.corejava;

import java.util.*;

class SetOperations
{
public static void main(String str[])
{
Collection<String> col1 = new TreeSet<String>();
col1.add("a");
col1.add("b");
col1.add("c");

Collection<String> col2 = new TreeSet<String>();


col2.add("b");
col2.add("c");
col2.add("d");
col2.add("e");

/*For Union*/
Collection<String> temp1 = new TreeSet<String>(col1);
temp1.addAll(col2);
System.out.println("Union of Set-A and Set-B "+temp1);

/*For Intersection*/
Collection<String> temp2 = new TreeSet<String>(col1);
temp2.retainAll(col2);
System.out.println("Intersection of Set-A and Set-B "+temp2);

/*For Difference*/
Collection<String> temp3 = new TreeSet<String>(col1);
temp3.removeAll(col2);
System.out.println("Difference of Set-A and Set-B "+temp3);
}
}

Department of Computer Science and Engineering


RCS-554
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

Program 3: - Create a Map that consists of Country-Capital pair to store information


about various countries along with their capital name. Display the entries in sorted
order of Country and Capital.
Description: - Implementation of Map and Linked HashMap of Collection API.
Program:

package com.democollection;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Stream;

public class MapSortByKeyExample {

public static void main(String[] args) {


Map<String, String> countryCapitalMap = new HashMap<String, String>();
countryCapitalMap.put("guyana", "georgetown");
countryCapitalMap.put("nepal", "kathmandu");
countryCapitalMap.put("australia", "canberra");
countryCapitalMap.put("india", "new delhi");
countryCapitalMap.put("japan", "tokyo");

System.out.println("Original Map : \n" + countryCapitalMap);

Map<String, String> sortedMap1 = new LinkedHashMap<String, String>();

Stream<Map.Entry<String, String>> stream1 = countryCapitalMap.entrySet()


.stream();
stream1.sorted(Map.Entry.comparingByKey()).forEachOrdered(
c -> sortedMap1.put(c.getKey(), c.getValue()));

System.out.println("Map sorted by key : \n" + sortedMap1);

Map<String, String> sortedMap2 = new LinkedHashMap<String, String>();

Stream<Map.Entry<String, String>> stream2 = countryCapitalMap.entrySet()


.stream();
stream2.sorted(Map.Entry.comparingByValue()).forEachOrdered(
c -> sortedMap2.put(c.getKey(), c.getValue()));

System.out.println("Map sorted by value : \n" + sortedMap2);

Department of Computer Science and Engineering


RCS-554

You might also like