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

Advanced Java Full Notes Till 20 June

Nehru Rajput took notes on Core Java and advanced Java topics over two days. On day one, they covered programming components like variables, methods, classes, and interfaces. They defined applications and web applications. On day two, they discussed the differences between objects, object references, and object reference variables. They also defined streams, file storage, database storage, and JDBC drivers.

Uploaded by

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

Advanced Java Full Notes Till 20 June

Nehru Rajput took notes on Core Java and advanced Java topics over two days. On day one, they covered programming components like variables, methods, classes, and interfaces. They defined applications and web applications. On day two, they discussed the differences between objects, object references, and object reference variables. They also defined streams, file storage, database storage, and JDBC drivers.

Uploaded by

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

Nehru Rajput's Notes

dt : 27/4/2022(day-1)

part-1 : CoreJava

=>Alphabets(Programming Components)

(a)Variables

(b)Methods

(c)Blocks

ii
(d)Constructors

ath
(e)Classes

(f)Interfaces

ip
(g)AbstractClasses

=>Programming Concepts

=>Object Oriented Programming features


Ma
Part-2 : AdvJava
sh
define Aplication?

=>The set-of-programs collected together


ate

to perform define action is known as

Application.
nk

define Web Application?


Ve

=>The application which is executing in Web

environment or Internet environment is known

as Web Application.

=>We use the following technologies to

construct WebApplications:
1.JDBC

2.Servlet

3.JSP

1.JDBC:

=>JDBC stands for 'Java DataBase

ii
Connectivity' and which is used to establish

ath
connection b/w JavaProgram and DB product.

ip
2.Servlet:
Ma
=>Servlet means 'Server program' and which

accept the request from User/Client and gives

the response.
sh

3.JSP:
ate

=>JSP stands for 'Java Server Page' and which

is response from WebApplication.


nk
Ve
ii
ath
ip
==========================================
Ma
1.JDBC:(Unit-1)
sh
Types of Storages:
ate

=>According to application development the

Storages are categorized into four types:


nk

(a)Field Storage

(b)Object Storage
Ve

(c)File Storage

(d)DataBase Storage

(a)Field Storage:

=>The memory generated to hold single data


value is known as Field Storage.

=>The primitive data types will generate

field Storage.

*imp

(b)Object Storage:

ii
=>The memory generated to hold group members

ath
is known as Object Storage.

ip
class Addition

int a,b,c;
Ma
void add()
sh
{

c = a+b;
ate

Sop(c);

}
nk

}
Ve

Addition ob = new Addition();


ii
ath
Dt : 28/4/2022(Day-2)

ip
faq:

wt is the diff b/w


Ma
(i)Object

(ii)Object reference
sh
(iii)Object reference Variable
ate

(i)Object:

=>The memory generated to hold NonStatic members of class


nk

is known as Object.
Ve

(ii)Object reference:

=>The address location where the object is created is known

as Object reference.

(iii)Object reference Variable:


=>The variable which is holding the object reference is

known as 'Object reference Variable'.

--------------------------------------------------

Summary:

=>Variable in Java are categorized into two types:

(i)Primitive DataType variable

ii
(ii)NonPrimitive DataType Variable

ath
(Reference DataType Variable)

=>Primitive DataType variables will hold values and

ip
NonPrimitive DataType variables will hold Object references.
Ma
=========================================================

Note:

=>The field Storages and the Object Storages which are


sh
generated part of JVM while application execution will be

destroyed automatically when the JVM ShutDowns.


ate

=>when we want to have permanent storages for applications

then we must take the support of any one of the following:


nk

=>File Storage

=>DataBase Storage
Ve
ii
ip ath
Ma
============================================================

faq:
sh
define API?

=>API stands for 'Application Programming Interface' and which


ate

is collection of related 'classes and Interfaces' used in

constructing applications to interact with resources.


nk

(According to Java API means package)

=>The following are some important packages available from


Ve

JavaLib:

CoreJava:

(i)java.lang - Language package

(ii)java.io - Streams and Files package


(iii)java.util - Utility package

(iv)java.net - Networking package

AdvJava:

(i)java.sql - DataBase Connection package

(ii)javax.servlet - Servlet Programming

ii
(iii)javax.servlet.jsp - JSP parogramming

ath
============================================================

*imp

ip
(c)File Storage:
Ma
=>The smallest permanent storage of computer System,which is

controlled and managed by the OperatingSystem is known as

File Storage.
sh
Note:

=>In the process of establishing communication b/w JavaProgram


ate

and File Storage,the JavaProgram must be constructed using the

classes and Interfaces available from java.io package.


nk

Diagram:
Ve
ii
ip ath
faq: Ma
define output stream?

=>The Java program writing the data to file storage is known as

output stream.
sh
ate

faq:

define input stream?

=>The Java program reading the data from the file storage is
nk

known as input stream.


Ve

----------------------------------------------------------

Dt : 29/4/2022

faq:

define Stream?

=>The contineous flow of data is known as Stream.


Types of Streams:

=>Streams in Java are categorized into two types:

1.Byte Stream

2.Character Stream

1.Byte Stream:

ii
=>The contineous flow of data in the form of 8-bits is known as

ath
ByteStream or Binary Stream.

ip
2.Character Stream:
Ma
=>The contineous flow of data in the form of 16-bits is known as

Character Stream or text Stream.


sh
Note:

=>Through Byte Stream we can send multimedia data files like


ate

Audio,Video,Image and Animation.

=>Through Binary Stream we can send text data or Character Stream.


nk

===========================================================

Dis-Advantages of File Storage:


Ve

1.Data Redundancy

2.Data Inconsistency

3.Difficuilty in Accessing Data

4.Limite data Sharing

5.Integrity Problems
6.Atomicity Problems

7.Concurrent Access Anomalies

8.Security problems

===================================================================

Note:

=>Because of these Dis-Advantages we take the support of DataBase

ii
for JavaApplications.

ath
===============================================================

*imp

ip
(d)DataBase Storage:
Ma
=>The largest Permanent Storage which is installed from

externally into ComputerSystem is known as DataBase Storage.

Note:
sh
=>In the process of establishing communication b/w JavaProgram

and DataBase product,the JavaProgram must be constructed using


ate

'classes and interfaces' available from 'java.sql' package and

the Program must use 'JDBC driver'.


nk

Diagram:
Ve
ii
ip ath
=======================================================
Ma
define "driver"?

=>The small s/w program part of Operatingsystem which is used to

control the resources of ComputerSystem is known as 'driver'.


sh
Ex:
ate

Audio driver

Video driver
nk

N/W driver

...
Ve

define JDBC driver?

=>The driver which is used to communicate with DataBase product

is known as JDBC driver(Java DataBase Connectivity Driver).


Types of JDBC drivers:

=>JDBC drivers are categorized into four types:

1.JDBC-ODBC bridge driver(Type-1)

2.Native API driver(Type-2)

3.Network Protocol driver(Type-3)

ii
4.Thin driver(Type-4)

ath
Note:

ip
=>In realtime we use 'Thin driver' for application development.
Ma
==================================================================

Dt : 30/4/2022

*imp
sh
Making System Environment ready to construct JDBC Application:
ate

step-1 : Download and Install Oracle DataBase

step-2 : Check the Login process with Oracle DataBase


nk

step-3 : Create table with name Product45


Ve

create table Product45(pcode varchar2(10),pname varchar2(15),

pprice number(10,2),pqty number(10),primary key(pcode));

step-4 : Insert records to DBTable Product45.


insert into Product45 values('A111','Mouse',1200,12);

SQL> select * from Product45;

PCODE PNAME PPRICE PQTY

ii
---------- --------------- ---------- ----------

ath
A111 Mouse 1200 12

A222 KBB 1100 10

ip
A105 CDR 1300 13

A104

A100
FDD

CDR
700

1200
3

45
Ma
sh
SQL>
ate

step-5 : Find DB-Jar file and copy into one User defined folder.
nk

DB Jar file is availabel at 'lib' folder of Oracle


Ve

C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib

*imp

define DataBase JAR file?

=>JAR stands for 'Java Archieve' and which is compressed format


of class files.

Oracle - ojdbc14.jar,ojdbc6.jar, ojdbc7.jar, ojdbc8.jar,

ojdbc10.jar

ii
Oracle10 - ojdbc14.jar

ath
Oracle11 - ojdbc6.jar

oracle12 - ojdbc7.jar,ojdbc8.jar

ip
other - ojdbc10.jar

MySQL
Ma
- mysql-connector-java-VERSION.jar

SQL Server - sqljdbc41.jar, sqljdbc42.jar


sh
PostgreSQL - postgresql-VERSION.jar

Apache Derby - derby.jar, derbyclient.jar


ate

SQLite - sqlite-jdbc-VERSION.jar

Microsoft Access - ucanaccess-VERSION.jar


nk

step-6 : Find Oracle DataBase PortNo and ServiceName


Ve

=>Open 'tnsnames.ora' file from "ADMIN" folder of "NETWORK" to

find PortNo and ServiceName

C:\oraclexe\app\oracle\product\11.2.0\server\network\ADMIN
PortNo : 1521

ServiceName : XE

=====================================================

*imp

JDBC API:

=>'java.sql' package is JDBC API and which provide the 'classes

ii
and Interfaces' used in JDBC application development.

ath
=>'java.sql.Connection' interface is the root of JDBC API.

=>The following are some important methods of 'Connection'

ip
interface:

1.createStatement()
Ma
- this method will create implementation object Statement

interface.
sh
2.prepareStatement()

3.prepareCall()
ate

4.setAutoCommit()

5.getAutoCommit()
nk

6.setSavepoint()

7.removeSavepoint()
Ve

8.commit()

9.rollback()

10.close() - this method will disconnect DBProduct from

JavaProgram.
Hierarchy of 'Connection' interface:

ii
ath
===========================================================

ip
Dt : 2/5/2022

Note:
Ma
=>we use getConnection() method from 'java.sql.DriverManager' class

to create the implementation object of 'Connection' interface.


sh
Method Signature of getConnection():
ate

public static java.sql.Connection getConnection

(java.lang.String, java.lang.String, java.lang.String)


nk

throws java.sql.SQLException;
Ve

syntax:

Connection con = DriverManager.getConnection

("DB-url","uname","pword");

DB-URL => jdbc:oracle:thin:@localhost:1521:xe


uname => system

pword => manager

Diagram:

ii
ip ath
Ma
sh
ate
nk
Ve

==========================================================

*imp

Types of JDBC-statements:
=>JDBC statements are used to perform operations on DataBase

product.

=>These JDBC statements are categorized into three types:

1.Statement

2.PreparedStatement

3.CallableStatement

ii
ath
1.Statement:

=>'Statement' is an interface from java.sql package and which is

ip
used to execute normal queries without IN parameters.
Ma
=>The fllowing are some important methods from 'Statement'

interface:

(i)executeQuery()
sh
(ii)executeUpdate()
ate

(i)executeQuery():

=>executeQuery() method is used to execute 'select' queries.


nk

Method Signature:

public abstract java.sql.ResultSet executeQuery(java.lang.String)


Ve

throws java.sql.SQLException;

(ii)executeUpdate():

=>executeUpdate() method is used to execute Non-select queries.

(Create,Insert,Update and Delete)


Method Signature:

public abstract int executeUpdate(java.lang.String)

throws java.sql.SQLException;

---------------------------------------------------------

Note:

=>we use createStatement() method from 'Connection' interface to

ii
create the implementation object of 'Statement' interface.

ath
Method Signature of createStatement():

public abstract java.sql.Statement createStatement()

ip
throws java.sql.SQLException;

syntax:
Ma
Statement stm = con.createStatement();
sh
--------------------------------------------------------------

*imp
ate

Creating JDBC Application using IDE Eclipse:

step-1 : open IDE Eclipse,while opening name the WorkSpace and click
nk

'Launch'

step-2 : Create Java Project


Ve

Click on File->new->Project->Java->select 'Java Project' and click

'next'->name the project and click 'finish'

step-3 : Add DB-Jar file to JavaProject using 'Built path'

RightClick on JavaProject->Build path->Configure Build path->


Libraries->select 'classpath' and click 'Add external Jars'->

browse and select DB-Jar file->Open->Apply->Apply and Close.

step-4 : Create package in 'src'

RightClick on 'src'->new->package,name the package and click 'finish'.

ii
step-5 : Create class in Package and type the code

ath
RightClick on package->new->Class,name the class and click 'finish'

Program No :: 01

ip
package test;

import java.sql.*;

