KCS-652-WT LAB Manual-2021-22
KCS-652-WT LAB Manual-2021-22
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
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>
<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>
<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>
<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>
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;
}
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>
<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>
</div>
</div>
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;
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;
}
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>
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;
}
Program 3: - Write a Java applet/AWT to display the Application Program screen i.e.
calculator and other.
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");
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);
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);
}
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); }
}
Program 4: - Write programs using Java script for Web Page to display browsers
information.
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);}
OUTPUT
Program: -
package webtech;
import java.sql.*;
import java.io.*;
import oracle.jdbc.driver.DBConversion;
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: ");
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))";
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
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);
}
} }
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.
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;
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;
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>
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>
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
<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>
Connect.java
package connection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
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.
Program: -
PROGRAM
cologin.html:
<html>
<head>
<title> login Page </title>
<p style= "background:yellow; top:100px; left:250px; position:absolute; ">
</head>
<body>
<form ACTION="clogin">
<label> Login </label>
<input type="text" name="usr" size="20"><br><br>
<label> Password </label>
<input type="password" name="pwd" size="20"><br><br>
<input type="submit" value="submit">
</form>
</body>
</html>
cologin1.html
<html>
<head>
<title> login Page </title>
<p style= "background:yellow; top:100px; left:250px; position:absolute; ">
</head>
<body>
<form ACTION="clogin1">
<label> Login </label>
<input type="text" name="usr" size="20"><br><br>
<label> Password </label>
<input type="password" name="pwd" size="20"><br><br>
<input type="submit" value="submit">
</form>
</body>
</html>
Addcook.java:
import javax.servlet.* ;
import javax.servlet.http.*;
import java.io.*;
public class Addcook extends HttpServlet
{
String user,pas;
public void service(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"))||
(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>
OUTPUT
Cookie Added
Display of Cookie
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
Program: -
Connect.java
package connection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
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>
</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);
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 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>
Program 10: - Design and Implement a simple shopping cart example with session
tracking API.
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);
}
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
*/
Item.java
package pack;
public class Item {
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>");
} /**
* @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;
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);
}
}
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
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
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
Program 2: - Write a Java applet to display the Application Program screen i.e.
Colour mixer pallet.
Program: -
import java.awt.*;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
public ColorMix() {
f.setLayout(null);
f.setSize(1000,1000);
f.add(l);
f.add(s1);
f.add(s2);
f.add(s3);
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);
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));
}
}
Program 3: - Write a program using TCP/IP socket between client and server and
perform two-way communication.
Program: -
Server Side-
import java.io.*;
import java.net.*;
public class Server {
Client Side-
import java.io.*;
import java.net.*;
public class Client {
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(); } } }
Program 5: - To Develop a student Marks sheet by using Servlet and Html with
database Oracle.
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/>
Search.java
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
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");
ResultSet rs=ps.executeQuery();
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>
Iterator i1 = s1.iterator();
Iterator i2 = s2.iterator();
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);
}
}
}
class Student
{
String name,branch;
Integer roll,age;
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");
/*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);
}
}
package com.democollection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Stream;