public class DBCon1 {


Ma
public static void main(String[] args) {
sh
try {

Connection con = DriverManager.getConnection


ate

("jdbc:oracle:thin:@localhost:1521:xe","system","manager");

Statement stm = con.createStatement();


nk

ResultSet rs = stm.executeQuery("select * from Product45");

while(rs.next()) {
Ve

System.out.println(rs.getString(1)+"\t"

+rs.getString(2)+"\t"

+rs.getFloat(3)+"\t"

+rs.getInt(4));

}//end of loop
con.close();

}catch(Exception e) {e.printStackTrace();}

ii
ath
step-6 : Execute the program

====================================================

ip
Dt : 4/5/2022

faq:

define ResultSet?
Ma
=>ResultSet is an interface from java.sql package and which hold result
sh
of select query.

=>we use executeQuery() method method to create the implementation object


ate

of 'ResultSet' interface.

=>This executeQuery() method will execute the query on DataBase product,


nk

create implementation object of ResultSet and the ResultSet object is

loaded with result of selcet query.


Ve

=>This executeQuery() method also generate cursor pointing before the

first row.

=>we use next() method to move the cursor row-by-row and which is boolean

return type.

record available means true


record Not-available means false.

Diagram:

ii
ip ath
Ma
================================================================

Ex_Application-2: ( Program No :: 02 )
sh
write JDBC application to read Product details from Console and insert into

DB Table product45.
ate

package test;
import java.sql.*;
import java.util.*;
public class DBCon2 {
nk

public static void main(String[] args) {


try {
Scanner s = new Scanner(System.in);
System.out.println("Enter the ProdCode:");
Ve

String pCode = s.nextLine();


System.out.println("Enter the ProdName:");
String pName = s.nextLine();
System.out.println("Enter the ProdPrice:");
float pPrice = s.nextFloat();
System.out.println("Enter the ProdQty:");
int pQty = s.nextInt();
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
Statement stm = con.createStatement();
int k = stm.executeUpdate
("insert into Product45 values('"+pCode+"','"+pName
+"',"+pPrice+","+pQty+")");
if(k>0) {
System.out.println
("Product Details inserted Successfully");
}
con.close();
s.close();
}catch(Exception e) {e.printStackTrace();}
}

ii
}

ip ath
==============================================================

Assignment-1:
Ma
DB Table : Book45(bcode,bname,bauthor,bprice,bqty)
sh
Prog-1 : JDBC Application to read book details from Cosole and insert into

DB table Book45 (Program No :: 03)


ate

Prog-2 : JDBC Application to display all book details (Program No :: 04)

Prog-3 : JDBC Application to display book details based on book code. ( Program No :: 05 )
nk

==============================================================

Assignment-2:
Ve

DB Table : Employee45(eid,ename,edesg,bsal,totsal)

Prog-1 : JDBC Application to read employee details from Cosole and insert into

DB table Employee45 ( Program No :: 06 )

Note:
Calculate totSal based on bSal using the following formula:

totSal = bSal+HRA+DA;

HRA = 93% of bSal

DA = 63% of bSal

ii
Prog-2 : JDBC Application to display all Employee details ( Program No :: 07 )

ath
Prog-3 : JDBC Application to display Employee details based on eId.
( Program No :: 08 )
=====================================================================

ip
Ma
sh
ate
nk
Ve
Dt : 5/5/2022

Ex_Application :

JDBC application to display the details of Product based on prodCode.

Program : DBCon3.java

package test;

ii
import java.sql.*;

ath
import java.util.*;;

public class DBCon3 {

ip
public static void main(String[] args) {

try {

Scanner s = new Scanner(System.in);


Ma
System.out.println("Enter the ProdCode:");
sh
String pCode = s.nextLine();

Connection con = DriverManager.getConnection


ate

("jdbc:oracle:thin:@localhost:1521:xe","system","manager");

Statement stm = con.createStatement();


nk

ResultSet rs = stm.executeQuery

("select * from Product45 where pcode='"+pCode+"'");


Ve

if(rs.next()) {

System.out.println(rs.getString(1)+"\t"+

rs.getString(2)+"\t"+rs.getFloat(3)+

"\t"+rs.getInt(4));

}else {
System.out.println("Invalid ProdCode...");

con.close();

s.close();

}catch(Exception e) {e.printStackTrace();}

ii
}

ath
o/p:

Enter the ProdCode:

ip
A222

A222 KB 1300.0 13
Ma
================================================================

*imp
sh
2.PreparedStatement:

=>PreparedStatement is an interface from java.sql package and which is used


ate

to execute normal queries with IN parameters.

=>The following are some important methods of PreparedStatement:


nk

(i)executeQuery()

(ii)executeUpdate()
Ve

(i)executeQuery():

=>executeQuery() method is used to execute select queries.

Method Signature:

public abstract java.sql.ResultSet executeQuery() throws java.sql.SQLException;


(ii)executeUpdate():

=>executeUpdate() method is used to execute Non-Select queries.

Method Signature:

public abstract int executeUpdate() throws java.sql.SQLException;

----------------------------------------------------------------

ii
=>we use prepareStatement() method from 'Connection' interface to create the

ath
implementation object of 'PreparedStatement' interface.

Method Signature of prepareStatement():

ip
public abstract java.sql.PreparedStatement prepareStatement(java.sql.String)

syntax:
Ma
throws java.sql.SQLException;

PreparedStatement ps = con.prepareStatement("query-structure");
sh
========================================================================

Prog-1 : JDBC Application to read employee details from Console and insert into
ate

DB table Employee45 using PreparedStatement

Note:
nk

Calculate totSal based on bSal using the following formula:


Ve

totSal = bSal+HRA+DA;

HRA = 93% of bSal

DA = 63% of bSal

DB Table : Employee45(eid,ename,edesg,bsal,totsal)
create table Employee45(eid varchar2(10),ename varchar2(15),edesg varchar2(10),

bsal number(10),totsal number(10,2),primary key(eid));

Program : DBCon4.java

package test;

ii
import java.util.*;

ath
import java.sql.*;

public class DBCon4 {

ip
public static void main(String[] args) {

try {
Ma
Scanner s = new Scanner(System.in);

System.out.println("Enter the EmpId:");


sh
String eId = s.nextLine();

System.out.println("Enter the EmpName:");


ate

String eName = s.nextLine();

System.out.println("Enter the EmpDesg:");


nk

String eDesg = s.nextLine();

System.out.println("Enter the BSal");


Ve

int bSal = s.nextInt();

float totSal = bSal+(0.93F*bSal)+(0.63F*bSal);

Connection con = DriverManager.getConnection

("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
PreparedStatement ps = con.prepareStatement

("insert into Employee45 values(?,?,?,?,?)");//Compilation

ps.setString(1,eId);

ps.setString(2,eName);

ps.setString(3,eDesg);

ii
ps.setInt(4, bSal);

ath
ps.setFloat(5, totSal);

ip
int k = ps.executeUpdate();//Execution process

if(k>0) {
Ma
System.out.println("Employee Details inserted Successfully...");
sh
}

con.close();
ate

s.close();

}catch(Exception e) {e.printStackTrace();}
nk

}
Ve

o/p:

Enter the EmpId:

A121

Enter the EmpName:

Raj
Enter the EmpDesg:

SE

Enter the BSal

12000

Employee Details inserted Successfully...

ii
ip ath
Ma
============================================================

faq:

wt is the execution behaviour of prepareStatement() method?


sh
=>prepareStatement() method will compile the query Structure.
ate

=>If the compilation is successfully then prepareStatement() method will

create fields equal to the parameter indexes.


nk

Note:
Ve

=>we use setter methods to set the data to the fields based on parameter index

and then executed.

==============================================================

faq:

wt is the advantage of PreparedStatement?

=>In PreparedStatement the query is compiled once and can be executed any
number of times by setting the values.

================================================================

Assignment:

DB Table : UserReg45(uname,pword,fname,lname,addr,mid,phno)

Primary Key : uname and pword

ii
Construct JDBC Application to perform the following operations based on User

ath
Choice:(Using PreparedStatement)

1.Register

ip
2.Login

1.Register:
Ma
=>read user details from console and insert in to DBtable UserReg45.
sh

2.Login:
ate

=>read uname and pword from the console and display the following msg:

Login Successfull...
nk

Welcome User : fName

===========================================================================
Ve
Dt : 7/5/2022

DB Table : UserReg45

create table UserReg45(uname varchar2(15),pword varchar2(15),

fname varchar2(15),lname varchar2(15),addr varchar2(15),

mid varchar2(25),phno number(15),primary key(uname,pword));

ii
( Program No :: 09 )

ath
Program : DBCon5.java

package test;

ip
import java.sql.Connection;

import java.sql.*;

import java.util.*;
Ma
public class DBCon5 {
sh
public static void main(String[] args) {

try {
ate

Scanner s = new Scanner(System.in);

Connection con = DriverManager.getConnection


nk

("jdbc:oracle:thin:@localhost:1521:xe","system","manager");

PreparedStatement ps1 = con.prepareStatement


Ve

("insert into UserReg45 values(?,?,?,?,?,?,?)");

PreparedStatement ps2 = con.prepareStatement

("select * from UserReg45 where uname=? and pword=?");

while(true) {

System.out.println("====Choice====");
System.out.println("1.Register\n2.Login\n3.exit");

System.out.println("Enter the Choice:");

int choice = Integer.parseInt(s.nextLine());

switch(choice)

case 1:

ii
System.out.println("Enter the UserName:");

ath
String uName = s.nextLine();

System.out.println("Enter the PassWord:");

ip
String pWord = s.nextLine();
Ma
System.out.println("Enter the FirstName:");

String fName = s.nextLine();

System.out.println("Enter the LastName:");


sh
String lName = s.nextLine();

System.out.println("Enter the Address:");


ate

String addr = s.nextLine();

System.out.println("Enter the MailId:");


nk

String mId = s.nextLine();

System.out.println("Enter the PhoneNo:");


Ve

long phNo = Long.parseLong(s.nextLine());

ps1.setString(1,uName);

ps1.setString(2,pWord);

ps1.setString(3,fName);
ps1.setString(4,lName);

ps1.setString(5,addr);

ps1.setString(6,mId);

ps1.setLong(7,phNo);

int k = ps1.executeUpdate();

ii
if(k>0) {

ath
System.out.println("User Registered Successfully");

ip
break;

case 2:
Ma
System.out.println("Enter the UserName:");

String uN = s.nextLine();
sh
System.out.println("Enter the PassWord:");

String pW = s.nextLine();
ate

ps2.setString(1,uN);
nk

ps2.setString(2, pW);
Ve

ResultSet rs = ps2.executeQuery();

if(rs.next()) {

System.out.println("Login Successfull...");

System.out.println("Welcome User : "+rs.getString(3));

}else {
System.out.println("Invalid Login Process...");

break;

case 3:

System.out.println("Program terminated...");

System.exit(0);

ii
default:

ath
System.out.println("Invalid Choice...");

}//end of switch;

ip
}//end of loop

//s.close();

}catch(Exception e) {e.printStackTrace();}
Ma
}
sh
}

============================================================
ate

Ex_Application:

JDBC Application to update Product Price and qty based on pCode?


nk

Program : DBCon6.java
Ve

package test;

import java.sql.*;

import java.util.*;

public class DBCon6 {

public static void main(String[] args) {


try {

Scanner s = new Scanner(System.in);

System.out.println("Enter the ProdCode:");

String pCode = s.nextLine();

Connection con = DriverManager.getConnection

("jdbc:oracle:thin:@localhost:1521:xe","system","manager");

ii
PreparedStatement ps1 = con.prepareStatement

ath
("select * from Product45 where pcode=?");

PreparedStatement ps2 = con.prepareStatement

ip
("update Product45 set pprice=?,pqty=pqty+? where pcode=?");

ps1.setString(1,pCode);
Ma
ResultSet rs = ps1.executeQuery();
sh
if(rs.next()) {

System.out.println("Old price:"+rs.getFloat(3));
ate

System.out.println("Enter the New Price:");

float newPrice = s.nextFloat();


nk

System.out.println("Available qty:"+rs.getInt(4));

System.out.println("Enter the new qty:");


Ve

int newQty = s.nextInt();

ps2.setFloat(1,newPrice);

ps2.setInt(2,newQty);

ps2.setString(3, pCode);
int k = ps2.executeUpdate();

if(k>0) {

System.out.println("Product details updated...");

}else {

System.out.println("Invalid ProdCode...");

ii
}

ath
s.close();

}catch(Exception e) {e.printStackTrace();}

ip
}

}
Ma
===========================================================

Ex_Application:
sh
JDBC Application to delete Product on pCode?
ate

Program : DBCon7.java

package test;
nk

import java.sql.*;

import java.util.*;
Ve

public class DBCon7 {

public static void main(String[] args) {

try {

Scanner s = new Scanner(System.in);

System.out.println("Enter the ProdCode:");


String pCode = s.nextLine();

Connection con = DriverManager.getConnection

("jdbc:oracle:thin:@localhost:1521:xe","system","manager");

PreparedStatement ps1 = con.prepareStatement

("select * from Product45 where pcode=?");

PreparedStatement ps2 = con.prepareStatement

ii
("delete from Product45 where pcode=?");

ath
ps1.setString(1,pCode);

ip
ResultSet rs = ps1.executeQuery();

if(rs.next()) {

ps2.setString(1,pCode);
Ma
int k = ps2.executeUpdate();
sh
if(k>0) {

System.out.println("Product details deleted...");


ate

}else {
nk

System.out.println("Invalid ProdCode...");

}
Ve

s.close();

}catch(Exception e) {e.printStackTrace();}

=========================================================
Assignment: ( Program No :: 10 )

JDBC application to perform the following operations on Book45 based

on user choice:(Choice is repeated until user terminates)

1.AddBook

2.ViewAllBooks

3.ViewBookByBookCode

ii
4.UpdateBookByBookCode(price and qty)

ath
5.DeleteBookByBookCode

ip
Dt : 9/5/2020

*imp

3.CallableStatement:
Ma
=>CallableStatement is an interface from java.sql package and
sh
which is used to execute Procedures and Functions on DB-Product.

=>we use prepareCall() method from 'Connection' interface to


ate

create the implementation object of CallableStatement interface.

Method Signature of prepareCall():


nk

public abstract java.sql.CallableStatement prepareCall

(java.lang.String)throws java.sql.SQLException;
Ve

syntax

CallableStatement cs = con.prepareCall("Proc/Func");

define Procedure?

=>procedure is a set-of-queries executed on DataBase product


and after execution it will not return any value.

(Procedure means Non-return_type)

structure of procedure:

create or replace procedure Proc_name

ii
(para_list) is

ath
begin

query1;

ip
query2;

end;
...
Ma
/
sh

define Function?
ate

=>Function is a set-of-queries executed on DataBase product and

after execution it will return the value.


nk

Note:

=>Functions in SQL will use 'return' statement to return the


Ve

value after execution.

structure of Function:

create or replace function Func_name


(para_list)return data_type as var data_type;

begin

query1;

query2;

....

return var;

ii
end;

ath
/

========================================================================

ip
*imp

Create and execute Procedure on DB-Product:


Ma
step-1 : Create the following DB-tables using SQL-CommandLine
sh

Bank45(accno,custname,balance,acctype)
ate

CustDetails45(accno,addr,mid,phno)
nk

create table Bank45(accno number(15),custname varchar2(15),

balance number(10,2),acctype varchar2(15),primary key(accno));


Ve

create table CustDetails45(accno number(15),addr varchar2(15),

mid varchar2(25),phno number(15),primary key(accno));

step-2 : Construct the Procedure to createAccount


create or replace procedure CreateAccount45

(accno number,custN varchar2,bal number,accT varchar2,

addr varchar2,mid varchar2,phno number) is

begin

insert into Bank45 values(accno,custN,bal,accT);

ii
insert into CustDetails45 values(accno,addr,mid,phno);

ath
end;

ip
Ma
step-3 : construct JDBC application to execute procedure

( Program NO :: 11 )

Program : DBCon8.java
sh
package test;

import java.util.*;
ate

import java.sql.*;

public class DBCon8 {


nk

public static void main(String[] args) {

try {
Ve

Scanner s = new Scanner(System.in);

System.out.println("Enter the accNo:");

long accNo = Long.parseLong(s.nextLine());

System.out.println("Enter the CustName:");

String custName = s.nextLine();


System.out.println("Enter the Balance:");

float bal = Float.parseFloat(s.nextLine());

System.out.println("Enter the AccType:");

String accType = s.nextLine();

System.out.println("Enter the Address:");

String addr = s.nextLine();

ii
System.out.println("Enter the MailId:");

ath
String mId = s.nextLine();

System.out.println("Enter the PhoneNo:");

ip
long phNo = s.nextLong();
Ma
Connection con = DriverManager.getConnection

("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
sh
CallableStatement cs = con.prepareCall

("{call CreateAccount45(?,?,?,?,?,?,?)}");
ate

cs.setLong(1,accNo);

cs.setString(2,custName);
nk

cs.setFloat(3,bal);

cs.setString(4,accType);
Ve

cs.setString(5,addr);

cs.setString(6, mId);

cs.setLong(7, phNo);

cs.execute();
System.out.println("Procedure executed Successfully...");

con.close();;

s.close();

}catch(Exception e) {e.printStackTrace();}

ii
}

ath
o/p:

Enter the accNo:

ip
6123456

Enter the CustName:

Raj
Ma
Enter the Balance:
sh
12000

Enter the AccType:


ate

savings

Enter the Address:


nk

SrNagar

Enter the MailId:


Ve

[email protected]

Enter the PhoneNo:

7878781234

Procedure executed Successfully...

---------------------------------------------------------
Diagram:

ii
ath
=========================================================

Assignment:

ip
Create and execute procedure
Ma
Step-1 : Construct DB Tables
sh
EmpData45(eid,ename,edesg)
ate

EmpAddress45(eid,hno,sname,city,pincode)

EmpContact45(eid,mid,phno)

EmpSalary45(eid,bsal,totsal)
nk

step-2 : Jdbc Application to execute procedure to update EmpDetails


Ve

=========================================================

Dt : 10/5/2022

Types of Procedures:

=>Procedures are categorized into two types:

(i)IN-Parameter Procedures

(ii)OUT-Parameter Procedures
(i)IN-Parameter Procedures:

=>The procedures which take the data from JavaProgram and update

DB-Tables are known as IN-Parameter procedures.

Ex:

above program(DBCon8.java)

ii
ath
(ii)OUT-Parameter Procedures:

=>The procedures which take the data from DB-Tables and sent to

ip
JavaProgram are known as OUT-Parameter Procedures.

Ex:
Ma
Construct Procedure to display the Complete details of
sh
Customer based on accno.
ate

step-1 : Construct procedure to retrieve Complete details based on

accno.
nk

create or replace procedure RetrieveDetails45


Ve

(ano number,cname OUT varchar2,bal OUT number,atype OUT varchar2,

adr OUT varchar2,md OUT varchar2,pno OUT number) is

begin

select custname,balance,acctype into cname,bal,atype from Bank45 where accno=ano;

select addr,mid,phno into adr,md,pno from CustDetails45 where accno=ano;


end;

step-2 : JDBC application to execute procedure.

( Program No :: 12 )

Program : DBCon9.java

ii
package test;

ath
import java.util.*;

import java.sql.*;

ip
public class DBCon9 {
Ma
public static void main(String[] args) {

try {

Scanner s = new Scanner(System.in);


sh
System.out.println("Enter the AccNo:");

long accNo = s.nextLong();


ate

Connection con = DriverManager.getConnection

("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
nk

CallableStatement cs = con.prepareCall

("{call RetrieveDetails45(?,?,?,?,?,?,?)}");
Ve

cs.setLong(1, accNo);

cs.registerOutParameter(2,Types.VARCHAR);

cs.registerOutParameter(3,Types.FLOAT);

cs.registerOutParameter(4,Types.VARCHAR);

cs.registerOutParameter(5,Types.VARCHAR);
cs.registerOutParameter(6,Types.VARCHAR);

cs.registerOutParameter(7,Types.BIGINT);

cs.execute();

System.out.println("AccNo:"+accNo);

System.out.println("CustName:"+cs.getString(2));

System.out.println("Balance:"+cs.getFloat(3));

ii
System.out.println("AccType:"+cs.getString(4));

ath
System.out.println("Address:"+cs.getString(5));

System.out.println("MailId:"+cs.getString(6));

ip
System.out.println("PhoneNO:"+cs.getLong(7));;

s.close();
Ma
}catch(Exception e) {e.printStackTrace();}

}
sh

}
ate

o/p:

Enter the AccNo:


nk

6123456

AccNo:6123456
Ve

CustName:Raj

Balance:12000.0

AccType:savings

Address:SrNagar

MailId:[email protected]
PhoneNO:7878781234

-----------------------------------------------------------

faq:

define registerOutParameter() method?

=>This registerOutParameter() method specify the type of value

to be recorded to the fields of CallableStatement object in

ii
OUT-Parameter procedure.

ath
------------------------------------------------------------

faq:

ip
wt is the advantage of Procedures?
Ma
=>Using Procedures we can execute multiple queries at-a-time and

which saves the execution time and generate HighPerformance of an

application.
sh
-----------------------------------------------------------

Assignment:
ate

Construct Procedure to display the complete details of Employee

based on eId.
nk

=================================================================

*imp
Ve

Create and execute Functon:

step-1 : Construct function to retrieve balance based on accno.

create or replace function RetrieveBalance45


(ano number)return number as bal number;

begin

select balance into bal from Bank45 where accno=ano;

return bal;

end;

ii
ath
step-2 : JDBC Application to execute function

( Program No :: 13 )

ip
Program : DBCon10.java

package test;

import java.util.*;
Ma
import java.sql.*;
sh
public class DBCon10 {

public static void main(String[] args) {


ate

try {

Scanner s = new Scanner(System.in);


nk

System.out.println("Enter the AccNo:");

long accNo = s.nextLong();


Ve

Connection con = DriverManager.getConnection

("jdbc:oracle:thin:@localhost:1521:xe","system","manager");

CallableStatement cs = con.prepareCall

("{call ? := RetrieveBalance45(?)}");

cs.registerOutParameter(1,Types.FLOAT);
cs.setLong(2,accNo);

cs.execute();

System.out.println("AccNo:"+accNo);

System.out.println("Balance:"+cs.getFloat(1));

con.close();

s.close();

ii
}catch(Exception e) {e.printStackTrace();}

ath
}

ip
o/p:

Enter the AccNo:

6123456
Ma
AccNo:6123456
sh
Balance:12000.0

=========================================================
ate

Assignment:

Construct Function to display totSal of an employee based on eId.


nk

=========================================================
Ve

=========================================================
Dt : 12/5/2022

Connection Pooling in JDBC:

=>The process of organizing multiple pre-initialized DataBase

Connections among multiple users is known as 'Connection pooling

process'.

ii
Behaviour:

ath
(i)User picks the DataBase connection from the Pool.

(ii)User uses the connection to perform operations on DataBase

ip
(iii)After usage returns the Connection back to the pool.

Note:
Ma
=>we take the support of Vector<E> to construct Connection
sh
Pooling Process.

=>This Vector<E> organizes elements in Sequence.


ate

=>Vector<E> is synchronized class and Thread-Safe class.


nk

Hierarchy of Vector<E>:
Ve
ii
ath
-------------------------------------------------------

ip
Ex_program: ( Program No :: 14 )

ConnectionPool.java
Ma
package test;

import java.sql.*;
sh
import java.util.*;
ate

public class ConnectionPool {

public String url,uname,pword;

public ConnectionPool(String url,String uname,String pword) {


nk

this.url=url;
Ve

this.uname=uname;

this.pword=pword;

public Vector<Connection> v = new Vector<Connection>();

public void createConnections()

{
try {

while(v.size()<5)

System.out.println("Connection pool is Not-Full...");

Connection con=DriverManager.getConnection

(url,uname,pword);

ii
v.add(con);//Adding the connection to Pool

ath
System.out.println(con);

}//end of loop

ip
if(v.size()==5)

{
Ma
System.out.println("Connection Pool is full...");

}
sh
}catch(Exception e) {e.printStackTrace();}

}//end of method
ate

public synchronized Connection useConnection()

{
nk

Connection con = v.firstElement();//First Connection is taken

v.remove(0);//one Connection at index 0 is deleted


Ve

return con;

}//end of method

public synchronized void returnConnection(Connection con)

v.addElement(con);//Adding Connection back to pool


System.out.println("Connection returned back to the pool...");;

DBCon12.java

ii
package test;

ath
import java.util.*;
import java.sql.*;
public class DBCon12 {
public static void main(String[] args) {
ConnectionPool cp = new ConnectionPool

ip
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
Ma
cp.createConnections();
System.out.println("Pool Size:"+cp.v.size());
Connection con = cp.useConnection();
System.out.println("User using : "+con);
System.out.println("Pool Size:"+cp.v.size());
cp.returnConnection(con);
sh
System.out.println("Pool Size:"+cp.v.size());
System.out.println("====Display the Connection from
Pool====");
ate

cp.v.forEach((k)->
{
System.out.println(k);
});
nk

}
}
Ve
Ve
nk
ate
sh
Ma
ip ath
ii
Dt : 13/5/2022

*imp

Batch Processing in JDBC:

=>The process of collecting multiple queries as batch and executing

at-a-time is known as Batch Processing.

=>The following are the methods used in Batch Processing:

ii
(a)addBatch()

ath
(b)executeBatch()

(c)clearBatch()

ip
(a)addBatch():
Ma
=>This addBatch() method is used to add query to the batch.

Method Signature:
sh
public abstract void addBatch(java.lang.String)

throws java.sql.SQLException;
ate

(b)executeBatch():
nk

=>This executeBatch() method is used to execute the queries

from the batch at-a-time.


Ve

Method Signature:

public abstract int[] executeBatch() throws java.sql.SQLException;

(c)clearBatch():

=>This clearBatch() method is used to clear all the queries from


the batch and deletes the batch.

Method Signature:

public abstract void clearBatch()throws java.sql.SQLException;

-----------------------------------------------------

Program-1 : Batch Processing using 'Statement'

DBCon13.java ( Program No :: 15 >>JDBC_APP15)

ii
package test;

ath
import java.sql.*;
public class DBCon13 {
public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection

ip
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
Statement stm = con.createStatement(); Ma
stm.addBatch
("insert into Product45 values('B123','ER',123,12)");
stm.addBatch
("insert into Bank45
values(456,'Alex',234,'savings')");
sh
stm.addBatch
("insert into CustDetails45
values(456,'SRN','a@..',7878)");
ate

int k[] = stm.executeBatch();


for(int i=0;i<k.length;i++)
{
nk

System.out.println("Data updated...");
}//end of loop
stm.clearBatch();
con.close();
Ve

}catch(Exception e) {e.printStackTrace();}
}
}

Note:

=>Batch Processing using 'Statement' we can update multiple

DataBase tables at-a-time


========================================================

Program-2 : Batch Processing using 'PreparedStatement'

DBCon14.java

package test;
import java.sql.*;
public class DBCon14 {
public static void main(String[] args) {

ii
try {

ath
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
PreparedStatement ps = con.prepareStatement
("insert into Product45 values(?,?,?,?)");

ip
ps.setString(1,"C111");
ps.setString(2,"TRY"); Ma
ps.setFloat(3,234);
ps.setInt(4,12);
ps.addBatch();

ps.setString(1,"C222");
ps.setString(2,"Catch");
sh
ps.setFloat(3,244);
ps.setInt(4,11);
ps.addBatch();
ate

int k[] = ps.executeBatch();


for(int i=0;i<k.length;i++)
{
nk

System.out.println("Data Updated...");
}
ps.clearBatch();
con.close();
Ve

}catch(Exception e) {e.printStackTrace();}
}
}

Note:

=>Batch processing using 'PreparedStatement' we can update

multiple records into same DataBase table.


========================================================

faq:

wt is the Advantage of Batch processing?

=>In Batch processing the execution control is transferred to

DataBase only once and executes all the queries from the batch

at-a-time,in this process the execution time is saved and generate

ii
HighPerformance of an application.

ath
==========================================================

faq:

ip
wt is the diff b/w

(i)Batch Processing

(ii)Procedures
Ma
=>using Batch Processing we can execute only Non-Select queries
sh
on DataBase product,which means it is Batch Update processing.

=>Using Procedures we can execute both select and Non-select queries


ate

===========================================================

*imp
nk

Types of ResultSet objects:

=>Based on control over the cursor,the ResultSet objects are


Ve

categorized into two types:

1.Non-Scrollable ResultSet object

2.Scrollable ResultSet object

1.Non-Scrollable ResultSet object:


=>In Non-Scrollable ResultSet Objects the cursor is moved only in

one direction,which means the cursor moves from top-of-the-table-data to

Bottom-of-table-data.

Ex:

above programs related to ResultSet

ii
ath
*imp

2.Scrollable ResultSet object:

ip
=>In Scrollable ResultSet object the cursor can be moved in two
Ma
directions,which means down the table data and upward the table data.

Syntax for Creating Scrollable ResultSet object:


sh

Statement stm = con.createStatement(type,mode);


ate

PreparedStatement ps = con.prepareStatement("query-S",type,mode);
nk

Type:

public static final int TYPE_FORWARD_ONLY=1003


Ve

public static final int TYPE_SCROLL_INSENSITIVE=1004

public static final int TYPE_SCROLL_SENSITIVE=1005

Mode:

public static final int CONCUR_READ_ONLY=1007


public static final int CONCUR_UPDATABLE=1008

Note:

'type' specifies the direction of the cursor and 'mode' specifies the

action to be performed(read or update).

ii
ath
The following are some Methods used to control cursor on Scrollable

ip
ResultSet object:
Ma
afterLast() =>Moves the cursor after the Last row
sh
beforeFirst() =>Moves the cursor before the First row
ate

previous() =>Moves the Cursor in the BackWard Direction


nk

next() => Moves the cursor in the ForWard Direction


Ve

first() => Moves the cursor to the First row

last() => Moves the cursor to the Last row

absolute(int)=>Moves the cursor to the specified row number


relative(int)=>Moves the cursor from the current position

in forward or backward direction by increment or decrement.

---------------------------------------------------------

Dt : 16/5/2022

Ex_Program:(Demonstrating Scrollable ResultSet object)

ii
ath
Program : DBCon15.java

package test;
import java.sql.*;;

ip
public class DBCon15 {
public static void main(String[] args) { Ma
try {
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
Statement stm = con.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
sh
ResultSet rs = stm.executeQuery("select * from
Product45");
System.out.println("====Display Product in
ate

reverse====");
rs.afterLast();//Cursor pointing after last row
while(rs.previous()) {

System.out.println(rs.getString(1)+"\t"+rs.getString(2)+
nk

"\t"+rs.getFloat(3)+"\t"+rs.getInt(4));
}//end of loop
con.close();;
Ve

}catch(Exception e) {e.printStackTrace();}
}
}

o/p:

====Display Product in reverse====

C222 Catch 244.0 11


C111 TRY 234.0 12

A545 ER 123.0 12

A100 CDR 1200.0 45

A104 FDD 700.0 3

A105 CDR 1300.0 13

A222 KBB 1100.0 10

ii
B123 ER 123.0 12

ath
-------------------------------------------------------

Program : DBCon16.java (JDBC_APP16)

ip
package test;
import java.sql.*;
public class DBCon16 {
public static void main(String[] args) {
try {
Ma
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
PreparedStatement ps = con.prepareStatement
sh
("select * from Product45",
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ate

ResultSet rs = ps.executeQuery();
System.out.println("====Display Product in
reverse====");
rs.afterLast();//Cursor pointing after last row
while(rs.previous()) {
nk

System.out.println(rs.getString(1)+"\t"+rs.getString(2)+
"\t"+rs.getFloat(3)+"\t"+rs.getInt(4));
Ve

}//end of loop
System.out.println("====Display Last row====");
rs.last();//Cursor pointing to last row

System.out.println(rs.getString(1)+"\t"+rs.getString(2)+
"\t"+rs.getFloat(3)+"\t"+rs.getInt(4));
System.out.println("====Display First row====");
rs.first();//Cursor pointing to first row

System.out.println(rs.getString(1)+"\t"+rs.getString(2)+
"\t"+rs.getFloat(3)+"\t"+rs.getInt(4));
System.out.println("====Display row number 4====");
rs.absolute(4);//Cursor pointing to 4th row

System.out.println(rs.getString(1)+"\t"+rs.getString(2)+
"\t"+rs.getFloat(3)+"\t"+rs.getInt(4));
System.out.println("====Display relative(+1)====");
rs.relative(+1);//Cursor moved forward by one row

System.out.println(rs.getString(1)+"\t"+rs.getString(2)+
"\t"+rs.getFloat(3)+"\t"+rs.getInt(4));

ii
con.close();
}catch(Exception e) {e.printStackTrace();}

ath
}
}

ip
o/p:

====Display Product in reverse====


Ma
C222 Catch 244.0 11
sh
C111 TRY 234.0 12

A545 ER 123.0 12
ate

A100 CDR 1200.0 45

A104 FDD 700.0 3


nk

A105 CDR 1300.0 13

A222 KBB 1100.0 10


Ve

B123 ER 123.0 12

====Display Last row====

C222 Catch 244.0 11

====Display First row====

B123 ER 123.0 12
====Display row number 4====

A104 FDD 700.0 3

====Display relative(+1)====

A100 CDR 1200.0 45

=============================================================

*imp

ii
define 'RowSet'?

ath
=>RowSet object will encapsulate the rows generated from ResultSets

or any other data sources.

ip
=>RowSet is an interface from javax.sql package and which is

extended from 'java.sql.ResultSet' interface.


Ma
=>The following are the interfaces extended from RowSet:

(a)JDBCRowSet
sh
(b)CachedRowSet

=>WebRowSet
ate

(i)FilteredRowSet

(ii)JoinRowSet
nk

Hierarchy of RowSet:
Ve

-----------------------------------------------------

faq:

wt is the diff b/w

(i)JdbcRowSet

(ii)CachedRowSet
(i)JdbcRowSet:

=>JdbcRowSet will hold ResultSet and connection to DataBase is

active.

(ii)CachedRowSet:

ii
=>cachedRowSet will hold ResultSet,but connection to DataBase is

ath
Dis-Connected automatically.

--------------------------------------------------------------

ip
Note:
Ma
=>WebRowSet is used to transfer the data from one layer to another

layer in Application architectures.

=>FilteredRowSet will hold the data retrieved based on condition.


sh
=>JoinRowSet will hold the data joined from more than one ResultSet

=========================================================
ate

*imp

define RowSetFactory?
nk

=>RowSetFactory is an interface from 'javax.sql.rowset' package and

which provide the following methods to create the implementations of


Ve

RowSet:

(a)createJdbcRowSet()

(b)createCachedRowSet()

(c)createWebRowSet()

(d)createFilteredRowSet()
(e)createJoinRowSet()

(a)createJdbcRowSet():

=>This method is used to create the implementation object of

'JdbcRowSet'.

Method Signature:

ii
public abstract javax.sql.rowset.JdbcRowSet createJdbcRowSet()

ath
throws java.sql.SQLException;

ip
(b)createCachedRowSet():
Ma
=>This method is used to create the implementation object of

'CachedRowSet'.

Method Signature:
sh
public abstract javax.sql.rowset.CachedRowSet createCachedRowSet()

throws java.sql.SQLException;
ate

(c)createWebRowSet():
nk

=>This method is used to create the implementation object of

'WebRowSet'.
Ve

Method Signature:

public abstract javax.sql.rowset.WebRowSet createWebRowSet()

throws java.sql.SQLException;

(d)createFilteredRowSet():
=>This method is used to create the implementation object of

'FilteredRowSet'.

Method Signature:

public abstract javax.sql.rowset.FilteredRowSet createFilteredRowSet()

throws java.sql.SQLException;

ii
(e)createJoinRowSet():

ath
=>This method is used to create the implementation object of 'JoinRowSet'.

Method Signature:

ip
public abstract javax.sql.rowset.JoinRowSet createJoinRowSet()

throws java.sql.SQLException;
Ma
Note:
sh
=>we use the following methods from 'javax.sql.rowset.RowSetProvider'

class to create the implementation object of 'RowSetFactory'


ate

interface.
nk

public static javax.sql.rowset.RowSetFactory newFactory()

throws java.sql.SQLException;
Ve

public static javax.sql.rowset.RowSetFactory newFactory

(java.lang.String, java.lang.ClassLoader)

throws java.sql.SQLException;

===================================================================
Dt : 17/5/2022 (JDBC APP_17)

Ex_Program : DBCon17.java

package test;

import java.util.*;

import javax.sql.rowset.*;

public class DBCon17 {

ii
public static void main(String[] args) {

ath
try {

Scanner s = new Scanner(System.in);

ip
Class.forName("oracle.jdbc.driver.OracleDriver");
Ma
RowSetFactory rsf = RowSetProvider.newFactory();

//Implemented Object of RowSetFactory

System.out.println("===Choice====");
sh
System.out.println("1.JdbcRowSet\n2.CachedRRowSet");

System.out.println("Enter the Choice:");


ate

int choice = s.nextInt();

switch(choice)
nk

case 1:
Ve

JdbcRowSet jrs = rsf.createJdbcRowSet();

jrs.setUrl("jdbc:oracle:thin:@localhost:1521:xe");

jrs.setUsername("system");

jrs.setPassword("manager");

jrs.setCommand("select * from Product45");


jrs.execute();

while(jrs.next()) {

System.out.println(jrs.getString(1)+"\t"+

jrs.getString(2)+"\t"+jrs.getFloat(3)+"\t"+

jrs.getInt(4));

}//end of loop

ii
break;

ath
case 2:

CachedRowSet crs = rsf.createCachedRowSet();

ip
crs.setUrl("jdbc:oracle:thin:@localhost:1521:xe");

crs.setUsername("system");

crs.setPassword("manager");
Ma
crs.setCommand("select * from Bank45");
sh
crs.execute();

while(crs.next()) {
ate

System.out.println(crs.getLong(1)+"\t"+

crs.getString(2)+"\t"+crs.getFloat(3)+"\t"+
nk

crs.getString(4));

}//end of loop
Ve

break;

default:

System.out.println("Invalid Choice...");

}//end of switch;

s.close();
}catch(Exception e) {e.printStackTrace();}

o/p:

===Choice====

1.JdbcRowSet

ii
2.CachedRRowSet

ath
Enter the Choice:

ip
6123456 Raj 9000.0 savings

313131

56565 Alex
Ram 3500.0 Savings

234.0 savings
Ma
456 Alex 234.0 savings
sh
=============================================================

Summary of Objects generated from CoreJava:


ate

1.User defined Class Object

2.String Objects
nk

3.WrapperClass Objects

4.Array objects
Ve

5.Collection<E> objects

6.Map<K,V> objects

7.Enum<E> object

Summary of Objects generated from JDBC:


1.Connection Object

2.Statement Object

3.PreparedStatement Object

4.CallableStatement Object

5.NonScrollable ResultSet Object

6.Scrollable ResultSet Object

ii
7.RowSet Object

ath
(i)JdbcRowSet Object

(ii)CachedRowSet Object

ip
=>WebRowSet Object

(i)FiltertedRowSet Object

(ii)JoinRowSet Object
Ma
8.Metadata Objects
sh
(i)DatabaseMetaData object

(ii)ParameterMetaData Object
ate

(iii)ResultSetMetaData Object

(iv)RowSetMetaData Object
nk

Diagram:
Ve
ii
ath
===================================================================

ip
define Metadata in JDBC?

=>Metadata means the data holding information about another data

is known as Metadata.
Ma
=>According to Object Oriented proggramming,Metadata means one object
sh
holding information about another object.

=>The following are the metadata components from JDBC:


ate

1.DatabaseMetaData

2.ParameterMetaData
nk

3.ResultSetMetaData

4.RowSetMetaData
Ve

1.DatabaseMetaData:

=>DatabaseMetaData is an interface from java.sql package and

which is used to hold information about Connection Object.

syntax:
DatabaseMetaData dmd = con.getMetaData();

2.ParameterMetaData:

=>ParameterMetaData is an interface from java.sql package and

which is used to hold information about PreparedStatement object.

syntax:

ii
ParameterMetaData pmd = ps.getParameterMetaData();

ath
3.ResultSetMetaData :

ip
=>ResultSetMetaData is an interface from java.sql package and
Ma
which is used to hold the information about ResultSet Object.

syntax:

ResultSetMetaData rsmd = rs.getMetaData();


sh

4.RowSetMetaData:
ate

=>RowSetMetaData is also an interface from java.sql package and

which is used to hold information about RowSet Object.


nk

syntax:
Ve

RowSetMetaData rsmd = (RowSetMetaData)rs.getMetaData();

Ex:

package test;

import java.sql.*;
import javax.sql.rowset.*;

import javax.sql.*;

public class DBCon18 {

public static void main(String[] args) {

try {

Class.forName("oracle.jdbc.driver.OracleDriver");

ii
Connection con = DriverManager.getConnection

ath
("jdbc:oracle:thin:@localhost:1521:XE","system","manager");

DatabaseMetaData dmd = con.getMetaData();

ip
System.out.println("DriverVersion:"+dmd.getDriverMajorVersion());
Ma
PreparedStatement ps = con.prepareStatement

("select * from Book45 where bcode=?");

ps.setString(1,"");
sh
ParameterMetaData pmd = ps.getParameterMetaData();

System.out.println("Count:"+pmd.getParameterCount());
ate

ResultSet rs = ps.executeQuery();

ResultSetMetaData rsmd = rs.getMetaData();


nk

System.out.println("Column count:"+rsmd.getColumnCount());
Ve

JdbcRowSet jrs = RowSetProvider.newFactory().createJdbcRowSet();

jrs.setUrl("jdbc:oracle:thin:@localhost:1521:XE");

jrs.setUsername("system");

jrs.setPassword("manager");

jrs.setCommand("select * from Product45");


jrs.execute();

RowSetMetaData rsmd2 = (RowSetMetaData)jrs.getMetaData();

System.out.println(rsmd2.getColumnCount());

con.close();

jrs.close();

}catch(Exception e) {System.out.print(e.getMessage());}

ii
}

ath
}

============================================================

ip
faq:

define Stream?
Ma
=>The Continuous flow of data is known as Stream.
sh
Types of Streams:

=>Streams in Java are categorized into two types:


ate

1.Byte Stream(Binary Stream)

2.Character Stream
nk

1.Byte Stream(Binary Stream):


Ve

=>The continuous flow of 8-bit data is known as Byte Stream or Binary

Stream.

=>Byte Stream supports all multi-media data files like Text,Audio,Video,

Image and Animation.


2.Character Stream:

=>The Continuous flow of 16-bit data is known as Character Stream.

=>Character Stream is preferable for Text data and not preferable for

Audio,Video,Image and Animation files.

----------------------------------------------------------

faq:

ii
wt is the diff b/w

ath
(i)input stream

(ii)output stream

ip
(i)input stream:
Ma
=>The stream into JavaProgram is known as input stream.

Ex:
sh
JavaProgram reading stream from file

(ii)output stream:
ate

=>The stream outof JavaProgram is known as output stream.

Ex:
nk

JavaProgram writing stream onto file

=====================================================================
Ve

Note:

=>we use the following SQL-types to store streams:

1.BLOB

2.CLOB
1.BLOB:

=>BLOB stands for 'Binary Large OBjects' and which is used to store binary

Stream data.(Multi-Media data)

2.CLOB:

=>CLOB stands for 'Character Large OBjects' and which is used to store

ii
Character Stream data.(Text data)

ath
=======================================================================

*imp

ip
Servlet Programming:(Unit-2)

define Servlet Program?


Ma
=>The PlatForm independent JavaProgram which is executed in
sh
Server environment is known as Servlet Program or Server Program.

=>Servlet Program will accept HTTP request from user through


ate

WebBrowser and provides response.


nk

Diagram:
Ve
ii
ip ath
Ma
=========================================================
sh
ate
nk
Ve
Dt : 18/5/2022

Types of Applications:

=>Applications are categorized in the following:

(a)StandAlone Applications

(b)Web Applications

(c)Enterprise Applications

ii
(d)Mobile Applications

ath
(a)StandAlone Applications:

ip
=>The applications which are installed in one computer
Ma
and performs actions in the same computer are known as

StandAlone Applications.

=>which are also known as DeskTop applications or


sh
Windows Applications.

Note:
ate

=>According to developer StandAlone applications means,

No HTML input
nk

No Server Environment

No DataBase Storage
Ve

=>Based on User interaction these StandAlone applications are

Categorized into two types:

(i)CUI Applications

(ii)GUI Applications
(i)CUI Applications:

=>The applications in which the user interacts through

Console are known as CUI Applications.

(CUI - Console User Interface)

ii
(ii)GUI Applications:

ath
=>The applications in which the user interacts through

GUI components are known as GUI Applications.

ip
(GUI - Graphical User Interface)

Note:
Ma
=>we use AWT(Abstract Window Toolkit) and Swings to design
sh
GUI components

--------------------------------------------------
ate

(b)Web Applications:

=>The applications which are executed in Web Environment


nk

or Internet Environment are known as Web Applications.

=>To Construct WebApplications we use JDBC,Servlet and JSP.


Ve

Note:

=>These Web Applications are executed in 'WebContainer'

=>This WebContainer is available from WebServers and

Application Servers.
------------------------------------------------------

(c)Enterprise Applications:

=>The applications which are executing in distributed

Environment and depending on the features like Security,

Load Balancing and Clustering process are known as Enterprise

Applications or Enterprise Distributed Applications.

ii
-------------------------------------------------------

ath
(d)Mobile Applications:

=>The applications which are executed in Mobile environment

ip
are known as Mobile Applications.

==========================================================

faq:
Ma
define Server?
sh
=>Server means service provider,which means accepting the

request and providing the response.


ate

define Client?
nk

=>The user who generate request to the Server is known as

Client.
Ve

imp

Types of Servers:

=>Servers are categorized into two types:

(i)WebServers
(ii)Application Servers

(i)WebServer:

=>Web Server contains only Web container .

=>A web server is good in case of static contents like static

html pages.

ii
=>Web server consumes less resources like CPU, Memory etc. as

ath
compared to application server.

=>Web Server provides the runtime environment for web

ip
applications.

=>Web Server supports HTTP Protocol

=>Apache Web Server.(Tomcat)


Ma
sh
(ii)Application Server:

=>Application Server contains both Web Container and EJB


ate

Container.(EJB - Enterprise Java Bean)

=>Applcation server is relevant in case of dynamic contents


nk

like bank websites.

=>Application server utilizes more resources


Ve

=>Application server provides the runtime environment for

enterprise applications.

=>Application Server suppots HTTP as well as RPC/RMI protocols.

(RPC - Remote Procedure call)

(RMI - Remote Method Invocation)


=>Weblogic, JBoss.

------------------------------------------------------------------

*imp

Installing Tomcat Server:

step1 : Download Tomcat9.x WebServer

ii
ath
webserver - Tomcat 9.x

(Compatable with JDK1.8 and Above )

ip
vendor - Apache org

default port no

download
- 8080

- www.apache.org(Open source)
Ma
sh
Note:

=>WebContainer internally has two SubContainers


ate

(i)Servlet container

(ii)JSP Container
nk

Servlet container : Catelina


Ve

Jsp Container : Jasper

step-2 : Install the Tomcat Server


while Installation process,

Select the type of install : Full(click next)

Server Shutdown port : 8089

HTTP/1.1 Connector port : 8081 or 8082 or 8083...

ii
User Name : Venkatesh

ath
Password : nit

(click next)

ip
step-3 : Start the Tomcat Server
Ma
=>To start Tomcat server click on 'startup' or 'Tomcat9w'
sh
from 'bin' of Tomcat

C:\Tomcat 9.0\bin
ate
nk

step-4 : Access Tomcat Server from WebBrowser using the

following URL:
Ve

http://localhost:8081

step-5 : Stop the Tomcat Server

=>To stop Tomcat server click on 'shutdown' or 'Tomcat9w'


from 'bin' of Tomcat

C:\Tomcat 9.0\bin

===========================================================

Dt : 19/5/2022

*imp

Servlet API:

ii
=>'javax.servlet' package is known as Servlet API and which

ath
provide classes and interfaces used in Servlet application

development.

ip
=>'javax.servlet.Servlet' interface is the root of Servlet API.

Hierarchy of Servlet API:


Ma
sh
ate
nk
Ve

-------------------------------------------------------

Note:

=>In the process of constructing Servlet programs,the programs


must be extended from any one of the following:

(a)GenericServlet

(b)HttpServlet

(a)GenericServlet:

=>When ServletProgram is extended from GenericServlet then

ii
the following Life-Cycle methods are available

ath
(i)init()

(ii)service()

ip
(iii)destroy()
Ma
=>These methods are automatically executed in the same order.

=>GenericServlet is Protocol independent,which means ready to

accept request from any type of protocol.


sh
ate
nk
Ve
ii
ip ath
Ma
(b)HttpServlet:
sh
=>when ServletProgram is extended from HttpServlet then

the following Life-Cycle methods are available


ate

(i)init()

(ii)service()/doPost()/doGet()
nk

(iii)destroy()

=>HttpServlet is Protocol dependent,which means accepts the


Ve

request from Http Protocol.


ii
ip ath
Ma
sh
ate

==================================================

*imp

Constructing Servlet Application using IDE Eclipse:


nk
Ve

step-1 : Open IDE Eclipse,while opening name the WorkSpace and

click finish

step-2 : Create Dynamic Web Project

Click on File->new->Project->Web->select 'Dynamic Web Project'->


click 'next'->name the Project and click 'finish'

step-3 : Add 'servlet-api.jar' to Dynamic Web Project

RightClick on Dynamic Web Project->Build Path->

Configure Build path->Libraries->select 'classpath and click

ii
Add External Jars'->Browse and select 'servlet-api.jar' file

ath
from 'lib' of Tomcat->open-Apply->Apply and Close.

ip
step-4 : Add Tomcat Server to IDE environment
Ma
Click Servers->click 'click this link to create new server'->

select the type of server and click next-> Browse Tomcat


sh
Installation directory and click finish.
ate

step-5 : Construct the Servlet Application.


nk

input.html

<!DOCTYPE html>
Ve

<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="dis" method="post">
UserName:<input type="text" name="uname"><br>
MailId:<input type="text" name="mid"><br>
<input type="submit" value="Display">
</form>
</body>
</html>

DisplayServlet.java

package test;

import java.io.*;

import javax.servlet.*;

import javax.servlet.annotation.*;

ii
ath
@SuppressWarnings("serial")

@WebServlet("/dis")

public class DisplayServlet extends GenericServlet{

ip
public void init()throws ServletException{
Ma
//NoCode

public void service(ServletRequest req,


sh
ServletResponse res)throws ServletException,
ate

IOException{

String uName = req.getParameter("uname");

String mId = req.getParameter("mid");


nk

PrintWriter pw = res.getWriter();
Ve

res.setContentType("text/html");

pw.println("====UserDetails===");

pw.println("<br>UserName:"+uName);

pw.println("<br>MailId:"+mId);

public void destroy() {


//NoCode

web.xml

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


<web-app>
<welcome-file-list>
<welcome-file>input.html</welcome-file>

ii
</welcome-file-list>

ath
</web-app>

step-6 : Execute the Servlet Application

RightClick on Dynamic Web Project->Run as->Run on Server->

ip
select the server and click finish. Ma
=====================================================
sh
ate
nk
Ve
Dt:21/5/2022

Assignment-1:(Solution)

Construct Servlet Application to read and display Product details?

product.html

<!DOCTYPE html>
<html>

ii
<head>

ath
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="dis" method="post">

ip
ProductCode:<input type="text" name="pcode"><br>
ProductName:<input type="text" name="pname"><br>
Ma
ProductPrice:<input type="text" name="pprice"><br>
ProductQty:<input type="text" name="pqty"><br>
<input type="submit" value="Display">
</form>
</body>
</html>
sh
DisplayServlet.java
ate

package test;

import java.io.*;
nk

import javax.servlet.*;

import javax.servlet.annotation.*;
Ve

@SuppressWarnings("serial")

@WebServlet("/dis")

public class DisplaySerrvlet extends GenericServlet{

public void init()throws ServletException{

//NoCode

}
public void service(ServletRequest req,ServletResponse res)

throws ServletException,IOException{

String pC = req.getParameter("pcode");

String pN = req.getParameter("pname");

float pP = Float.parseFloat(req.getParameter("pprice"));

int pQ = Integer.parseInt(req.getParameter("pqty"));

ii
PrintWriter pw = res.getWriter();

ath
res.setContentType("text/html");

pw.println("ProdCode:"+pC);

ip
pw.println("<br>ProdName:"+pN);

pw.println("<br>ProdPrice:"+pP);

pw.println("<br>ProdQty:"+pQ);
Ma
}
sh
public void destroy() {

//NoCode
ate

}
nk

web.xml

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


Ve

<web-app>
<welcome-file-list>
<welcome-file>product.html</welcome-file>
</welcome-file-list>
</web-app>

===============================================================

Note:

=>we use getRequestDispatcher() method from ServletRequest to create the


implementation object of 'RequestDispatcher' interface.

syntax:

RequestDispatcher rd = req.getRequestDispatcher("url-pattern/HTML/JSP");

rd.forward(req,res);

ii
rd.include(req,res);

ath
Ex:

ip
input.html

<!DOCTYPE html>
<html>
<head>
Ma
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
sh
<body>
<form action="choice" method="post">
Enter the Value1:<input type="text" name="v1"><br>
ate

Enter the Value2:<input type="text" name="v2"><br>


<input type="submit" value="Add" name="s1">
<input type="submit" value="Sub" name="s1">
</form>
</body>
nk

</html>

ChoiceServlet.java
Ve

package test;

import java.io.*;

import javax.servlet.*;

import javax.servlet.annotation.*;

@SuppressWarnings("serial")
@WebServlet("/choice")

public class ChoiceServlet extends GenericServlet{

public void init()throws ServletException{

//NoCode

public void service(ServletRequest req,ServletResponse res)

ii
throws ServletException,IOException{

ath
String s1 = req.getParameter("s1");

if(s1.equals("Add")) {

ip
RequestDispatcher rd=req.getRequestDispatcher("ad");

}else {
rd.forward(req, res);
Ma
RequestDispatcher rd=req.getRequestDispatcher("sb");
sh
rd.forward(req, res);

}
ate

public void destroy() {


nk

//NoCode

}
Ve

AdditionServlet.java

package test;

import java.io.*;

import javax.servlet.*;
import javax.servlet.annotation.*;

@SuppressWarnings("serial")

@WebServlet("/ad")

public class AdditionServlet extends GenericServlet{

public void init()throws ServletException{

//NoCode

ii
}

ath
public void service(ServletRequest req,ServletResponse res)

throws ServletException,IOException{

ip
int v1 = Integer.parseInt(req.getParameter("v1"));
Ma
int v2 = Integer.parseInt(req.getParameter("v2"));

int v3 = v1+v2;

PrintWriter pw = res.getWriter();
sh
res.setContentType("text/html");

pw.println("Sum:"+v3+"<br>");
ate

RequestDispatcher rd = req.getRequestDispatcher("input.html");

rd.include(req, res);
nk

public void destroy() {


Ve

//NoCode

SubtractionServlet.java

package test;
import java.io.*;

import javax.servlet.*;

import javax.servlet.annotation.*;

@SuppressWarnings("serial")

@WebServlet("/sb")

public class SubtractionServlet extends GenericServlet{

ii
public void init()throws ServletException{

ath
//NoCode

ip
public void service(ServletRequest req,ServletResponse res)

throws ServletException,IOException{
Ma
int v1 = Integer.parseInt(req.getParameter("v1"));

int v2 = Integer.parseInt(req.getParameter("v2"));
sh
int v3 = v1-v2;

PrintWriter pw = res.getWriter();
ate

res.setContentType("text/html");

pw.println("Sub:"+v3+"<br>");
nk

RequestDispatcher rd = req.getRequestDispatcher("input.html");

rd.include(req, res);
Ve

public void destroy() {

//NoCode

}
web.xml

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


<web-app>
<welcome-file-list>
<welcome-file>input.html</welcome-file>
</welcome-file-list>
</web-app>

Diagram:

ii
ip ath
Ma
sh
-----------------------------------------------------------------

Assignment-1:
ate

Update above application with the following :

=>MultiplicationServlet
nk

=>DivisionServlet

=>ModuloDivisionServlet
Ve

-------------------------------------------------------------

Assignment-2:

Construct Servlet Application using the following Layout:


ii
ath
======================================================================

ip
Ma
sh
ate
nk
Ve
Dt : 23/5/2022

Assignment-2:(Solution)

Construct Servlet Application using the following Layout:

input.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">

ii
<title>Insert title here</title>

ath
</head>
<body>
<form action="choice" method="post">
<input type="submit" value="Book" name="s1">
<input type="submit" value="Product" name="s1">

ip
</form> Ma
</body>
</html>

book.html

<!DOCTYPE html>
sh
<html>
<head>
<meta charset="ISO-8859-1">
ate

<title>Insert title here</title>


</head>
<body>
<form action="book" method="post">
BookCode:<input type="text" name="bcode"><br>
nk

BookName:<input type="text" name="bname"><br>


BookAuthor:<input type="text" name="bauthor"><br>
BookPrice:<input type="text" name="bprice"><br>
Ve

BookQty:<input type="text" name="bqty"><br>


<input type="submit" value="DisplayBookDetails">
</form>
</body>
</html>

product.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="product" method="post">
ProdCode:<input type="text" name="pcode"><br>
ProdName:<input type="text" name="pname"><br>
ProdPrice:<input type="text" name="pprice"><br>
ProdQty:<input type="text" name="pqty"><br>
<input type="submit" value="DisplayProductDetails">
</form>

ii
</body>
</html>

ath
ChoiceServlet.java

package test;

ip
import java.io.*;

import javax.servlet.*;

import javax.servlet.annotation.*;
Ma
@SuppressWarnings("serial")
sh
@WebServlet("/choice")

public class ChoiceServlet extends GenericServlet{


ate

public void init()throws ServletException{

//NoCode
nk

public void service(ServletRequest req,ServletResponse res)


Ve

throws ServletException,IOException{

String s1 = req.getParameter("s1");

if(s1.equals("Book")) {

RequestDispatcher rd = req.getRequestDispatcher("book.html");

rd.forward(req, res);
}else {

RequestDispatcher rd = req.getRequestDispatcher("product.html");

rd.forward(req, res);

public void destroy() {

ii
//NoCode

ath
}

ip
BookServlet.java

package test;

import java.io.*;
Ma
import javax.servlet.*;
sh
import javax.servlet.annotation.*;

@SuppressWarnings("serial")
ate

@WebServlet("/book")

public class BookServlet extends GenericServlet{


nk

public void init()throws ServletException{

//NoCode
Ve

public void service(ServletRequest req,ServletResponse res)

throws ServletException,IOException{

PrintWriter pw = res.getWriter();

res.setContentType("text/html");
pw.println("====BookDetails====");

pw.println("<br>BookCode:"+req.getParameter("bcode"));

pw.println("<br>BookName:"+req.getParameter("bname"));

pw.println("<br>BookAuthor:"+req.getParameter("bauthor"));

pw.println("<br>BookPrice:"+req.getParameter("bprice"));

pw.println("<br>BookQty:"+req.getParameter("bqty"));

ii
pw.println("<br>");

ath
RequestDispatcher rd=req.getRequestDispatcher("input.html");

rd.include(req, res);

ip
}

public void destroy() {

//NoCode
Ma
}
sh
}

ProductServlet.java
ate

package test;

import java.io.*;
nk

import javax.servlet.*;

import javax.servlet.annotation.*;
Ve

@SuppressWarnings("serial")

@WebServlet("/product")

public class ProductServlet extends GenericServlet{

public void init()throws ServletException{

//NoCode
}

public void service(ServletRequest req,ServletResponse res)

throws ServletException,IOException{

PrintWriter pw = res.getWriter();

res.setContentType("text/html");

pw.println("====ProductDetails=====");

ii
pw.println("<br>ProdCode:"+req.getParameter("pcode"));

ath
pw.println("<br>ProdName:"+req.getParameter("pname"));

pw.println("<br>ProdPrice:"+req.getParameter("pprice"));

ip
pw.println("<br>ProdQty:"+req.getParameter("pqty"));

pw.println("<br>");
Ma
RequestDispatcher rd = req.getRequestDispatcher("input.html");

rd.include(req, res);
sh
}

public void destroy() {


ate

//NoCode

}
nk

web.xml
Ve

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


<web-app>
<welcome-file-list>
<welcome-file>input.html</welcome-file>
</welcome-file-list>
</web-app>

=====================================================================

*imp
define Java Bean Class?

=>The classes which are constructed with the following rules are known as

Java Bean Classes.

Rule-1 : The class must be implemented from 'java.io.Serializable' interface.

Rule-2 : The variables declared in the class must be private variables.

ii
Rule-3 : The class must be declared with 0-argument constructor or 0-parameter

ath
Constructor.

Rule-4 : The class must be declared with 'Setter' and 'Getter' methods.

ip
define Setter methods?
Ma
=>The methods which are used to load the data to object are known as 'Setter'

methods.
sh

define Getter methods?


ate

=>The methods which are used to get the data from the object are known as

Getter methods.
nk

Rule of Constructing Setter and Getter methods:


Ve

=>Every Variable in Class must have its own Setter method and Getter method.

Note:

=>These Java Bean Classes will generate bean objects and these bean objects

will hold data going on to DataBase or bean Objects will hold data coming from
DataBase.

-----------------------------------------------------------------

=>Based on serialization process,the objects are categorized into two types:

(i)Serializable objects

(ii)NonSerializable Objects

ii
(i)Serializable objects:

ath
=>The objects which support Serialization process are known as Serializable

objects,which means we can convert Object state into binary Stream.

ip
=>These Serializable objects can travel on N/W.
Ma
=>To generate Serializable objects the classes must be implemented from

java.io.Serializable interface.
sh
(ii)NonSerializable Objects:

=>The Objects which will not support Serialization process are known as
ate

NonSerializable objects.

Ex:
nk

JDBC objects are NonSerializable objects.

-----------------------------------------------------------------
Ve

*imp

Summary of Objects generated from CoreJava:

1.User defined Class Object(Serializable object)

2.String Objects(Serializable objects)

3.WrapperClass Objects(Serializable Objects)


4.Array objects(Serializable Objects)

5.Collection<E> objects(Serializable Objects)

6.Map<K,V> objects(Serializable Objects)

7.Enum<E> object(Serializable Object)

==============================================================

ii
ip ath
Ma
sh
ate
nk
Ve
Dt : 24/5/2022

*imp

"attribute" in Servlet Programming:

=>'attribute' is a variable in Servlet programming which can be added to

ServletContext object,ServletRequest object and HttpSession object.

=>The following are the methods related to 'attribute':

ii
(i)setAttribute()

ath
(ii)getAttribute()

(iii)removeAttribute()

ip
(iv)getAttributeNames()

(i)setAttribute():
Ma
=>setAttribute() method is used to add 'attribute' to the objects.
sh
Method Signature:

public abstract void setAttribute(java.lang.String,java.lang.Object);


ate

(ii)getAttribute():
nk

=>This getAttribute() method is used to get the attribute from the Objects.

Method Signature:
Ve

public abstract java.lang.Object getAttribute(java.lang.String);

(iii)removeAttribute():

=>removeAttribute() method is used to delete the attribute from the objects.

Method Signature:
public abstract void removeAttribute(java.lang.String);

(iv)getAttributeNames():

=>getAttributeNames() method is used to get all the attribute names from

the objects.

Method Signature:

public abstract java.util.Enumeration<java.lang.String> getAttributeNames();

ii
------------------------------------------------

ath
Scope of 'attribute':

=>'attribute' in ServletContext object can be used by all the Servlet programs

ip
of WebApplication.
Ma
=>'attribute' in ServletRequest object can be accessed by Second Servlet

program in forward communication process.

=>'attribute' in HttpSession object is available from user Login to Logout.


sh
ate
nk
Ve

==========================================================================

faq:

define DAO?
=>DAO stands for 'Data Access Object' and which is separate layer in MVC(Model

View Controller) to hold DataBase related codes.(Persistent Logics)

Diagram:

ii
ip ath
Note:
Ma
=>In the process of establishing communiation b/w Servlet Program and DataBase

product,the DB-Jar file must be copied into 'lib' folder of 'WEB-INF'.


sh
==================================================================
ate
nk
Ve
Dt : 25/5/2022

ServletApplication : ProductApp

choice.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">

ii
<title>Insert title here</title>

ath
</head>
<body>
<a href="product.html">AddProduct</a>
<a href="view">ViewProducts</a>
</body>

ip
</html>

product.html

<!DOCTYPE html>
Ma
<html>
<head>
<meta charset="ISO-8859-1">
sh
<title>Insert title here</title>
</head>
<body>
ate

<form action="add" method="post">


ProductCode:<input type="text" name="pcode"><br>
ProductName:<input type="text" name="pname"><br>
ProductPrice:<input type="text" name="pprice"><br>
ProductQty:<input type="text" name="pqty"><br>
nk

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


</form>
</body>
Ve

</html>

ProductBean.java

package test;
import java.io.*;
@SuppressWarnings("serial")
public class ProductBean implements Serializable{
private String code,name;
private float price;
private int qty;
public ProductBean() {}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {

ii
this.name = name;
}

ath
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;

ip
}
public int getQty() { Ma
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
sh
}
ate

AddProductServlet.java

package test;
nk

import java.io.*;

import javax.servlet.*;
Ve

import javax.servlet.annotation.*;

@SuppressWarnings("serial")

@WebServlet("/add")

public class AddProductServlet extends GenericServlet{

public void init()throws ServletException{


//NoCode

public void service(ServletRequest req,ServletResponse res)

throws ServletException,IOException{

ProductBean pb = new ProductBean();//Bean object

pb.setCode(req.getParameter("pcode"));

ii
pb.setName(req.getParameter("pname"));

ath
pb.setPrice(Float.parseFloat(req.getParameter("pprice")));

pb.setQty(Integer.parseInt(req.getParameter("pqty")));

ip
PrintWriter pw = res.getWriter();

res.setContentType("text/html");
Ma
sh
int k = new InsertDAO().insert(pb);

if(k>0) {
ate

pw.println("Product Added Successfully....<br>");

RequestDispatcher rd=
nk

req.getRequestDispatcher("choice.html");

rd.include(req, res);
Ve

public void destroy() {

//NoCode

}
}

DBConnection.java

package test;
import java.sql.*;
public class DBConnection {
private static Connection con=null;//reference variable
private DBConnection() {}
static
{
try {

ii
Class.forName("oracle.jdbc.driver.OracleDriver");

ath
con = DriverManager.getConnection

("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
}catch(Exception e) {e.printStackTrace();}
}

ip
public static Connection getCon()
{ Ma
return con;
}
}

InsertDAO.java
sh
package test;
import java.sql.*;
ate

public class InsertDAO {


public int k=0;
public int insert(ProductBean pb)
{
nk

try {
Connection con = DBConnection.getCon();
//Accessing the Connection
PreparedStatement ps = con.prepareStatement
Ve

("insert into Product45 values(?,?,?,?)");


ps.setString(1,pb.getCode());
ps.setString(2,pb.getName());
ps.setFloat(3,pb.getPrice());
ps.setInt(4,pb.getQty());
k = ps.executeUpdate();
}catch(Exception e) {e.printStackTrace();}
return k;
}
}
RetrieveDAO.java

package test;

import java.sql.*;

import java.util.*;

public class RetrieveDAO {

ii
public ArrayList<ProductBean> al = new ArrayList<ProductBean>();

ath
public ArrayList<ProductBean> retrieve()

ip
try {
Ma
Connection con = DBConnection.getCon();

//Accessing the Connection

PreparedStatement ps = con.prepareStatement
sh
("select * from Product45");

ResultSet rs = ps.executeQuery();
ate

while(rs.next())

{
nk

ProductBean pb = new ProductBean();

pb.setCode(rs.getString(1));
Ve

pb.setName(rs.getString(2));

pb.setPrice(rs.getFloat(3));

pb.setQty(rs.getInt(4));

al.add(pb);//Adding bean to ArrayList

}//end of loop
}catch(Exception e) {e.printStackTrace();}

return al;

ViewProductsServlet.java

package test;

ii
import java.io.*;

ath
import java.util.*;

import javax.servlet.*;

ip
import javax.servlet.annotation.*;

@SuppressWarnings("serial")

@WebServlet("/view")
Ma
public class ViewProductsServlet extends GenericServlet{
sh
public void init()throws ServletException{

//NoCode
ate

public void service(ServletRequest req,ServletResponse res)


nk

throws ServletException,IOException{

ArrayList<ProductBean> al = new RetrieveDAO().retrieve();


Ve

PrintWriter pw = res.getWriter();

res.setContentType("text/html");

if(al.size()==0) {

pw.println("Products Not Available...<br>");

}else {
Iterator<ProductBean> it = al.iterator();

while(it.hasNext())

ProductBean pb = (ProductBean)it.next();

pw.println(pb.getCode()+"&nbsp&nbsp"+

pb.getName()+"&nbsp&nbsp"+pb.getPrice()+

ii
"&nbsp&nbsp"+pb.getQty()+"<br>");

ath
}//end of loop

}//end of else

ip
RequestDispatcher rd = req.getRequestDispatcher("choice.html");

}
rd.include(req, res);
Ma
public void destroy() {
sh
//NoCode

}
ate

web.xml
nk

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


<web-app>
<welcome-file-list>
Ve

<welcome-file>choice.html</welcome-file>
</welcome-file-list>
</web-app>

Diagram:
ii
ath
===============================================================

ip
Ma
sh
ate
nk
Ve
Dt:26/5/2022

define Iterator<E>?

=>Iterator<E> is an interface from java.util package and which is used to

retrieve elements from Collection<E> objects in forward direction.

=>The following are some important methods from Iterator<E>:

(a)hasNext()

ii
(b)next()

ath
(c)remove()

(d)forEachRemaining()

ip
(a)hasNext():
Ma
=>hasNext() method will check the element is available or not,and generate

boolean result.
sh
Method Signature:

public abstract boolean hasNext();


ate

(b)next():
nk

=>This next() method is used to take the element from Collection<E> object.

Method Signature:
Ve

public abstract E next();

(c)remove():

=>This method is used to remove the element from Collection<E> object.

Method Signature:
public default void remove();

(d)forEachRemaining():

=>forEachRemaining() method added to Iterator<E> from Java8 version onwards

and uses LambdaExpression to retrieve the elements.

Method Signature:

ii
public default void forEachRemaining(java.util.function.Consumer<? super E>);

ip ath
define iterator() method?
Ma
=>iterator() method is used to create the implementation object of Iterator<E>

interface and the object will hold the reference of Collection<E> object,in this

process the iterator() method also generate cursor pointing before the first
sh
element of Collection<E> object.
ate

syntax:

Iterator<ProductBean> it = al.iterator();
nk

=======================================================================

Assignment:
Ve

Construct Servlet Application to perform the following operations:

=>AddBook

=>ViewBooks

=>EditBookDetails(based on BookCode)

=>DeleteBook(based on BookCode)
==========================================================================

faq:

define request?

=>The query generated from user or client through WebBrowser is known as request.

Diagram:

ii
ath
Types of requests:

ip
=>Requests are categorized into two types:

1.POST request

2.GET request
Ma
sh
1.POST request :

=>The request generated to send the data to Server is known as POST request.
ate

=>Through POST request we can send all types of data like Text,Audio,Video,

Image and Animation.


nk

=>Through POST request we can send UnLimited data.

=>The data which is sent through POST request is secured because the data is
Ve

encapsulated into the body part of HTTP.

=>We use the following syntax to generate POST request:

<form action="url" method="POST">

...

</form>
=>we use doPost() method from HttpServlet to accept POST request.

Method Signature:

protected void doPost(javax.servlet.http.HttpServletRequest,

javax.servlet.http.HttpServletResponse)throws javax.servlet.ServletException,

java.io.IOException;

ii
ath
2.GET request"

=>The request generated to get the data from the Server is known as GET request.

ip
=>Through GET request we can send only text data.
Ma
=>Through GET request we can send only limited data,which means up to 4kb or 8kb.

=>The data which is sent through GET request is not secured,because the data is

display in address bar directly.


sh
=>We use the following four ways to generate GET request:
ate

(i)Using method="GET" in <form> tag

<form action="url" method="GET">


nk

...

</form>
Ve

(ii)without using method attribute in <form> tag

<form action="url">

...

</form>

(iii)Using Hyper Link


(iv)Using servlet-url-pattern in AddressBar

=>we use doGet() method from HttpServlet to accept GET request

Method Signature:

protected void doGet(javax.servlet.http.HttpServletRequest,

javax.servlet.http.HttpServletResponse)throws javax.servlet.ServletException,

java.io.IOException;

ii
=============================================================

ip ath
Ma
sh
ate
nk
Ve
Dt : 27/5/2022

*imp

Session Tracking in Servlet Programming:

define Session?

=>The time interval b/w login to logout is known as Session.

ii
ath
define Session Tracking process?

=>The process of tracking the 'user state' from login to logout is known as

ip
Session Tracking process.
Ma
=>We use the following four techniques to perform Session Tracking process:

(a)Cookie

(b)HttpSession
sh
(c)URL re-write

(d)Hidden form fields


ate

(a)Cookie:
nk

=>The piece of information persisted b/w multiple client requets is known as

cookie.
Ve

=>Cookies are stored in WebBrowser and tracks the user.

=>These Cookies are categorized into two types:

(i)Persistent Cookies

(ii)Non-Persistent Cookies
(i)Persistent Cookies:

=>The Cookies which are available in WebBrowser until user logs out are

known as Persistent Cookies.

(ii)Non-Persistent Cookies:

=>The Cookies which are destroyed automatically when the WebBrowser is closed

ii
are known as Non-Persistent Cookies.

ath
---------------------------------------------------------------------

=>we use 'javax.servlet.http.Cookie' class to construct Cookie Session Tracking

ip
process.

Hierarchy of Cookie:
Ma
sh
ate
nk

=>The following are some important methods from Cookie:


Ve

public javax.servlet.http.Cookie(java.lang.String, java.lang.String);

public void setMaxAge(int);

public int getMaxAge();


public void setValue(java.lang.String);

public java.lang.String getValue();

public java.lang.String getName();

-----------------------------------------------------------

ii
=>we use the following process to construct Cookie Session Tracking:

ath
step-1 : When the Login process is Successfull then construct the Cookie.

ip
syntax:

Cookie ck = new Cookie("name","value");


Ma
step-2 : Add the Cookie to the response
sh
syntax:

res.addCookie(ck);
ate

step-3 : Get cookies from the request


nk

systax:

Cookie c[] = req.getCookies();


Ve

step-4 : Invalidating the Cookie

syntax:

c.setMaxAge(0);

-----------------------------------------------------------------------
Ex:

ii
ath
DBConnection.java

package test;

ip
import java.sql.*;
public class DBConnection {
private static Connection con=null;//reference variable
Ma
private DBConnection() {}
static
{
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
sh
con = DriverManager.getConnection

("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
ate

}catch(Exception e) {e.printStackTrace();}
}
public static Connection getCon()
{
return con;
nk

}
}
Ve

UserBean.java

package test;
import java.io.*;
@SuppressWarnings("serial")
public class UserBean implements Serializable{
private String uName,pWord,fName,lName,addr,mId;
private long phNo;
public UserBean() {}
public String getuName() {
return uName;
}
public void setuName(String uName) {
this.uName = uName;
}
public String getpWord() {
return pWord;
}
public void setpWord(String pWord) {
this.pWord = pWord;
}

ii
public String getfName() {
return fName;

ath
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {

ip
return lName;
} Ma
public void setlName(String lName) {
this.lName = lName;
}
public String getAddr() {
return addr;
}
sh
public void setAddr(String addr) {
this.addr = addr;
}
ate

public String getmId() {


return mId;
}
public void setmId(String mId) {
nk

this.mId = mId;
}
public long getPhNo() {
return phNo;
Ve

}
public void setPhNo(long phNo) {
this.phNo = phNo;
}

login.html
package test;
import java.io.*;
@SuppressWarnings("serial")
public class UserBean implements Serializable{
private String uName,pWord,fName,lName,addr,mId;
private long phNo;
public UserBean() {}
public String getuName() {
return uName;
}
public void setuName(String uName) {

ii
this.uName = uName;
}

ath
public String getpWord() {
return pWord;
}
public void setpWord(String pWord) {
this.pWord = pWord;

ip
}
public String getfName() { Ma
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
sh
return lName;
}
public void setlName(String lName) {
ate

this.lName = lName;
}
public String getAddr() {
return addr;
nk

}
public void setAddr(String addr) {
this.addr = addr;
}
Ve

public String getmId() {


return mId;
}
public void setmId(String mId) {
this.mId = mId;
}
public long getPhNo() {
return phNo;
}
public void setPhNo(long phNo) {
this.phNo = phNo;
}

register.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">

ii
<title>Insert title here</title>

ath
</head>
<body>
<form action="reg" method="post">
UserName:<input type="text" name="uname"><br>
PassWord:<input type="text" name="pword"><br>

ip
FirstName:<input type="text" name="fname"><br>
LastName:<input type="text" name="lname"><br>
Ma
Address:<input type="text" name="addr"><br>
MailId:<input type="text" name="mid"><br>
PhoneNo:<input type="text" name="phno"><br>
<input type="submit" value="Register">
</form>
</body>
sh
</html>

RegisterDAO.java
ate

package test;
import java.sql.*;
public class RegisterDAO {
public int k=0;
nk

public int register(UserBean ub)


{
try {
Ve

Connection con = DBConnection.getCon();


PreparedStatement ps = con.prepareStatement
("insert into UserReg45 values(?,?,?,?,?,?,?)");
ps.setString(1,ub.getuName());
ps.setString(2,ub.getpWord());
ps.setString(3,ub.getfName());
ps.setString(4,ub.getlName());
ps.setString(5,ub.getAddr());
ps.setString(6,ub.getmId());
ps.setLong(7,ub.getPhNo());
k = ps.executeUpdate();
}catch(Exception e) {e.printStackTrace();}
return k;
}
}

RegisterServlet.java

package test;

ii
import java.io.*;

ath
import javax.servlet.*;

import javax.servlet.http.*;

import javax.servlet.annotation.*;

ip
@SuppressWarnings("serial") Ma
@WebServlet("/reg")

public class RegisterServlet extends HttpServlet{

protected void doPost(HttpServletRequest req,HttpServletResponse res)


sh
throws ServletException,IOException{
ate

UserBean ub = new UserBean();

ub.setuName(req.getParameter("uname"));
nk

ub.setpWord(req.getParameter("pword"));

ub.setfName(req.getParameter("fname"));
Ve

ub.setlName(req.getParameter("lname"));

ub.setAddr(req.getParameter("addr"));

ub.setmId(req.getParameter("mid"));

ub.setPhNo(Long.parseLong(req.getParameter("phno")));

int k = new RegisterDAO().register(ub);

PrintWriter pw = res.getWriter();
res.setContentType("text/html");

if(k>0) {

pw.println("User Registered Successfully...<br>");

RequestDispatcher rd=

req.getRequestDispatcher("login.html");

rd.include(req, res);

ii
}

ath
}

ip
Web.xml

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


Ma
<web-app>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
sh
</welcome-file-list>
</web-app>
ate
nk
Ve
Dt : 28/5/2022

link.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="view">ViewProducts</a>

ii
<a href="logout">Logout</a>

ath
</body>
</html>

LoginDAO.java

ip
package test;

import java.sql.*;

import javax.servlet.http.*;
Ma
public class LoginDAO {
sh
public UserBean ub=null;

public UserBean login(HttpServletRequest req) {


ate

try {

Connection con = DBConnection.getCon();


nk

PreparedStatement ps = con.prepareStatement

("select * from UserReg45 where uname=? and pword=?");


Ve

ps.setString(1,req.getParameter("uname"));

ps.setString(2,req.getParameter("pword"));

ResultSet rs = ps.executeQuery();

if(rs.next()) {

ub = new UserBean();//Bean Object


ub.setuName(rs.getString(1));

ub.setpWord(rs.getString(2));

ub.setfName(rs.getString(3));

ub.setlName(rs.getString(4));

ub.setAddr(rs.getString(5));

ub.setmId(rs.getString(6));

ii
ub.setPhNo(rs.getLong(7));

ath
}

}catch(Exception e) {e.printStackTrace();}

ip
return ub;

}
}
Ma
LoginServlet.java
sh
package test;

import java.io.*;
ate

import javax.servlet.*;

import javax.servlet.http.*;
nk

import javax.servlet.annotation.*;

@SuppressWarnings("serial")
Ve

@WebServlet("/log")

public class LoginServlet extends HttpServlet{

protected void doPost(HttpServletRequest req,

HttpServletResponse res)throws ServletException,IOException{

UserBean ub = new LoginDAO().login(req);


PrintWriter pw = res.getWriter();

res.setContentType("text/html");

if(ub==null) {

pw.println("Invalid Login Process....<br>");

RequestDispatcher rd=

req.getRequestDispatcher("login.html");

ii
rd.include(req, res);

ath
}else {

Cookie ck = new Cookie("fName",ub.getfName());

ip
//Creating Cookie
Ma
res.addCookie(ck);//Adding Cookie to response

pw.println("Welcome User "+ub.getfName()+"<br>");

RequestDispatcher rd =
sh
req.getRequestDispatcher("link.html");

rd.include(req, res);
ate

}
nk

ProductBean.java
Ve

package test;
import java.io.*;
@SuppressWarnings("serial")
public class ProductBean implements Serializable{
private String code,name;
private float price;
private int qty;
public ProductBean() {}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPrice() {

ii
return price;
}

ath
public void setPrice(float price) {
this.price = price;
}
public int getQty() {
return qty;

ip
}
public void setQty(int qty) { Ma
this.qty = qty;
}

}
sh
RetrieveDAO.java

package test;
ate

import java.sql.*;

import java.util.*;
nk

public class RetrieveDAO {

public ArrayList<ProductBean> al = new ArrayList<ProductBean>();


Ve

public ArrayList<ProductBean> retrieve()

try {

Connection con = DBConnection.getCon();

//Accessing the Connection


PreparedStatement ps = con.prepareStatement

("select * from Product45");

ResultSet rs = ps.executeQuery();

while(rs.next())

ProductBean pb = new ProductBean();

ii
pb.setCode(rs.getString(1));

ath
pb.setName(rs.getString(2));

pb.setPrice(rs.getFloat(3));

ip
pb.setQty(rs.getInt(4));
Ma
al.add(pb);//Adding bean to ArrayList

}//end of loop

}catch(Exception e) {e.printStackTrace();}
sh
return al;

}
ate

ViewProductsServlet.java
nk

package test;

import java.io.*;
Ve

import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;

import javax.servlet.annotation.*;

@SuppressWarnings("serial")
@WebServlet("/view")

public class ViewProductsServlet extends HttpServlet{

protected void doGet(HttpServletRequest req,HttpServletResponse res)

throws ServletException,IOException{

PrintWriter pw = res.getWriter();

res.setContentType("text/html");

ii
Cookie c[] = req.getCookies();//Getting the Cookies

ath
if(c==null) {

pw.println("Session Expired...<br>");

ip
RequestDispatcher rd=
Ma
req.getRequestDispatcher("login.html");

rd.include(req, res);

}else {
sh
String fName = c[0].getValue();

pw.println("page of "+fName+"<br>");
ate

RequestDispatcher rd=

req.getRequestDispatcher("link.html");
nk

rd.include(req, res);

ArrayList<ProductBean> al = new RetrieveDAO().retrieve();


Ve

if(al.size()==0) {

pw.println("<br>Products Not Available...<br>");

}else {

Iterator<ProductBean> it = al.iterator();

while(it.hasNext())
{

ProductBean pb = (ProductBean)it.next();

pw.println("<br>"+pb.getCode()+"&nbsp&nbsp"+

pb.getName()+"&nbsp&nbsp"+pb.getPrice()+

"&nbsp&nbsp"+pb.getQty()+"<br>");

}//end of loop

ii
}//end of else

ath
}

ip
}

LogoutServlet.java

package test;
Ma
import java.io.*;
sh
import javax.servlet.*;

import javax.servlet.http.*;
ate

import javax.servlet.annotation.*;

@SuppressWarnings("serial")
nk

@WebServlet("/logout")

public class LogoutServlet extends HttpServlet{


Ve

protected void doGet(HttpServletRequest req,

HttpServletResponse res)throws ServletException,IOException{

PrintWriter pw = res.getWriter();

res.setContentType("text/html");

Cookie c[] = req.getCookies();


if(c==null) {

pw.println("Session Expired....<br>");

}else {

c[0].setMaxAge(0);//Cookie destroyed

pw.println("User Loggedout Successfully...<br>");

ii
RequestDispatcher rd=

ath
req.getRequestDispatcher("login.html");

rd.include(req, res);

ip
}

Layout:
Ma
sh
ate
nk
Ve
=================================================================

Assignment:

Construct Servlet Application using the following Layout:

DB Tables:

UserReg45(uname,pword,fname,lname,addr,mid,phno)

ii
AdminReg45(uname,pword,fname,lname,addr,mid,phno)

ath
BookDetails45(bcode,bname,bauthor,bprice,bqty)

ip
Ma
sh
ate
nk
Ve
Dt : 2/6/2022

Diagram:

ii
ip ath
Ma
=========================================================================

Dis-Advantage of Cookie is Session Tracking process:

=>Cookies are stored in WebBrowser to track the user,which means Cookies are
sh
browser dependent or Client dependent.
ate

=>If any changes occured in WebBrowser related to Cookies,then Cookie

related applications will not work.


nk

=====================================================================

*imp
Ve

(b)HttpSession:

=>'HttpSession' is an interface from javax.servlet.http package and which

is used in Session tracking process.

=>The following are some important methods from HttpSession:

public abstract javax.servlet.ServletContext getServletContext();


public abstract javax.servlet.http.HttpSessionContext getSessionContext();

public abstract void setAttribute(java.lang.String, java.lang.Object);

public abstract java.lang.Object getAttribute(java.lang.String);

public abstract void removeAttribute(java.lang.String);

public abstract java.util.Enumeration<java.lang.String> getAttributeNames();

ii
ath
public abstract void putValue(java.lang.String, java.lang.Object);

public abstract java.lang.Object getValue(java.lang.String);

ip
public abstract java.lang.String[] getValueNames();
Ma
public abstract void removeValue(java.lang.String);

public abstract void invalidate();


sh
public abstract boolean isNew();
ate

Note:

=>In Session tracking process we add attribute to HttpSession Object to


nk

tack the user.

=>we use getSession() method from 'HttpServletRequest' to create the


Ve

implementation object of 'HttpSession' interface.

Method Signature of getSession():

public abstract javax.servlet.HttpSession getSession(boolean);

public abstract javax.servlet.HttpSession getSession();


========================================================

ii
ip ath
Ma
sh
ate
nk
Ve
Dt : 3/6/2022

Layout:

ii
ip ath
Ma
sh
login.html

<!DOCTYPE html>
ate

<html>
<head>
<meta charset="ISO-8859-1">
nk

<title>Insert title here</title>


</head>
Ve

<body>
<form action="log" method="post">
UserName:<input type="text"
name="uname"><br>
PassWord:<input type="password"
name="pword"><br>
<input type="submit" value="Login">
<a href="register.html">NewUser?</a>
</form>
</body>
</html>
link.html

<!DOCTYPE html>
<html>

ii
<head>

ath
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>

ip
<body>
<a href="view">ViewProfile</a>
Ma
<a href="">EditProfile</a>
<a href="logout">Logout</a>
</body>
sh
</html>
DBConnection.java
ate

package test;
import java.sql.*;
nk

public class DBConnection {


private static Connection
Ve

con=null;//reference variable
private DBConnection() {}
static
{
try {
Class.forName("oracle.jdbc.driver.Orac
leDriver");
con =
DriverManager.getConnection

ii
("jdbc:oracle:thin:@localhost:1521:xe"

ath
,"system","manager");
}catch(Exception e)
{e.printStackTrace();}

ip
} Ma
public static Connection getCon()
{
return con;
}
sh
}
ate

LoginDAO.java

package test;
nk

import java.sql.*;

import javax.servlet.http.*;
Ve

public class LoginDAO {

public UserBean ub=null;

public UserBean login(HttpServletRequest req) {

try {

Connection con = DBConnection.getCon();


PreparedStatement ps = con.prepareStatement

("select * from UserReg45 where uname=? and pword=?");

ps.setString(1,req.getParameter("uname"));

ps.setString(2,req.getParameter("pword"));

ResultSet rs = ps.executeQuery();

if(rs.next()) {

ii
ub = new UserBean();//Bean Object

ath
ub.setuName(rs.getString(1));

ub.setpWord(rs.getString(2));

ub.setfName(rs.getString(3));

ip
ub.setlName(rs.getString(4));
Ma
ub.setAddr(rs.getString(5));

ub.setmId(rs.getString(6));

ub.setPhNo(rs.getLong(7));
sh
}

}catch(Exception e) {e.printStackTrace();}
ate

return ub;

}
nk

UserBean.java
Ve

package test;
import java.io.*;
@SuppressWarnings("serial")
public class UserBean implements
Serializable{
private String
uName,pWord,fName,lName,addr,mId;
private long phNo;
public UserBean() {}
public String getuName() {
return uName;
}

ii
public void setuName(String uName) {

ath
this.uName = uName;
}
public String getpWord() {

ip
return pWord; Ma
}
public void setpWord(String pWord) {
this.pWord = pWord;
}
sh
public String getfName() {
ate

return fName;
}
public void setfName(String fName) {
nk

this.fName = fName;
}
Ve

public String getlName() {


return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public String getmId() {

ii
return mId;

ath
}
public void setmId(String mId) {
this.mId = mId;

ip
} Ma
public long getPhNo() {
return phNo;
}
public void setPhNo(long phNo) {
sh
this.phNo = phNo;
ate

}
nk

LoginServlet.java
Ve

package test;

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import javax.servlet.annotation.*;

@SuppressWarnings("serial")
@WebServlet("/log")

public class LoginServlet extends HttpServlet{

protected void doPost(HttpServletRequest req,

HttpServletResponse res)throws ServletException,IOException{

UserBean ub = new LoginDAO().login(req);

PrintWriter pw = res.getWriter();

ii
res.setContentType("text/html");

ath
if(ub==null) {

pw.println("Invalid Login Process....<br>");

RequestDispatcher rd=

ip
req.getRequestDispatcher("login.html");
Ma
rd.include(req, res);

}else {

HttpSession hs = req.getSession();//Session Created


sh
hs.setAttribute("ubean",ub);//Adding attribute to Session

pw.println("Welcome User "+ub.getfName()+"<br>");


ate

RequestDispatcher rd =

req.getRequestDispatcher("link.html");
nk

rd.include(req, res);

}
Ve

web.xml

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


<web-app>
<welcome-file-list>
<welcome-file>login.html</welcome-
file>
</welcome-file-list>
</web-app>
ViewProfileServlet.java

package test;

import java.io.*;

ii
ath
import javax.servlet.*;

import javax.servlet.http.*;

import javax.servlet.annotation.*;

ip
@SuppressWarnings("serial")

@WebServlet("/view")
Ma
public class ViewProfileServlet extends HttpServlet{

protected void doGet(HttpServletRequest req,HttpServletResponse res)


sh
throws ServletException,IOException{

PrintWriter pw = res.getWriter();
ate

res.setContentType("text/html");

HttpSession hs = req.getSession(false);
nk

//Accessing existing Session

if(hs==null) {
Ve

pw.println("Session Expired...<br>");

RequestDispatcher rd =

req.getRequestDispatcher("login.html");

rd.include(req, res);

}else {

UserBean ub = (UserBean)hs.getAttribute("ubean");
pw.println("Page of "+ub.getfName()+"<br>");

RequestDispatcher rd=

req.getRequestDispatcher("link.html");

rd.include(req, res);

pw.println("<br>"+ub.getfName()+"&nbsp&nbsp"+

ub.getlName()+"&nbsp&nbsp"+ub.getAddr()+"&nbsp&nbsp"+

ii
ub.getmId()+"&nbsp&nbsp"+ub.getPhNo());

ath
}

ip
LogoutServlet.java Ma
package test;

import java.io.*;

import javax.servlet.*;
sh
import javax.servlet.http.*;

import javax.servlet.annotation.*;
ate

@SuppressWarnings("serial")

@WebServlet("/logout")
nk

public class LogoutServlet extends HttpServlet{

protected void doGet(HttpServletRequest req,HttpServletResponse res)


Ve

throws ServletException,IOException{

PrintWriter pw = res.getWriter();

res.setContentType("text/html");

HttpSession hs = req.getSession(false);

if(hs==null) {
pw.println("Session Expired...<br>");

}else {

hs.invalidate();//Session destroyed

pw.println("User Logged out Successfully...<br>");

RequestDispatcher rd=

ii
req.getRequestDispatcher("login.html");

ath
rd.include(req, res);

ip
=========================================================================
Ma
Assignment:

Update above application with EditProfile

=======================================================================
sh
ate
nk
Ve
Dt:4/6/2022

faq:

wt is the diff b/w

(i)getSession()

(ii)getSession(false)

(iii)getSession(true)

ii
ath
(i)getSession():

=>This getSession() method is used to create new Session object,if the

ip
Session Object is not available.
Ma
=>If available then getSession() method will access the existing session

object.
sh
(ii)getSession(false):

=>This getSession(false) method is used to access the existing session object


ate

if available,but it will not create new Session object if not available.


nk

(iii)getSession(true):

=>This getSession(true) method is used to create new Session object,if the


Ve

Session object is not available.

=>If available then getSession(true) method will access the existing session

object.

===========================================================================

(c)URL re-write:
=>The process of adding parameter-values to url-pattern is known as URL re-write.

=>using URL re-write process we pass information from one Servlet program to

another Servlet program part of tracking process.

syntax:

url-pattern?para=value&para=value&...

ii
ath
Note:

=>"?" symbol is the separator b/w url-pattern and parameters

ip
=>"&" symbol is the separator b/w parameters.

Ex Application:
Ma
DBConnection.java
sh
package test;
import java.sql.*;
public class DBConnection {
ate

private static Connection con=null;//reference variable


private DBConnection() {}
static
{
try {
nk

Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection
Ve

("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
}catch(Exception e) {e.printStackTrace();}
}
public static Connection getCon()
{
return con;
}
}
RetrieveDAO.java

package test;

import java.sql.*;

import javax.servlet.http.*;

public class RetrieveDAO {

public ProductBean pb=null;

ii
ProductBean retrieve(HttpServletRequest req)

ath
{

try {

ip
Connection con = DBConnection.getCon();
Ma
//Accessing the Connection

PreparedStatement ps = con.prepareStatement

("select * from Product45 where pcode=?");


sh
ps.setString(1,req.getParameter("pcode"));

ResultSet rs = ps.executeQuery();
ate

while(rs.next())

{
nk

pb = new ProductBean();

pb.setCode(rs.getString(1));
Ve

pb.setName(rs.getString(2));

pb.setPrice(rs.getFloat(3));

pb.setQty(rs.getInt(4));

}//end of loop

}catch(Exception e) {e.printStackTrace();}
return pb;

ProductBean.java

package test;
import java.io.*;
@SuppressWarnings("serial")
public class ProductBean implements Serializable{

ii
private String code,name;

ath
private float price;
private int qty;
public ProductBean() {}
public String getCode() {
return code;

ip
}
public void setCode(String code) {
Ma
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
sh
this.name = name;
}
public float getPrice() {
ate

return price;
}
public void setPrice(float price) {
this.price = price;
nk

}
public int getQty() {
return qty;
}
Ve

public void setQty(int qty) {


this.qty = qty;
}

input.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="first" method="post">
Enter the ProdCode:<input type="text" name="pcode"><br>
<input type="submit" value="RetrieveProduct">
</form>
</body>

ii
</html>

ath
FirstServlet.java

package test;

import java.io.*;

ip
import javax.servlet.*; Ma
import javax.servlet.http.*;

import javax.servlet.annotation.*;

@SuppressWarnings("serial")
sh
@WebServlet("/first")
ate

public class FirstServlet extends HttpServlet{

protected void doPost(HttpServletRequest req,HttpServletResponse res)

throws ServletException,IOException{
nk

PrintWriter pw = res.getWriter();
Ve

res.setContentType("text/html");

ProductBean pb = new RetrieveDAO().retrieve(req);

if(pb==null) {

pw.println("Invalid ProductCode...<br>");

RequestDispatcher rd=

req.getRequestDispatcher("input.html");
rd.include(req, res);

}else {

pw.println("<a href='second?code="+pb.getCode()

+"&name="+pb.getName()

+"&price="+pb.getPrice()

+"&qty="+pb.getQty()+"'>ViewProductDetails</a>");

ii
}

ath
}

ip
SecondServlet.java

package test;

import java.io.*;
Ma
import javax.servlet.*;
sh
import javax.servlet.http.*;

import javax.servlet.annotation.*;
ate

@SuppressWarnings("serial")

@WebServlet("/second")
nk

public class SecondServlet extends HttpServlet{

protected void doGet(HttpServletRequest req,HttpServletResponse res)


Ve

throws ServletException,IOException{

PrintWriter pw = res.getWriter();

res.setContentType("text/html");

pw.println("====ProductDetails====");

pw.println("<br>PCode:"+req.getParameter("code"));
pw.println("<br>PName:"+req.getParameter("name"));

pw.println("<br>PPrice:"+req.getParameter("price"));

pw.println("<br>PQty:"+req.getParameter("qty"));

web.xml

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

ath
<web-app>
<welcome-file-list>
<welcome-file>input.html</welcome-file>
</welcome-file-list>
</web-app>

ip
Diagram: Ma
sh
ate
nk
Ve

http://localhost:8082/Servlet_App8_URL_Re_Write/second?

code=A111

&name=Mouse
&price=1200.0

&qty=12

https://www.google.com/search?

ii
q=gmail

ath
&oq=

&aqs=chrome.0.35i39i362l8.1558847477j0j7

ip
&sourceid=chrome

&ie=UTF-8
Ma
=====================================================================
sh
Assignment:

Construct Servlet Application to send Book details from one Servlet program to
ate

another Servlet program using 'URL re-write process'

=======================================================================
nk
Ve
Dt : 6/6/2022

(d)Hidden form fields:

=>The process of declaring <input type="hidden"...> in <form> tag of HTML is

known as 'Hidden form field'.

=>The data which is available in hidden form filds are not visible to the

end user.

ii
=>In Session tracking process we can also take the support hidden form fields

ath
to transfer the information from one Servlet program to another Servlet program.

ip
syntax:

<form action="url-pattern"...>
Ma
<input type="hidden" value="alex" name="n">

...
sh
</form>
ate

Ex_program:

DBConnection.java
nk

package test;
import java.sql.*;
public class DBConnection {
Ve

private static Connection con=null;//reference variable


private DBConnection() {}
static
{
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection

("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
}catch(Exception e) {e.printStackTrace();}
}
public static Connection getCon()
{
return con;
}
}

RetrieveDAO.java

package test;

ii
import java.sql.*;

ath
import javax.servlet.http.*;

public class RetrieveDAO {

public ProductBean pb=null;

ip
ProductBean retrieve(HttpServletRequest req)
Ma
{

try {

Connection con = DBConnection.getCon();


sh
//Accessing the Connection
ate

PreparedStatement ps = con.prepareStatement

("select * from Product45 where pcode=?");


nk

ps.setString(1,req.getParameter("pcode"));

ResultSet rs = ps.executeQuery();
Ve

while(rs.next())

pb = new ProductBean();

pb.setCode(rs.getString(1));

pb.setName(rs.getString(2));

pb.setPrice(rs.getFloat(3));
pb.setQty(rs.getInt(4));

}//end of loop

}catch(Exception e) {e.printStackTrace();}

return pb;

ii
ProductBean.java

ath
package test;
import java.io.*;
@SuppressWarnings("serial")
public class ProductBean implements Serializable{

ip
private String code,name;
private float price; Ma
private int qty;
public ProductBean() {}
public String getCode() {
return code;
}
public void setCode(String code) {
sh
this.code = code;
}
public String getName() {
ate

return name;
}
public void setName(String name) {
this.name = name;
}
nk

public float getPrice() {


return price;
}
Ve

public void setPrice(float price) {


this.price = price;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
}

input.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

ii
<form action="first" method="post">

ath
Enter the ProdCode:<input type="text" name="pcode"><br>
<input type="submit" value="RetrieveProduct">
</form>
</body>
</html>

ip
FirstServlet.java Ma
package test;

import java.io.*;

import javax.servlet.*;
sh
import javax.servlet.http.*;
ate

import javax.servlet.annotation.*;

@SuppressWarnings("serial")
nk

@WebServlet("/first")

public class FirstServlet extends HttpServlet{


Ve

protected void doPost(HttpServletRequest req,HttpServletResponse res)

throws ServletException,IOException{

PrintWriter pw = res.getWriter();

res.setContentType("text/html");

ProductBean pb = new RetrieveDAO().retrieve(req);

if(pb==null) {
pw.println("Invalid ProductCode...<br>");

RequestDispatcher rd=

req.getRequestDispatcher("input.html");

rd.include(req, res);

}else {

pw.println("<form action='second' method='GET'>");

ii
pw.println

ath
("<input type='hidden' value='"+pb.getCode()+"' name='code'>");

pw.println

ip
("<input type='hidden' value='"+pb.getName()+"' name='name'>");

pw.println
Ma
("<input type='hidden' value='"+pb.getPrice()+"' name='price'>");

pw.println
sh
("<input type='hidden' value='"+pb.getQty()+"' name='qty'>");

pw.println
ate

("<input type='submit' value='ViewProductDetails'>");

pw.println("</form>");
nk

}
Ve

SecondServlet.java

package test;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import javax.servlet.annotation.*;

@SuppressWarnings("serial")

@WebServlet("/second")

public class SecondServlet extends HttpServlet{

protected void doGet(HttpServletRequest req,HttpServletResponse res)

ii
throws ServletException,IOException{

ath
PrintWriter pw = res.getWriter();

res.setContentType("text/html");

ip
pw.println("====ProductDetails====");
Ma
pw.println("<br>PCode:"+req.getParameter("code"));

pw.println("<br>PName:"+req.getParameter("name"));

pw.println("<br>PPrice:"+req.getParameter("price"));
sh
pw.println("<br>PQty:"+req.getParameter("qty"));

}
ate

web.xml
nk

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


<web-app>
<welcome-file-list>
Ve

<welcome-file>input.html</welcome-file>
</welcome-file-list>
</web-app>

=======================================================================

Assignment:

Construct Servlet Application to send Book details from one Servlet program to

another Servlet program using 'Hidden Form fields'


=======================================================================

ii
ip ath
Ma
sh
ate
nk
Ve
Dt : 7/6/2022

*imp

ServletContext:

=>ServletContext is an interface from javax.servlet package and which is

instantiated automatically when WebApplication is deployed(loaded) into Server.

=>This ServletContext object is loaded with Server information.

ii
=>we use getServletContext() method to access the reference of ServletContext

ath
object.

=>This getServletContext() method is available from ServlerRequest,

ip
GenericServlet,HttpSession and ServletConfig.

syntax:
Ma
ServletContext sct = req.getServletContext();
sh

=>we use <context-param> tag part of web.xml to initialize parameters to


ate

ServletContext object.
nk

syntax:

<web-app>
Ve

<context-param>

<param-name> name </param-name>

<param-value> value </param-value>

</context-param>

.
.

</web-app>

=>we use getInitParameter() method to access the initialized parameter from

ServletContext and ServletConfig objects.

ii
Note:

ath
=>Total WebApplication will have only one ServletContext object and the

information in ServletContext object can be used by all Servlet Programs of

ip
WebApplication.
Ma
-------------------------------------------------------------------

*imp

ServletConfig:
sh
=>ServletConfig is an interface from javax.servlet package and which is

instantiated automatically when Servlet program is loaded for execution.


ate

=>Every Servlet program in WebApplication wil have its own ServletConfig

object.
nk

=>This ServletConfig object is loaded with Servlet name.

=>we use getServletConfig() method to access the reference of ServletConfig


Ve

object.

=>This getServletConfig() method is available from GenericServlet.

syntax:

ServletConfig sc = this.getServletConfig();
=>we use <init-param> tag part of <servlet> to initialize parameters to

ServletConfig object.

syntax:

<web-app>

ii
<servlet>

ath
.

<init-param>

ip
<param-name> name </param-name>
Ma
<param-value> value </param-value>

</init-param>

</servlet>
sh
<servlet-mapping>

.
ate

</servlet-mapping>

.
nk

</web-app>
Ve

Ex Application:

input.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="dis" method="post">
Name:<input type="text" name="name"><br>
<input type="submit" value="Display">
</form>
</body>
</html>

web.xml

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


<web-app>

ii
<context-param>

ath
<param-name>a</param-name>
<param-value>2000</param-value>
</context-param>

<servlet>

ip
<servlet-name>DisplayServlet</servlet-name>
<servlet-class>test.DisplayServlet</servlet-class>
Ma
<init-param>
<param-name>b</param-name>
<param-value>3000</param-value>
</init-param>
</servlet>
<servlet-mapping>
sh
<servlet-name>DisplayServlet</servlet-name>
<url-pattern>/dis</url-pattern>
</servlet-mapping>
ate

<welcome-file-list>
<welcome-file>input.html</welcome-file>
</welcome-file-list>
nk

</web-app>

DisplayServlet.java
Ve

package test;

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

@SuppressWarnings("serial")
public class DisplayServlet extends HttpServlet{

protected void doPost(HttpServletRequest req,HttpServletResponse res)

throws ServletException,IOException{

PrintWriter pw = res.getWriter();

res.setContentType("text/html");

pw.println("User : "+req.getParameter("name"));

ii
pw.println("<br>====ServletContext=====");

ath
ServletContext sct = req.getServletContext();

//Accessing Context object reference

ip
pw.println("<br>ServerInfo:"+sct.getServerInfo());
Ma
pw.println("<br>ContextValue:"+sct.getInitParameter("a"));

pw.println("<br>====ServletConfig====");

ServletConfig sc = this.getServletConfig();
sh
//Accessing Config Object

pw.println("<br>ServletName:"+sc.getServletName());
ate

pw.println("<br>ConfigValue:"+sc.getInitParameter("b"));

}
nk

Diagram of Object Layout:


Ve
ii
ath
=====================================================================

ip
Ma
sh
ate
nk
Ve
Dt : 8/6/2022

Summary of Objects from Servlet Programming:

1.ServletContext

2.ServletConfig

3.ServletRequest/HttpServletRequest

4.ServletResponse/HttpServletResponse

ii
5.PrintWriter

ath
6.HttpSession

7.Cookie

ip
8.Java Beans

9.DAO(Data Access Object)

10.JCF(Java Collection Framework) objects


Ma
====================================================================
sh
faq:

wt is the diff b/w


ate

(i)ServletContext

(ii)ServletConfig
nk

(i)ServletContext:
Ve

=>ServletContext is instantiated automatically when WebApp is deployed into

Server and which will hold Server information.

=>Only one ServletContext object is created for WebApp.

(ii)ServletConfig:
=>ServletConfig is instantiated automatically when Servlet program is loaded

for execution and which will hold Servlet name.

=>Every Servlet program will have its own ServletConfig object.

=========================================================================

faq:

wt is the diff b/w

ii
(i)<contex-param>

ath
(ii)<init-param>

ip
(i)<contex-param>:
Ma
<context-param> tag is used to initialize parameters to ServletContext object.

(ii)<init-param>:
sh
<init-param> tag is the Sub-tag of <servlet> tag and which is used to

initialize parameters to ServletConfig object.


ate

============================================================================

faq:
nk

wt is the diff b/w

(i)getParameter()
Ve

(ii)getInitParameter()

(i)getParameter():

=>getParameter() method is used to read parameters from the request object.


(ii)getInitParameter():

=>getInitParameter() method is used to read initialized parameters from the

ServletContext and ServletConfig objects.

============================================================================

*imp

Filters in Servlet Programming:

ii
=>Filter is a Pre-Processing component before Servlet program.

ath
=>Filter and Servlet programs are executed with same url-pattern.

=>In the process of execution Filter programs will have highest priority in

ip
execution than Servlet programs

Diagram:
Ma
sh
ate
nk
Ve

Advantage of Filters:

1.Using Filter we can perform Authentication process

2.Using Filter we can perform Authorization process


3.Using Filter we can perform data conversion

4.Using Filter we can perform data compression

=======================================================================

Note:

=>The following programming components are used in Constructing Filter programs:

ii
1.Filter

ath
2.FilterChain

3.FilterConfig

ip
1.Filter:
Ma
=>Filter is an interface from javax.servlet package and which is implemented

to filter program.
sh
=>The following are the Life-Cycle methods from 'Filter':
ate

public void init(javax.servlet.FilterConfig)

throws javax.servlet.ServletException;
nk

public abstract void doFilter(javax.servlet.ServletRequest,

javax.servlet.ServletResponse, javax.servlet.FilterChain)
Ve

throws java.io.IOException, javax.servlet.ServletException;

public void destroy();

2.FilterChain:
=>FilterChain is an interface from javax.servlet package and which is

instantiated automatically while doFilter() method execution.

=>This FilterChain will have the following doFilter() method to link the

Servlet program in execution process.

public abstract void doFilter(javax.servlet.ServletRequest,

ii
javax.servlet.ServletResponse) throws java.io.IOException,

ath
javax.servlet.ServletException;

ip
3.FilterConfig:
Ma
=>FilterConfig is an interface from javax.servlet package and which is

instantiated automatically when filter program loaded for execution and


sh
FilterConfig will hold the filter name.

=>The following are the methods from FilterConfig:


ate

public abstract java.lang.String getFilterName();


nk

public abstract javax.servlet.ServletContext getServletContext();

public abstract java.lang.String getInitParameter(java.lang.String);


Ve

public abstract java.util.Enumeration<java.lang.String>

getInitParameterNames();

-------------------------------------------------------------------------
Dt : 9/6/2022

Note:

=>we use the following tags part of web.xml to execute filter program:

<web-app>

ii
<filter>

ath
<filter-name> name </filter-name>

<filter-class> class </filter-class>

ip
<init-param>

<param-name>name</param-name>

<param-value>value</param-value>
Ma
</init-param>
sh
</filter>

<filter-mapping>
ate

<filter-name>name</filter-name>

<url-pattern>/url-pattern</url-pattern>
nk

</filter-mapping>

</web-app>
Ve

=========================================================================

Ex_Application-1:

login.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="log" method="post">
UserName:<input type="text" name="uname"><br>
PassWord:<input type="password" name="pword"><br>
<input type="submit" value="Login">
<a href="register.html">NewUser?</a>
</form>

ii
</body>
</html>

ath
DBConnection.java

package test;
import java.sql.*;

ip
public class DBConnection {
private static Connection con=null;//reference variable
Ma
private DBConnection() {}
static
{
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection
sh
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
}catch(Exception e) {e.printStackTrace();}
ate

}
public static Connection getCon()
{
return con;
nk

}
}
Ve

LoginDAO.java

package test;

import java.sql.*;

import javax.servlet.*;

public class LoginDAO {


public String fName=null;

public String login(ServletRequest req) {

try {

Connection con = DBConnection.getCon();

PreparedStatement ps = con.prepareStatement

("select * from UserReg45 where uname=? and pword=?");

ii
ps.setString(1,req.getParameter("uname"));

ath
ps.setString(2,req.getParameter("pword"));

ResultSet rs = ps.executeQuery();

ip
if(rs.next()) {
Ma
fName = rs.getString(3);

}catch(Exception e) {e.printStackTrace();}
}

return fName;
sh
}

}
ate

LoginFilter.java

package test;
nk

import java.io.*;

import javax.servlet.*;
Ve

import javax.servlet.annotation.*;

@WebFilter("/log")

public class LoginFilter implements Filter{

public void doFilter(ServletRequest req,ServletResponse res,

FilterChain chain)throws ServletException,IOException{


PrintWriter pw = res.getWriter();

res.setContentType("text/html");

String fName = new LoginDAO().login(req);

if(fName==null) {

pw.println("Invalid Login process...<br>");

RequestDispatcher rd =

ii
req.getRequestDispatcher("login.html");

ath
rd.include(req, res);

}else {

ip
req.setAttribute("fname", fName);

}
Ma
chain.doFilter(req, res);//linking Servlet_program

}
sh
}

WelcomeServlet.java
ate

package test;

import java.io.*;
nk

import javax.servlet.*;

import javax.servlet.http.*;
Ve

import javax.servlet.annotation.*;

@SuppressWarnings("serial")

@WebServlet("/log")

public class WelcomeServlet extends HttpServlet{

protected void doPost(HttpServletRequest req,HttpServletResponse res)


throws ServletException,IOException{

PrintWriter pw = res.getWriter();

res.setContentType("text/html");

String name = (String)req.getAttribute("fname");

pw.println("Login Successfull...<br>");

pw.println("Welcome User "+name);

ii
}

ath
}

web.xml

ip
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
Ma
</web-app>

Diagram:
sh
ate
nk
Ve

========================================================================

Dt : 11/6/2022

Filter_program-2:
Application to demonstrate FilterConfig.

input.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="dis" method="post">

ii
UserName:<input type="text" name="uname"><br>

ath
<input type="submit" value="Display">
</form>
</body>
</html>

ip
web.xml

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


<web-app>
<filter>
Ma
<filter-name>DisplayFilter</filter-name>
<filter-class>test.DisplayFilter</filter-class>
<init-param>
sh
<param-name>a</param-name>
<param-value>3000</param-value>
</init-param>
ate

</filter>
<filter-mapping>
<filter-name>DisplayFilter</filter-name>
<url-pattern>/dis</url-pattern>
</filter-mapping>
nk

<welcome-file-list>
<welcome-file>input.html</welcome-file>
</welcome-file-list>
Ve

</web-app>

DisplayFilter.java

package test;

import java.io.*;

import javax.servlet.*;
public class DisplayFilter implements Filter{

public FilterConfig fc=null;//Instance Variable

public void init(FilterConfig fc)throws ServletException{

this.fc=fc;

public void doFilter(ServletRequest req,ServletResponse res,

ii
FilterChain chain)throws ServletException,IOException{

ath
PrintWriter pw = res.getWriter();

res.setContentType("text/html");

ip
pw.println("UserName:"+req.getParameter("uname"));
Ma
pw.println("<br>====FilterConfig====");

pw.println("<br>FilterName:"+fc.getFilterName());

pw.println("<br>FilterValue:"+fc.getInitParameter("a"));
sh
}

}
ate

Diagram:
nk
Ve
ii
ip ath
Ma
========================================================================
sh
faq:
ate

wt is the diff b/w

(i)ServletConfig

(ii)FilterConfig
nk
Ve

(i)ServletConfig:

=>ServletConfig is instantiated automatically when the Servlet program is

loaded for execution.

=>ServletConfig object will hold Servlet name.

(ii)FilterConfig:
=>FilterConfig is instantiated automatically when the Filter program loaded

for execution.

=>FilterConfig object will hold Filter name

================================================================

Note:

=>In realtime filters are used in Security and protection layer.

ii
================================================================

ip ath
Ma
sh
ate
nk
Ve
Dt : 14/6/2022

*imp

Listeners in Servlet Programming:

=>Listerners are the components executed background to Servlet Objects and

which respond to the events(actions) performed on Servlet Objects.

ii
Note:

ath
=>when event(action) is performed on Servlet object deligated to Listener and

the Listener will execute related method to handle the event,is known as

ip
Event-Delegation-Model.

Diagram:
Ma
sh
ate
nk
Ve

------------------------------------------------------------------

=>we can have listeners to the following Servlet objects:

1.ServletContext

2.ServletRequest
3.HttpSession

1.ServletContext:

Event_Class : ServletContextEvent

Event_Listener : ServletContextListener

ii
methods :

ath
public void contextInitialized(javax.servlet.ServletContextEvent)

public void contextDestroyed(javax.servlet.ServletContextEvent)

ip
2.ServletRequest:
Ma
Event_Class : ServletRequestEvent
sh
Event_Listener : ServletRequestListener

methods :
ate

public void requestInitialized(javax.servlet.ServletRequestEvent)

public void requestDestroyed(javax.servlet.ServletRequestEvent)


nk

3.HttpSession:
Ve

Event_Class : HttpSessionEvent

Event_Listener : HttpSessionListener

methods :

public void sessionCreated(javax.servlet.http.HttpSessionEvent)


public void sessionDestroyed(javax.servlet.http.HttpSessionEvent)

============================================================================

Ex_Program : Application to demonstrate Listeners in Servlet programming

(Update HttpSession application with following Listeners)

ContextListener.java

ii
package test;

ath
import javax.servlet.*;

import javax.servlet.annotation.*;

ip
@WebListener
Ma
public class ContextListener implements ServletContextListener

public void contextInitialized(ServletContextEvent sce) {


sh
System.out.println("Contect Object Initialized...");

}
ate

public void contextDestroyed(ServletContextEvent sce) {

System.out.println("Context Object Destroyed...");


nk

}
Ve

RequestListener.java

package test;

import javax.servlet.*;

import javax.servlet.annotation.*;

@WebListener
public class RequestListener implements ServletRequestListener{

public void requestInitialized(ServletRequestEvent sre) {

System.out.println("Request object initialized...");

public void requestDestroyed(ServletRequestEvent sre) {

System.out.println("Request Object destroyed...");

ii
}

ath
}

SessionListener.java

ip
package test;

import javax.servlet.http.*;

import javax.servlet.annotation.*;
Ma
@WebListener
sh
public class SessionListener implements HttpSessionListener,

HttpSessionAttributeListener{
ate

public void sessionCreated(HttpSessionEvent hse) {

System.out.println("Session Created....");
nk

public void sessionDestroyed(HttpSessionEvent hse) {


Ve

System.out.println("Session Destroyed...");

public void attributeAdded(HttpSessionBindingEvent hsbe) {

System.out.println("Attribute Added to Session...");

}
public void attributeRemoved(HttpSessionBindingEvent hsbe) {

System.out.println("Attribute removed from Session..");

========================================================================

faq:

ii
Types of Listeners in Servlet Programming"

ath
=>Listeners in Servlet programming are categorized into three types:

1.Application Level Listener

ip
2.Request Level Listener

3.Session Level Listener


Ma
1.Application Level Listener:
sh
=>The process of adding Listener to the ServletContext object is

known as Application Level Listener.


ate

2.Request Level Listener:


nk

=>The process of adding Listener to the ServletRequest object is

known as Request Level Listener.


Ve

3.Session Level Listener:

=>The process of adding Listener to the HttpSession object is known

as Session Level Listener.

======================================================
structure of web.xml from Servlet Programming:

<web-app>

<context-param></context-param>

<listener>

Listener_Class_name

ii
</listener>

ath
<servlet>

<servlet-name></servlet-name>

ip
<servlet-class></servlet-class>

<init-param></init-param>

</servlet>
Ma
<servlet-mapping>
sh
<servlet-name></servlet-name>

<url-pattern></url-pattern>
ate

</servlet-mapping>

<filter>
nk

<filter-name></filter-name>

<filter-class></filter-class>
Ve

<init-param></init-param>

</filter>

<filter-mapping>

<filter-name></filter-name>

<url-pattern></url-pattern>
</filter-mapping>

<welcome-file-list>

<welcome-file></welcome-file>

</welcome-file-list>

</web-app>

ii
ip ath
Ma
sh
*imp
ate

Annotations in Servlet Programming:

define Annotation?
nk

=>The tag based information which is added to the programming


Ve

component like class,Interface,method and variable is known as

annotation.

=>These Annotations are represented using "@" symbol.

=>These Annotations will specify the information to the compiler

at compilation stage or Execution controls at execution stage.


Exp:

@ Override

@ SuppressWarnings("unchecked")

@ SuppressWarnings("rawtypes")

ii
ath
=>The following are some important annotations used in Servlet

programming:

ip
(a)@ WebServlet

(b)@ WebFilter

(c)@ WebInitParam
Ma
(d)@ WebListener
sh

(a)@ WebServlet:
ate

=>This '@ WebServlet' is declared to the ServletProgram and used

for identifying Servlet program in execution process.


nk

(b)@ WebFilter:
Ve

=>This '@ WebFilter' is declared to FilterProgram and used for

identifying Filter program in execution process.

(c)@ WebInitParam:

=>This '@ WebInitParam' is used to initialize the parameters with


ServletConfig and FilterConfig objects.

(d)@ WebListener:

=>This '@ WebListener' is declared to the ListenerProgram and used

for identifying listener program in execution process.

--------------------------------------

ii
Note:

ath
=>When we use annotations in Servlet programming,the Servlet programs

can be executed without depending on web.xml mapping file.

ip
=>All the annotations related to ServletProgramming are available

from "javax.servlet.annotation" package.


Ma
=========================================================================

Dt : 15/6/2022
sh
faq:

define Servlet Collaboration?


ate

=>The process of exchanging the information among Servlet programs is known as

Servlet Collaboration.
nk

=>Servlet Collaboration can be done in two ways:


Ve

(i)Using 'RequestDispatcher'

=>forward()

=>include()

(ii)Using 'sendRedirect()' method


define sendRedirect()?

=>sendRedirect() method is avialble from 'HttpServletResponse' and which is used

to send information to another servlet program in communication process.

=>In this process another Servlet program may be in same WebApp or diff WebAppl.

ii
Method Signature:

ath
public abstract void sendRedirect(java.lang.String) throws java.io.IOException;

ip
Ex:

WebApp-1 : TestApp1
Ma
input.html
sh
<!DOCTYPE html>
<html>
<head>
ate

<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="first" method="post">
nk

UserName:<input type="text" name="uname"><br>


MailId:<input type="text" name="mid"><br>
<input type="submit" value="Display">
Ve

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

FirstServlet.java

package test;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import javax.servlet.annotation.*;

@SuppressWarnings("serial")

@WebServlet("/first")

public class FirstServlet extends HttpServlet{

protected void doPost(HttpServletRequest req,HttpServletResponse res)

ii
throws ServletException,IOException{

ath
String uName = req.getParameter("uname");

String mId = req.getParameter("mid");

ip
res.sendRedirect("http://localhost:8082/TestApp2/second?uname="+

}
uName+"&mid="+mId);
Ma
}
sh
web.xml

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


ate

<web-app>
<welcome-file-list>
<welcome-file>input.html</welcome-file>
</welcome-file-list>
</web-app>
nk

WebApp-2 : TestApp2
Ve

SecondServlet.java

package test;

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import javax.servlet.annotation.*;
@SuppressWarnings("serial")

@WebServlet("/second")

public class SecondServlet extends HttpServlet{

protected void doGet(HttpServletRequest req,HttpServletResponse res)

throws ServletException,IOException{

PrintWriter pw = res.getWriter();

ii
res.setContentType("text/html");

ath
pw.println("====SecondServlet====");

pw.println("<br>Name:"+req.getParameter("uname"));

ip
pw.println("<br>MailId:"+req.getParameter("mid"));

}
Ma
}
sh
http://localhost:8082/TestApp2/second?uname=Alex&[email protected]

-----------------------------------------------------------------------
ate

faq:

wt is the diff b/w


nk

(i)forward() method

(ii)sendRedirect() method
Ve

=>when we use forward() method,then the same request is forwarded to next

servlet program.

=>when we use sendRedirect() method then new requset is generated from the

WebBrowser and forwarded to next servlet program.


--------------------------------------------------------------------------

faq:

define Servlet Life-Cycle?

=>Servlet Life-Cycle demonstrates different states of Servlet program from

Starting of servlet program execution to ending of Servlet program execution.

1.Loading process

ii
2.Instantiation proccess

ath
3.Initialization process

4.Request handling process

ip
5.Destroying process

1.Loading process:
Ma
=>The process of identifying the servlet program based on url-pattern and
sh
loading onto WebContatiner is known as Loading prrocess.

Note:
ate

=>we can have url-pattern in

(i)Annotation
nk

(ii)web.xml
Ve

2.Instantiation proccess:

=>When Servlet program loaded onto WebContainer it is automatically instantiated

known as Instantiation processs.

=>After instantiation process we can find the following Life-Cycle methods:

Genericservlet
(a)init()

(b)service()

(c)destroy()

HttpServlet

(a)init()

(b)doPost()/doGet()/service()

ii
(c)destroy()

ath
Filter

(a)init()

ip
(b)doFilter()

faq:
(c)destroy()
Ma
define Life-Cycle methods?
sh
=>The methods which are executed automatically in same order are known as

Life-Cycle methods.
ate

3.Initialization process:
nk

=>The process of making the programming components ready for execution is known as

Initialization process.
Ve

=>we use init() method to perform initialization.

Note:

=>Through Initialization process we can make Bean objects and DAO objects ready

for execution.

=>This initialization process is performed only once.


4.Request handling process:

=>The process of taking the request and providing the response is known as

Request Handling process.

=>we use service()/doPost()/doGet()/doFilter() methods to perform Request

Handling process.

Note:

ii
=>In Multi-User Applications,

ath
=>init() method is executed only once,but doPost()/doGet()/service() methods

are executed for all the multiple Users.

ip
5.Destroying process:
Ma
=>The process of closing or destroying the resources after execution is known

as Destroying process.
sh
=>we use destroy() method to perform destroying process.

=============================================================================
ate

Summary of Objects from JDBC:

1.Connection Object
nk

2.Statement Object

3.PreparedStatement Object
Ve

4.CallableStatement Object

5.NonScrollable ResultSet Object

6.Scrollable ResultSet object

7.DatabaseMetaData object

8.ParameterMetaData object
9.ResultSetMetaData object

10.RowSet Object

(a)JdbcRowSet

(b)CachedRowSet

=>WebRowSet

(i)FilteredRowSet

ii
(ii)JoinRowset

ath
*

11.Connection Pooling Object

ip
=>Vector<E> Object
Ma
Summary of Objects from Servlet Programming:
sh
1.ServletContext object

2.ServletConfig object
ate

3.ServletRequest/HttpServletRequest object

4.ServletResponse/HttpServletResponse object
nk

5.PrintWriter object

6.Cookie object
Ve

7.HttpSession object

8.Bean class object

9.DAO Layer objects

10.JCF object
==============================================================================
==

*imp

JSP Programming:(Unit-3)

=>JSP Stands for 'Java Server Page' and which is response from

WebApplication.

ii
=>JSP is tag based programming language and which is more easy when

ath
compared to Servlet programming.

=>Programs in JSP are saved with (.jsp) as an extention.

ip
=>JSP programs are combination of both HTML code and Java Code.

=>JSP provides the following tags to write JavaCode part of JSP


Ma
programs:

1.Scripting tags

=>Scriptlet tag
sh
=>Expression tag
ate

=>Declarative tag

2.Directive tags
nk

=>page

=>include
Ve

=>taglib

3.Action tags

=>jsp:include

=>jsp:forward

=>jsp:param
=>jsp:useBean

=>jsp:setProperty

=>jsp:getProperty

Dt : 16/6/2022

1.Scripting tags:

ii
=>Scripting tags are used to write JavaCode part of JSP programs.

ath
=>Scripting tags are categorized into the following:

(a)Scriptlet tag

ip
(b)Expression tag

(c)Declarative tag
Ma
(a)Scriptlet tag:
sh
=>Scriptlet tag is used to write normal JavaCode part of JSP programs
ate

syntax:

<% ---JavaCode--- %>


nk
Ve

(b)Expression tag:

=>Expression tag is used to assign the value to variable or which is

used to display the data to the WebBrowser.

syntax:
<%= expression %>

(c)Declarative tag:

=>Declarative tag is used to declare variables and methods in JSP programs.

ii
syntax:

ath
<%! variables;methods %>

ip
=======================================================================

2.Directive tags:
Ma
=>The tags which are used to specify the directions in translation

process are known as Directive Tags.


sh

The following are the types of Directive tags:


ate

(a)page

(b)include
nk

(c)taglib
Ve

(a)page:

=>'page' directive tag specifies the translator to add the related

attribute to current JSP page.


syntax:

<%@ page attribute="value" %>

exp:

<%@ page import="java.util.*"%>

ii
List of attributes:

ath
1.import

ip
2.contentType

3.extends

4.info
Ma
5.buffer
sh
6.language

7.isELIgnored
ate

8.isThreadSafe

9.autoFlush
nk

10.session

11.pageEncoding
Ve

12.errorPage

13.isErrorPage

-----------------------------------------------------

(b)include:

=>'include' directive tag specifies the file to be included to current


JSP page.

syntax:

<%@ include file="file-name"%>

Exp:

ii
<%@ include file="input.html" %>

ath
-----------------------------------------------------

ip
(c)taglib:
Ma
=>'taglib' directive tag specifies to add specified url to current

JSP page and which is used part of EL(Expression Lang) and JSTL

(JSP Standard Tag Lib).


sh

syntax:
ate

<%@ taglib url="urloftaglib" prefix="prefixoftaglib"%>

===============================================
nk

Exp program1:

JSP Application to calculate factorial of given number.


Ve

Note:

=>JSP files are created part of WebContent.

input.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="Display.jsp" method="post">
Enter the Value:<input type="text" name="v"><br>
<input type="submit" value="Factorial">
</form>
</body>
</html>

ii
Display.jsp

ath
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
errorPage="Error.jsp"%>

ip
<!DOCTYPE html>
<html> Ma
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%!
sh
int fact;
int factorial(int n)
{
ate

fact=1;
for(int i=n;i>=1;i--)
{
fact=fact*i;
nk

}
return fact;
}
%>
Ve

<%
int val = Integer.parseInt(request.getParameter("v"));
int result = factorial(val);
out.println("Factorial : "+result+"<br>");
%>
<%@include file="input.html"%>
</body>
</html>

Errorr.jsp
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
isErrorPage="true"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

ii
<%
out.println("Enter only Integer value...<br>");

ath
%>
<%= exception %>
<br>
<%@include file="input.html"%>
</body>

ip
</html>

web.xml

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


Ma
<web-app>
<welcome-file-list>
<welcome-file>input.html</welcome-file>
sh
</welcome-file-list>
</web-app>
ate

Execute the application as follows:

http://localhost:8082/JSPApp1
nk

Diagram:
Ve
ii
ath
=======================================================================

ip
=>The following are the implicit objects of JSP:
Ma
application - javax.servlet.ServletContext

config - javax.servlet.ServletConfig
sh
request - javax.servlet.http.HttpServletRequest
ate

response - javax.servlet.http.HttpServletResponse

out - javax.servlet.jsp.JspWriter

session - javax.servlet.http.HttpSession
nk

exception - java.lang.Throwable
Ve

page - java.lang.Object

pageContext - javax.servlet.jsp.PageContext

=============================================================

3.Action tags:

=>Action Tags are used to include some basic actions like inserting
some other page resources ,forwarding the request to another page,

creating or locating the JavaBean instances and,setting and retriving

the bean properties in JSP pages.

Note:

=>These action tags are used in Execution process at runtime.

ii
------------------------------------------------------

ath
=>The following are some Important action tags available in JSP:

ip
1.<jsp:include>

2.<jsp:forward>

3.<jsp:param>
Ma
4.<jsp:useBean>
sh
5.<jsp:setProperty>

6.<jsp:getProperty>
ate
nk

1.<jsp:include> :
Ve

=>This action tag allows to include a static or dynamic resource

such as HTML or JSP specified by a URL to be included in the current

JSP while processing request.

=>If the resource is static then its content is included in the JSP

page.
=>If the resource is dynamic then its result is included in the JSP

page.

syntax:

<jsp:include attributes>

<---Zero or more jsp:param tags--->

ii
</jsp:include>

ath
attributes of include tag:

ip
*imp
Ma
page : Takes a relative URL,which locates the resource

to be included in the JSP page.


sh
<jsp:include page="/Header.html"/>

<jsp:include page="<%=mypath%>"/>
ate

flush : Takes true or false,which indicates whether or not the buffer


nk

needs to be flushed before including resource.


Ve

2.<jsp:forward>:

=> This action tag forwards a JSP request to another resource and

which can be either static or dynamic.

=>If the resource is dynamic then we can use a jsp:param tag to pass
name and value of the parameter to the resource.

sntax:

<jsp:forward attributes>

<-- Zero or more jsp:param tags-->

</jsp:forward>

ii
Exp:

ath
<jsp:forward page="/Header.html"/>

<jsp:forward page="<%=mypath%>"/>

ip
3.<jsp:param>:
Ma
This action tag is used to hold the parameter with value and which

is to be forwarded to the next resource.


sh

syntax:
ate

<jsp:param name="paramName" value="paramValue"/>

====================================================
nk

4.<jsp:useBean>:
Ve

=>This tag is used to instantiate a JavaBean,or locate an existing

bean instance and assign it to a variable name(id).

syntax:
<jsp:useBean attributes>

<!-optional body content--->

</jsp:useBean>

Attributes of <jsp:useBean> tag:

(a)id

ii
(b)scope

ath
(c)class

(d)beanName

ip
(e)type

(a)id:
Ma
=>which represents the variable name assigned to id attribute of
sh
<jsp:useBean> tag and which holds the reference of JavaBean instance.
ate

(b)scope:

=>which specifies the scope in which the bean instance has to be


nk

created or located.
Ve

scope can be the following:

(i)page scope : within the JSP page,until the page sends response.

(ii)request scope : JSP page processing the same request until a JSP sends response.

(iii)session scope - Used with in the Session.

(iv)application scope - Used within entire web application.


*imp

(c)class :

=>The class attribute takes the qualified class name to create a

bean instance.

ii
(d)beanName :

ath
=>The beanName attribute takes a qualified class name.

ip
(e)type :
Ma
=>The "type" attribute takes a qualified className or interfaceName,

which can be the classname given in the class or beanName attribute or

its super type.


sh

5.<jsp:setProperty>:
ate

=>This action tag sets the value of a property in a bean, using

the bean's setter methods.


nk

Types of attributes:
Ve

(a)name

(b)property

(c)value

(d)param
(a)name:

=>The name attribute takes the name of already existing bean as a

reference variable to invoke the setter method.

(b)property:

=>which specifies the property name that has to be set,and

ii
specifies the setter method that has to be invoked.

ath
(c)value:

ip
=>The value attribute takes the value that has to be set to the

specified bean property.


Ma
(d)param:
sh
=>which specify the name of the request parameter whose value to be

assigned to bean property.


ate

6.<jsp:getProperty>:
nk

=>This action tag gets the value of a property in a bean by using

the bean's getter method and writes the value to the current JspWriter.
Ve

Types of attributes:

(a)name

(b)property
(a)name:

=>The name attribute takes the reference variable name on which we

want to invoke the getter method.

(b)property:

=>which gets the value of a bean property and invokes the getter

ii
method of the bean property.

ath
-------------------------------------

ip
The following are some rare used Actions tags:

7.< jsp:plugIn >:


Ma
The <jsp:plugin> action tag provide easy support for including a
sh
java applet in the client Web browser, using a built-in or

downloaded java plug-in.


ate

Syntax:
nk

<jsp:plugin attributes>

<!-optionally one jsp:params or jsp:fallback tag-


Ve

</jsp:plugin>

8. < jsp:fallBack >

The <jsp:fallback> action tag allows us to specify a text message to

be displayed if the required plug-in cannot run and this action tag
must be used as a child tag with the <jsp:plugin> action tag.

Syntax:

<jsp:fallback>

Test message that has to be displayed if the plugin cannot be started

</jsp:fallback>

ii
ath
9. < jsp:params >

The <jsp:params> action tag sends the parameters that we want to

ip
pass to an applet.

Syntax:
Ma
<jsp:params>
sh
<!-one or more jsp:param tags---

</jsp:params>
ate

=======================================================================
nk

Exp application_2:

JSP Application to demonstrate Login process?


Ve

(Using <jsp:forward> <jsp:include> <jsp:param>

DBConnection.java

package test;
import java.sql.*;
public class DBConnection {
private static Connection con=null;//reference variable
private DBConnection() {}
static
{
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection

("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
}catch(Exception e) {e.printStackTrace();}
}
public static Connection getCon()

ii
{
return con;

ath
}
}

LoginDAO.java

ip
package test; Ma
import java.sql.*;

import javax.servlet.http.*;

public class LoginDAO {


sh
public String fName=null;
ate

public String login(HttpServletRequest req) {

try {
nk

Connection con = DBConnection.getCon();

PreparedStatement ps = con.prepareStatement
Ve

("select * from UserReg45 where uname=? and pword=?");

ps.setString(1,req.getParameter("uname"));

ps.setString(2,req.getParameter("pword"));

ResultSet rs = ps.executeQuery();

if(rs.next()) {
fName = rs.getString(3);

}catch(Exception e) {e.printStackTrace();}

return fName;

ii
login.html

ath
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">

ip
<title>Insert title here</title>
</head> Ma
<body>
<form action="LoginJSP.jsp" method="post">
UserName:<input type="text" name="uname"><br>
PassWord:<input type="password" name="pword"><br>
<input type="submit" value="Login">
<a href="register.html">NewUser?</a>
sh
</form>
</body>
</html>
ate

LoginJSP.jsp

<%@ page language="java"


contentType="text/html; charset=ISO-8859-1"
nk

pageEncoding="ISO-8859-1"
import="test.*"%>
<!DOCTYPE html>
Ve

<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String fName = new LoginDAO().login(request);
if(fName==null){
out.println("Invalid Login process...<br>");
%>
<jsp:include page="login.html"/>
<%
}else{
%>
<jsp:forward page="WelcomeJSP.jsp">
<jsp:param value="<%=fName %>" name="fname"/>
</jsp:forward>
<%
}
%>

ii
</body>
</html>

ath
WelcomeJSP.jsp

<%@ page language="java"


contentType="text/html; charset=ISO-8859-1"

ip
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html> Ma
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
sh
<%
String fName = request.getParameter("fname");
out.println("Wlcome User : "+fName+"<br>");
ate

%>
</body>
</html>
nk

web.xml

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


<web-app>
Ve

<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
</web-app>

diagram:
ii
ip ath
Ma
----------------------------------------------------------------------

Assignment:

Update above application by displaying the complete user details


sh
--------------------------------------------------------------------
ate
nk
Ve
--------------------------------------------------------------------

Dt : 17/6/2022

Exp program_3:

JSP Application to demostrate accessing bean object.

(Using <jsp:useBean> <jsp:setProperty> <jsp:getProperty>)

ii
ProductBean.java(Bean class)

ath
package test;
import java.io.*;
@SuppressWarnings("serial")
public class ProductBean implements Serializable{

ip
private String code,name;
private float price; Ma
private int qty;
public ProductBean() {}
public String getCode() {
return code;
}
public void setCode(String code) {
sh
this.code = code;
}
public String getName() {
ate

return name;
}
public void setName(String name) {
this.name = name;
}
nk

public float getPrice() {


return price;
}
Ve

public void setPrice(float price) {


this.price = price;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
}

input.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

ii
<form action="LoadJSP.jsp" method="post">

ath
Enter the PCode:<input type="text" name="pcode"><br>
<input type="submit" value="Display">
</form>
</body>
</html>

ip
LoadJSP.jsp Ma
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="java.sql.*,test.*"%>
<!DOCTYPE html>
sh
<html>
<head>
<meta charset="ISO-8859-1">
ate

<title>Insert title here</title>


</head>
<body>
<%
try{
nk

ResultSet rs = new RetrieveDAO().retrieve(request);


if(rs.next()){
%>
Ve

<jsp:useBean id="ob" class="test.ProductBean"


scope="session"/>
<jsp:setProperty property="code" name="ob"
value="<%=rs.getString(1) %>"/>
<jsp:setProperty property="name" name="ob"
value="<%=rs.getString(2) %>"/>
<jsp:setProperty property="price" name="ob"
value="<%=rs.getFloat(3) %>"/>
<jsp:setProperty property="qty" name="ob"
value="<%=rs.getInt(4) %>"/>
<a href="ViewJSP.jsp">ViewProductDetails</a>
<%
}else{
out.println("Invalid ProdCode...<br>");
%>
<jsp:include page="input.html"/>
<%
}
}catch(Exception e){e.printStackTrace();}
%>
</body>

ii
</html>

ath
ViewJSP.jsp

<%@ page language="java"


contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"

ip
import="test.*"%>
<!DOCTYPE html> Ma
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
sh
<jsp:useBean id="ob" type="test.ProductBean" scope="session"/>
ProductCode:<jsp:getProperty property="code" name="ob"/><br>
ProductName:<jsp:getProperty property="name" name="ob"/><br>
ate

ProductPrice:<jsp:getProperty property="price" name="ob"/><br>


ProductQty:<jsp:getProperty property="qty" name="ob"/><br>

</body>
nk

</html>

web.xml
Ve

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


<web-app>
<welcome-file-list>
<welcome-file>input.html</welcome-file>
</welcome-file-list>
</web-app>

DBConnection.java
package test;
import java.sql.*;
public class DBConnection {
private static Connection con=null;//reference variable
private DBConnection() {}
static
{
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection

ii
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
}catch(Exception e) {e.printStackTrace();}

ath
}
public static Connection getCon()
{
return con;
}

ip
}
RetrieveDAO.java Ma
package test;

import java.sql.*;

import javax.servlet.http.*;
sh
public class RetrieveDAO {
ate

public ResultSet rs=null;

public ResultSet retrieve(HttpServletRequest req)


nk

try {
Ve

Connection con = DBConnection.getCon();

//Accessing the Connection

PreparedStatement ps = con.prepareStatement

("select * from Product45 where pcode=?");

ps.setString(1,req.getParameter("pcode"));
rs = ps.executeQuery();

}catch(Exception e) {e.printStackTrace();}

return rs;

=====================================================================

ii
Dt : 18/6/2022

ath
*imp

Web Architecture Models:(Web Application Architectures)

ip
Ma
Two types of development models are used in Java,for Web applications

and these models are classified based on the different approaches

used to develop Web applications.


sh

These models are:


ate

1. Model-1 Architecture

2. Model-2 Architecture(MVC)
nk

1. Model-1 Architecture:
Ve

The Model-1 architecture was the first development model used to

develop Web applications and this model uses JSP to design applications

and, which is responsible for all the activities and functionalities

provided by the application.


Limitations of the Model-1 Architecture:

(i).Applications are inflexible and difficult to maintain.

A single change in one page may cause changes in other pages, leading

to unpredictable results.

ii
ath
(ii).Involves the developer at both the page development and the

business logic implementation stages.

ip
Ma
(iii).Increases the complexity of a program with the increase in the

size of the JSP page.


sh
ate
nk
Ve

===========================================================
2. Model-2 Architecture:

=>The draw backs in the Model-1 architecture led to the introduction

of a new model called Model-2.

=>The Model-2 architecture was targeted at overcoming the drawbacks of

Model-1 and helping developers to design more powerful Web applications

ii
and this Model-2 architecture is based on the MVC design model.

ath
=>MVC Stands for Model View Controller.

ip
Ma
Model: Represents enterprise data and business rules that specify how

data is accessed and updated,and which is generally implemented by

using JavaBeans.
sh

View: Shows the contents of a Model.The View component accesses


ate

enterprise data through the Model component and specifies how that

data should be presented and this View Component is designed by JSP.


nk

Controller: Receives HTTP requests. The Controller component receives


Ve

requests from a client, determines the business logic to be performed,

and delegates the responsibility for producing the next phase of the

user interface to an appropriate view component. The Controller has

complete control over each view, implying that any change in the Model

component is immediately reflected in all the Views of an application.


The Controller component is implemented by servlets.

Advantages of Model-2 Architecture:

(i)Allows use of reusable software components to design the

Business logic. Therefore, these components can be used in the

ii
business logic of other applications.

ath
(ii)Offers great flexibility to the presentation logic, which can be

ip
modified without effecting the business logic.
Ma
sh
ate
nk
Ve

=====================================================================
Dt : 20/6/2022

Expression Language(EL) in JSP:

=>This EL simplifies the accessibility of data stored in java Bean

component and other objects like request,session,application,etc..

ii
Note:

ath
It is newly added feature in JSP technology.

ip
syntax of EL:

$(expression)
Ma
sh
The following are the implicit objects of EL:
ate

pageScope : It maps the given attribute name with the value,set in the vxvc v

page scope
nk

requestScope : It maps the given attribute name with the value set
Ve

inthe request scope

sessionScope : It maps the given attribute name with the value set

inthe session scope


applicationScope : It maps the given attribute name with the value set

inthe application scope

param : It maps the request parameter to the single value

paramValues :

ii
It maps the request parameters to the array of values

ath
header : It maps the request header name to the single value

ip
Ma
headerValues : It maps the request header names to the array of values

cookie :It maps the cookie name to the cookie value


sh

initParam : It maps the Initialization parameter


ate

pageContext : It provides access to many objects request,session,...


nk

===============================================================

Summery of Objects Generated:


Ve

CoreJava Objects:

1.UserDefined Class objects

2.WrapperClass objects

(i)Byte Object

(ii)Short Object
(iii)Integer object

(iv)Long Object

(v)Float Object

(vi)Double Object

(vii)Character object

(viii)Boolean Object

ii
3.String Objects

ath
(i)String Object

(ii)StringBuffer object

ip
(iii)StringBuilder object

4.Array Objects

(i)User defined Class Array


Ma
(ii)String Array
sh
(iii)WrapperClass Array

(iv)Object Array
ate

(v)Jagged Array

5.Collection<E> Objects
nk

(a)Set<E>

(i)HashSet<E> object
Ve

(ii)LinkedHashSet<E> Object

(iii)TreeSet<E> Object

(b)List<E>

(i)ArrayList<E> Object

(ii)Vector<E> Object
|->Stack<E> Object

(iii)LinkedList<E> Object

(c)Queue<E>

(i)PriorityQueue<E> Object

|->Deque<E>

(ii)ArrayDeque<E> Object

ii
6.Map<K,V> Objects

ath
(i)HashMap<K,V> Object

(ii)LinkedHashMap<K,V> Object

ip
(iii)TreeMap<K,V> Object

(iv)Hashtable<K,V> Object

7.Enum<E> objects
Ma
--------------------------
sh
JDBC Objects:

1.Connection Object
ate

2.Statement Object

3.PreparedStatement Object
nk

4.CallableStatement object

5.Scrollable ResultSet Object


Ve

6.Non-Scrollable ResultSet Object

7.DatabaseMetaData object

8.ParameterMetaData object

9.ResultSetMetaData object

10.RowSet Object
------------

11.Connection pooling object

Servlet Objects:

1.ServletContext object

2.ServletConfig Object

ii
3.ServletRequest object/HttpServletRequest object

ath
4.ServletResponse object/HttpServletResponse object

5.PrintWriter object

ip
6.HttpSession object

7.Cookie object

8.DAO Layer object


Ma
9.JavaBean object
sh
10.JCF Object
ate

JSP objects:

1.application
nk

2.config

3.request
Ve

4.response

5.out

6.session

7.exception

8.page
9.pageContext

----------

JSP EL objects:

1.pageScope

2.sessionScope

ii
3.requestScope

ath
4.applicationScope

5.param

ip
6.paramValues

7.cookie

8.pageContext
Ma
9.header
sh
10.headerValues

11.initParam
ate

--------------------------

Note:
nk

=>In realtime JSPEL replaces with SpEL.


Ve

Objects Layout diagram:


ii
ip ath
Ma
==============================================================
sh
JSTL(JSP Standard Tag Lib):
ate

=>This JSTL represents a set of tags to simplify the JSP development.


nk

Advantages of JSTL:

(i)Fast Development
Ve

(ii)Code Reusability

(iii)No need to use scriptlet tag

The following are the JSTL tags:


(1)Core Tags

(2)Function Tags

(3)Formatting Tags

(4)XML Tags

(5)SQL Tags

ii
ath
Note:

=>we use "taglib" directive tag to declare JSTL Tags.

ip
=>To Execute JSTL Tags we use the following steps:
Ma
sh
(i)Download the following Jar files to execute JSTL tags
ate

javax.servlet.jsp.jstl-1.2.1.jar

javax.servlet.jsp.jstl-api-1.2.1.jar
nk

(ii)These jars must be available within 'lib' folder of


Ve

'WEB-INF' in deployment directory

------------------------------------------------------------

(1)Core Tags:

=>These JSTL core tags provides variable support,URL management,


flow control etc. (Basic code writing)

syntax:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core"

prefix="c" %>

ii
ath
The following are the List of JSTL Core Tags:

ip
c:out ->It displays the result of an expression, similar to

<%=...%> tag.
Ma
c:import->It Retrives relative or an absolute URL.
sh

c:set-> It sets the value to variable.


ate

c:remove->It is used for removing the variable .


nk

c:catch-> It is used for Catching any Throwable exception that occurs


Ve

in the body.

c:if-> It is an conditional tag

c:choose, c:when, c:otherwise->


It is the simple conditional tag that includes its body content

if the evaluated condition is true.

*imp

c:forEach-> It is the basic iteration tag.

ii
c:forTokens-> It iterates over tokens which is separated by the

ath
supplied delimeters.

ip
c:param-> It adds a parameter in a containing 'import' tag's URL.
Ma
c:redirect-> It redirects the browser to a new URL and supports the

context-relative URLs.
sh

c:url-> It creates a URL with optional query parameters.


ate

-----------------------------------------------------

(2)Function Tags:
nk

=>These JSTL function tags provides a number of standard

functions, most of these functions are common string manipulation


Ve

functions.

syntax:

<%@taglib uri= "http://java.sun.com/jsp/jstl/functions"


prefix="fn" %>

List of Some Function tags:

fn:contains() : It is used to test if an input string containing the

specified substring or not.

ii
fn:containsIgnoreCase(): It is used to test if an input string

ath
contains the specified substring as a case insensitive way.

ip
fn:endsWith() : It is used to test if an input string ends with the

specified suffix.
Ma
fn:indexOf(): It returns an index within a string of first occurrence
sh
of a specified substring.
ate

fn:trim(): It removes the blank spaces from both the ends of a string.
nk

fn:startsWith(): It is used for checking whether the given string is

started with a particular string value or not.


Ve

fn:split(): It splits the string into an array of substrings.

fn:toLowerCase(): It converts all the characters of a string to lower

case.
fn:toUpperCase(): It converts all the characters of a string to

uppercase.

fn:substring(): It returns the subset of a string according to the

given start and end position.

ii
ath
fn:length(): It returns the number of characters inside a string, or

the number of items in a collection.

ip
Ma
fn:replace(): It replaces all the occurrence of a string with

another string sequence.

---------------------------------------------------------------
sh
(3)Formatting Tags:

=>The formatting tags provide support for message formatting,


ate

number formating and date formatting etc.

=>These formatting tags are also used for internationalized web


nk

sites to display and format text,time,date and numbers.


Ve

syntax:

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"

prefix="fmt" %>
List of some Formatting tags:

fmt:parseNumber : It is used to Parse the string representation of a

currency, percentage or number.

fmt:formatNumber : It is used to format the numerical value with

ii
specific format or precision.

ath
fmt:parseDate : It parses the string representation of a time and

ip
date.

fmt:setTimeZone
Ma
: It stores the time zone inside a time zone

configuration variable.
sh

*imp
ate

fmt:formatDate : It formats the time and date using the supplied

pattern and styles.


nk

-------------------------------------------------------------
Ve

(4)XML Tags:

=>The JSTL XML tags are used for providing a JSP-centric way of

manipulating and creating XML documents.

syntax:
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>

(5)SQL Tags:

=>The SQL tag library allows the tags to Interact with RDBMS

(Relational Databases) such as Microsoft SQL Server, mySQL,

or Oracle.

ii
ath
syntax:

<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>

ip
Note:
Ma
=>In realtime we must not have JSP Centric XML and DB Connections,

because of this reason XML tags and SQL Tags are less used when
sh
compared to other tags.

================================================================
ate
nk
Ve

You might also like