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

Adv - Java VM

The document outlines various types of applications, including Stand-Alone, Web, Enterprise, and Mobile Applications, along with their characteristics. It also discusses storage types relevant to Java application development, such as Field, Object, File, and Database Storage, highlighting the advantages and disadvantages of each. Additionally, it provides an overview of JDBC, including driver types, connection establishment, and example JDBC applications for database interaction.

Uploaded by

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

Adv - Java VM

The document outlines various types of applications, including Stand-Alone, Web, Enterprise, and Mobile Applications, along with their characteristics. It also discusses storage types relevant to Java application development, such as Field, Object, File, and Database Storage, highlighting the advantages and disadvantages of each. Additionally, it provides an overview of JDBC, including driver types, connection establishment, and example JDBC applications for database interaction.

Uploaded by

shankar.uiml
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

[JDBC,SERVLETS,JSP]

By VENKATESH MAIPATHI

DHANANJAYA ARJUN
Dt : 26/10/2023(day-1)
define Application?
=>Set-of-programs collected together to perform defined action is known
as Application.

Types of Applications:
=>Applications are categorized into four types:
[Link]-Alone-Applications
[Link] Applications
[Link] Applications
[Link] Applications

[Link]-Alone-Applications:
=>The Applications which are installed in one computer and performs
actions in the same Computer are knonw as Stand-Alone-Applications
or DeskTop Applications or Windows Applications
=>Based on user interaction the Stand-Alone-Applications are categorized
into two types:
(i)CUI Applications
(ii)GUI Applications
(i)CUI Applications:
=>The Applications in which the user interacts through Console
(CommandPrompt) are known as CUI Applications.
(CUI - Console User Interface)

(ii)GUI Applications:
=>The Applications in which the used interacts through GUI Components
are known as GUI Applications.
(GUI - Graphical User Interface)
=>we use the following to construct GUI Components:
AWT - Abstract Window Toolkit
Swing
JavaFX
------------------------------------------------------------------
*imp
[Link] Applications:
=>The applications which are executed in Web Environment or Internet
Environment are known as WebApplications or Internet Applications.
=>we use the following three technologies to construct WebApplications
(i)JDBC
(ii)Servlet
(iii)JSP
------------------------------------------------------------------
[Link] Applications:
=>The applications which are executing in distributed environment and
depending on the features like "Security","Load Balancing" and
"Clustering" are known as Enterprise Applications or Enterprise
Distribute Applications.
=>To develop Enterprise Applications we use Java Frameworks and
Java Tools.
-------------------------------------------------------------------------
[Link] Applications:
=>The appliactions which are executed in Mobile environment are known as
Mobile Applications.
==========================================================================
*imp
define Storage?(Syllabus)
=>The location where the data is available for access,is known as Storage.
Types of Storages:
=>According to Java Application development the storages are categorized
into four types:
[Link] Storage
[Link] Storage
[Link] Storage
[Link] Storage
Dt : 27/10/2023(day-2)
[Link] Storage:
=>The memory generated to hold 'single data value' is known as Field
Storage.
=>The primitive datatypes(byte,short,int,long,float,double,char,boolean)
will generate Field Storages.
*imp
[Link] Storage:
=>The memory generated to hold 'group members' is known as Object
Storage.
=>The NonPrimitive datatype(Class,Interface,Array,Enum) will generate
Object Storage.

Ex:
class Addition{
int a=10,b=20;
void add() {
int c = a+b;
[Link]("Sum="+c);
}
}

Addition ob = new Addition();


Diagram:

-------------------------------------------------------------------
faq:
wt is the diff b/w
(i)Object
(ii)Object reference
(iii)Object reference Variable

(i)Object:
=>The memory which is generated to hold instance members of Class is
known as Object.

(ii)Object reference
=>The address where object is generated is known as Object reference.

(iii)Object reference Variable:


=>The NonPrimitive datatype variable which is holding Object reference
is known as Object reference Variable or Object Name.
=====================================================================
Dt : 30/10/2023
*imp
Summary of Objects created from CoreJava:
[Link] defined Class Objects
[Link]-Objects
[Link]-Objects
[Link]-Objects
[Link]<E>-Objects
[Link]<K,V>-Objects
[Link]<E>-Objects
=======================================================================
Note:
=>The Field-Storages and Object-Storages which are generated part of JVM
will be destroyed automatically when JVM ShutDowns.
=>when we want to have permanent storage for application,then we must
use any one of the following:
=>File Storage
=>Database Storage

=====================================================================
[Link] Storage:
=>The smallest permanent storage of ComputerSystem which is controlled
and managed by the OperatingSystem is known as File Storage.
=>In the process of establishing communication b/w JavaProgram and
File-Storage,the JavaProgram must be constructed using 'classes and
Interfaces' available from '[Link]' package(IO Stream and FIle API).
Diagram:

======================================================================
Dis-Advantages of File-Storage:
[Link] Redundancy
[Link] Inconsistency
[Link] Integrity problem
[Link] Sharing Problem
[Link] Security Problem

[Link] Redundancy:
=>The process in which File-Storage will store duplicate data,known
as Data Redundancy or Data Replication.

[Link] Inconsistency:
=>The process in which File-storage will different data fields,known
as Data Inconsistency.

[Link] Integrity problem:


=>File-Storage will not support Data Integrity,which means combining
data available in different locations.

[Link] Sharing Problem:


=>File-Storage will not Support File Sharing,which means File-Storage
not available to multiple users at-a-time

[Link] Security Problem:


=>Data is not Secure in File-Storage

=================================================================
Note:
=>Because of DisAdvantages of File-Storage,we are not prefering to
take File-storage as Back-end for applications.
=====================================================================
Dt : 31/10/2023
*imp
[Link] Storage:
=>The largest permanent storage of ComputerSystem,which is 'downloaded
and installed' from externally is known as Database.
=>In the process of establishing communication b/w JavaProgram and
Database product,the JavaProgram must be constructed using 'Classes
and Interface' available from '[Link]' package(JDBC API) and the
JavaProgram must take the support of JDBC-driver

Diagram:

==================================================================
faq:
define driver?
=>The small s/w program used by OperatingSystem to establish connection
b/w two end-points
Ex:
Audio driver
Video driver
N/W driver
....

faq:
define JDBC driver?
=>The driver which is used to establish connection b/w JavaProgram and
Database product is known as JDBC driver.
(Java DataBase Connectivity driver)

Types of JDBC drivers:


=>JDBC drivers are categorized into four types:
[Link]-ODBC bridge driver(Type-1)
[Link] API driver(Type-2)
[Link] Protocol driver(Type-3)
[Link] driver(Type-4)

Note:
=>In realtime application development we use Type-4(Thin) driver.
=====================================================================
faq:
define API?
=>API stands for 'Application Programming Interface' and which is a
PlatForm for programmers to develop applications using Language or
Technology or Frameworks
=>According to JavaLanguage,API means package.
=>The following are some important APIs(packages):
CoreJava:
[Link] - Language package(default package)
[Link] - Input/Output Stream and Files package
[Link] - Utility package
[Link] - Networking package
AdvJava:
[Link] - Database package(JDBC API)
[Link] - Servlet programming package(Servlet API)
[Link] - JSP Programming package(JSP API)
===================================================================
*imp
Making ComputerSystem environment ready for executing JDBC Applications:

step-1 : Download and Install Database product(Oracle)


step-2 : Perform Login Process to Database project
step-3 : Create table with name Customer57
(cid,cname,ccity,cstate,pincode,mid,phno)
create table Customer57(cid varchar2(10),cname varchar2(15),
ccity varchar2(15),cstate varchar2(15),pincode number(10),
mid varchar2(25),phno number(15),primary key(cid));

step-4 : Insert min 5 Customer details

insert into Customer57 values('E111','Ram','Hyd','TS',612345,


'r@[Link]',9898981234);

step-5 : Copy DB-Jar file into User defined folder(DeskTop)

Location of DB-Jar file,


C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib
ojdbc6 - Oracle11

faq:
define JAR file?
=>JAR stands for Java Archieve and which is compressed format of
more class files.

step-6 : Find Database PortNo and ServiceName


Find PortNo and ServiceName from "[Link]" file
C:\oraclexe\app\oracle\product\11.2.0\server\network\ADMIN

PortNo : 1521
ServiceName : XE
=======================================================================
Dt : 1/11/2023
*imp
JDBC API:
=>'[Link]' package is known as JDBC API and which provide 'Classes
and Interfaces' to Construct JDBC Applications.
=>'[Link]' interface is the root of JDBC API.
=>The following are some important methods from 'Connection' interface:
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()

Hierarchy of 'Connection' Interface:

------------------------------------------------------------
=>we use getConnection() method from '[Link]' class to
create implemention object for 'Connection' interface.
=>This getConnection() method internally holding Anonymous Local InnerClass
as implementation class of 'Connection' interface.

Method Signature of getConnection():


public static [Link] getConnection([Link],
[Link], [Link]) throws [Link];

syntax:
Connection con = [Link]("DBURL","UName","PWord");

DBURL => jdbc:oracle:thin:@localhost:1521:xe


UName => system
PWord => manager
-------------------------------------------------------------------
Dt : 2/11/2023
*imp
JDBC Statements:
=>JDBC statements will specify the type of actions performed on database
product.
=>These JDBC Statements are categorized into three types:
[Link]
[Link]
[Link]

[Link]:
=>'Statement' is an interface from [Link] package and which is used
to execute normal queries without IN Parameters.
(Normal Queries maens Create,Insert,Select,Update,Delete)
=>we use createStatement() method from 'Connection' interface to create
implementation object for 'Statement' interface.
=>This createStatement() method internally holding Anonymous Local
InnerClass as implementation class of 'Statement' interface.

Method signature of createStatement():


public abstract [Link] createStatement()
throws [Link];

syntax:
Statement stm = [Link]();

=>The following are some important methods from 'Statement':


(i)executeQuery()
(ii)executeUpdate()
(i)executeQuery():
=>executeQuery() method is used to execute select-queries.

Method Signature:
public abstract [Link] executeQuery([Link])
throws [Link];

syntax:
ResultSet rs = [Link]("select-query");

(ii)executeUpdate():
=>executeUpdate() method is used to execute NonSelect-queries.

Method Signature:
public abstract int executeUpdate([Link])
throws [Link];
syntax:
int k = [Link]("NonSelect-query");
-------------------------------------------------------------
*imp
we use the following steps to establish connection to Database Product:
step-1 : Loading driver
step-2 : Creating Connection
step-3 : Preparing Statement
step-4 : Executing query
step-5 : Closing the connection
===================================================================
*imp
Creating JDBC application using IDE Eclipse:

step-1 : Open IDE Eclipse,while opening name the workspace and click
'Launch'.
step-2 : Create Java Project

step-3 : Add DB-Jar file to Java Project

RightClick on JavaProject->Build Path->Configure Build Path->Libraries->


select 'Classpath' and click 'Add External Jars'->Browse and select DB-Jar
file from user defined folder->open->Apply->Apply and Close

step-4 : Create package in 'src'

step-5 : Create class in package to write JDBC code

Program : [Link]
package test;
import [Link].*;
public class DBCon1
{
public static void main(String[] args)
{
try
{
//step-1 : Loading driver
[Link]("[Link]");
//step-2 : Creating Connection
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
//step-3 : Preparing Statement
Statement stm = [Link]();
//step-4 : Executing query
ResultSet rs = [Link]
("select * from Customer57");
[Link]("****Customer-Details****");
while([Link]())
{
[Link]([Link](1)+"\t"+
[Link](2)+"\t"+[Link](3)+
"\t"+[Link](4)+"\t"+
[Link](5)+"\t"+[Link](6)+"\t"+
[Link](7));
}//end of loop
//step-5 : Closing the connection
[Link]();
}//end of try
catch(Exception e)
{
[Link]();
}
}
}

=========================================================================
Assignment:
Step-1 : Create table with name Product57
(code,name,price,qty)

step-2 : Insert Min 5 product details

step-3 : Construct JDBC Application to display all products


====================================================================
Dt : 3/11/2023
Execution flow of above program:([Link])

===================================================================
faq:
define ResultSet?
=>ResultSet is an interface from [Link] package.
=>we use executeQuery() method to create implementation object for
ResultSet-Interface
=>This ResultSet-Object will hold the result generated from select
queries.
syntax:
ResultSet rs = [Link]("select-queries");
====================================================================
Ex-program:
Construct JDBC Application to read Customer details from Console input
and insert into Customer57-table

Program : [Link]
package test;
import [Link].*;
import [Link].*;
public class DBCon2
{
public static void main(String[] args)
{
Scanner s = new Scanner([Link]);
try(s;){
try {
[Link]("Enter the CustId:");
String cId = [Link]();
[Link]("Enter the CustName:");
String cName = [Link]();
[Link]("Enter the CustCity:");
String city = [Link]();
[Link]("Enter the CustState:");
String state = [Link]();
[Link]("Enter the PinCode:");
int pinCode = [Link]([Link]());
[Link]("Enter the CustMailId:");
String mId = [Link]();
[Link]("Enter the PhNO:");
long phNo = [Link]();

[Link]("[Link]");
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
Statement stm = [Link]();
int k = [Link]
("insert into Customer57
values('"+cId+"','"+cName+"','"+city+"','"+state+"',"+pinCode+",'"+mId+"',"+phNo+")");
if(k>0) {
[Link]("Customer details Inserted Successfully...");
}
[Link]();

}catch(Exception e) {[Link]();}
}//end of try-with-resource
}
}

o/p:
Enter the CustId:
A234
Enter the CustName:
Alex
Enter the CustCity:
Hyd
Enter the CustState:
TS
Enter the PinCode:
65432
Enter the CustMailId:
a@[Link]
Enter the PhNO:
7676761234
Customer details Inserted Successfully...
=====================================================================
Assignment:
Construct JDBC Application to read Product-Details from Console and
insert into Product57-table
======================================================================
Dt : 4/11/2023
Ex-program:
Construct JDBC Application to display Customer Details based on CustId.

Program : [Link]
package test;
import [Link].*;
import [Link].*;
public class DBCon3
{
public static void main(String[] args)
{
Scanner s = new Scanner([Link]);
try(s;){
try {
[Link]("Enter the CustId:");
String cId = [Link]();
[Link]("[Link]");
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
Statement stm = [Link]();
ResultSet rs = [Link]
("select * from Customer57 where cid='"+cId+"'");
if([Link]()) {
[Link]([Link](1)+"\t"+
[Link](2)+"\t"+[Link](3)+"\t"+
[Link](4)+"\t"+[Link](5)+
"\t"+[Link](6)+"\t"+
[Link](7));
}else {
[Link]("Invalid CustId...");
}
[Link]();
}catch(Exception e) {[Link]();}
}//end of try with resource
}
}
o/p:
Enter the CustId:
E111
E111 Ram Hyd TS 612345 r@[Link] 9898981234
====================================================================

Assignment:
Construct JDBC Application to display Product-details based on ProdCode.
=====================================================================
Assignment:
Create DB table with name : BookDetails57
(code,name,author,price,qty)
Prog-1 : Insert BookDetails
Prog-2 : Display All Book Details
Prog-3 : Display Book Details based on BookCode
================================================================
Dt : 6/11/2023
[Link]:
=>PreparedStatement is an interface from [Link] package and which is
used to execute normal queries with IN Parameters.
=>we use prepareStatement() method from 'Connection' interface to create
implementation object for 'PreparedStatement' interface.

Method Signature of prepareStatement():


public abstract [Link] prepareStatement
([Link]) throws [Link];

syntax:
PreparedStatement ps = [Link]("query-structure");

=>The following are two important methods from PreparedStatement:


(i)executeQuery()
(ii)executeUpdate()

(i)executeQuery():
=>executeQuery() method is used to execute select-queries.
Method Signature:
public abstract [Link] executeQuery()
throws [Link];

syntax:
ResultSet rs = [Link]();
(ii)executeUpdate():
=>executeUpdate() method is used to execute NonSelect-queries.
Method Signature:
public abstract int executeUpdate() throws [Link];

syntax:
int k = [Link]();
---------------------------------------------------------------------
Ex-program:
Construct JDBC Application to perform the following operations on DB-table
Product57 based on User Choice:
[Link]
[Link]
[Link]
[Link](price-qty)
[Link]

DB-table : Product57

create table Product57(code varchar2(10),name varchar2(15),


price number(10,2),qty number(10),primary key(code));

Program : [Link]
package test;
import [Link].*;
import [Link].*;
public class DBCon3
{
public static void main(String[] args)
{
Scanner s = new Scanner([Link]);
try(s;){
try {
[Link]("Enter the CustId:");
String cId = [Link]();
[Link]("[Link]");
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
Statement stm = [Link]();
ResultSet rs = [Link]
("select * from Customer57 where cid='"+cId+"'");
if([Link]()) {
[Link]([Link](1)+"\t"+
[Link](2)+"\t"+[Link](3)+"\t"+
[Link](4)+"\t"+[Link](5)+
"\t"+[Link](6)+"\t"+
[Link](7));
}else {
[Link]("Invalid CustId...");
}
[Link]();
}catch(Exception e) {[Link]();}
}//end of try with resource
}
}

o/p:
****Choice*****
[Link]
[Link]
[Link]
[Link](price-qty)
[Link]
[Link]
Enter the Choice:
1
====Enter Product Details===
Enter ProdCode:
A111
Enter ProdName:
Mouse
Enter ProdPrice:
1200
Enter ProdQty:
12
Product added Successfully..
****Choice*****
[Link]
[Link]
[Link]
[Link](price-qty)
[Link]
[Link]
Enter the Choice:
1
====Enter Product Details===
Enter ProdCode:
A222
Enter ProdName:
CDR
Enter ProdPrice:
1600
Enter ProdQty:
15
Product added Successfully..
****Choice*****
[Link]
[Link]
[Link]
[Link](price-qty)
[Link]
[Link]
Enter the Choice:
------------------------------------------------------------------
Diagram:

=====================================================================
Dt : 7/11/2023

Program : [Link](Code Modified)

package test;

import [Link].*;

import [Link].*;

public class DBCon4 {

public static void main(String[] args) {


Scanner s = new Scanner([Link]);

try(s;){

try {

[Link]("[Link]");

Connection con = [Link]

("jdbc:oracle:thin:@localhost:1521:xe",

"system","manager");

PreparedStatement ps1 = [Link]

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

PreparedStatement ps2 = [Link]

("select * from Product57");//Compilation

PreparedStatement ps3 = [Link]

("select * from Product57 where code=?");//Compilation

PreparedStatement ps4 = [Link]

("update Product57 set price=?,qty=qty+? where code=?");

PreparedStatement ps5 = [Link]

("delete from Product57 where code=?");

while(true)

[Link]("****Choice*****");

[Link]("[Link]"

+ "\t\[Link]"

+ "\t\[Link]"

+ "\t\[Link](price-qty)"

+ "\t\[Link]"

+ "\t\[Link]");

[Link]("Enter the Choice:");

int choice = [Link]([Link]());

switch(choice)

case 1:

[Link]("====Enter Product Details===");

[Link]("Enter ProdCode:");
String pC = [Link]();

[Link]("Enter ProdName:");

String pN = [Link]();

[Link]("Enter ProdPrice:");

float pP = [Link]([Link]());

[Link]("Enter ProdQty:");

int pQ = [Link]([Link]());

//Loading data to PreparedStatement Object

[Link](1, pC);

[Link](2, pN);

[Link](3, pP);

[Link](4, pQ);

int k = [Link]();//Execution

if(k>0) {

[Link]("Product added Successfully..");

break;

case 2:

ResultSet rs1 = [Link]();//Execution

while([Link]())

[Link]([Link](1)+"\t"+

[Link](2)+"\t"+

[Link](3)+"\t"+

[Link](4));

break;

case 3:

[Link]("Enter the ProdCode:");

String pC1 = [Link]();


[Link](1, pC1);

ResultSet rs2 = [Link]();//Execution

if([Link]()) {

[Link]([Link](1)+"\t"+

[Link](2)+"\t"+

[Link](3)+"\t"+

[Link](4));

}else {

[Link]("Invalid ProdCode...");

break;

case 4:

[Link]("Enter the ProdCode for Updating:");

String pC2 = [Link]();

[Link](1, pC2);

ResultSet rs3 = [Link]();

if([Link]()) {

[Link]("Old Price:"+[Link](3));

[Link]("Enter the New price:");

float nPrice = [Link]([Link]());

[Link]("Existing Qty:"+[Link](4));

[Link]("Enter the New Qty:");

int nQty = [Link]([Link]());

[Link](1, nPrice);

[Link](2, nQty);

[Link](3, pC2);

int k2 = [Link]();

if(k2>0) {

[Link]("Product Updated Successfully...");

}else {

[Link]("Invalid ProdCode...");

}
break;

case 5:

[Link]("Enter the ProCode for delete process:");

String pC3 = [Link]();

[Link](1, pC3);

ResultSet rs4 = [Link]();

if([Link]()) {

[Link](1, pC3);

int k4 = [Link]();

if(k4>0) {

[Link]("Product deleted Successfully...");

}else {

[Link]("Invalid ProdCode...");

break;

case 6:

[Link]("Operations Stopped...");

[Link](0);

default:

[Link]("Invalid Choice...");

}//end of switch

}//end of loop

}//end of try

catch(Exception e)

[Link]();

}//end of try with resource

o/p:

****Choice*****
[Link]

[Link]

[Link]

[Link](price-qty)

[Link]

[Link]

Enter the Choice:

Enter the ProCode for delete process:

A222

Product deleted Successfully...

****Choice*****

[Link]

[Link]

[Link]

[Link](price-qty)

[Link]

[Link]

Enter the Choice:

A111 Mouse 1200.0 12

****Choice*****

[Link]

[Link]

[Link]

[Link](price-qty)

[Link]

[Link]

Enter the Choice:

Operations Stopped...

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

Assignment:
Step-1 : Construct DB table with name Employee57

(eid,ename,edesg,bsal,totsal)

primary key : eid

step-2 : Construct JDBC Application to perform the following operations:

[Link]

[Link]

[Link]

[Link](bSal)

[Link]

Note:

totSal = bSal+hra+da;

hra = 93% of bSal

da = 61% of bSal

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

Dt : 8/11/2023
*imp
ResultSet in JDBC:
=>ResultSet is an interface from [Link] package and which is instantiated
using executeQuery() method.

syntax using Statement:


ResultSet rs = [Link]("select-query");

syntax using PreparedStatement:


ResultSet rs = [Link]();

=>This ResultSet-Object will hold the result generated from Select-queries


---------------------------------------------------------------
Types of ResultSet Objects:
=>Based on the control over the ResultSet objects,the ResultSet objects
are categorized into two types:
(a)NonScrollable ResultSet Objects
(b)Scrollable ResultSet Objects

(a)NonScrollable ResultSet Objects:


=>In NonScrollable ResultSet Objects the cursor is moved only in one
direction,which means only forward-direction.
Ex:
above programs related to Select-queries

(b)Scrollable ResultSet Objects:


=>In Scrollable ResultSet objects the cursor can be moved in both
directions,which means forward and backward.
=>we use the following syntaxes to generate Scrollable ResultSet
Objects:

syntax using Statement:


Statement stm = [Link](type,mode);

syntax using PreparedStatement:


PreparedStatement ps = [Link]("qyery-structure",type,mode);

define 'type'?
=>'type' specifies the movement of Cursor on ResultSet object.
=>ResultSet provides the following fields related to 'type':
public static final int TYPE_FORWARD_ONLY;------>1003
public static final int TYPE_SCROLL_INSENSITIVE;---->1004
public static final int TYPE_SCROLL_SENSITIVE;------>1005

define 'mode'?
=>'mode' specifies the action to be performed on ResultSet Object.
=>ResultSet provides the following fields related to 'mode':
public static final int CONCUR_READ_ONLY;---->1007
public static final int CONCUR_UPDATABLE;---->1008

Note:
=>In 'TYPE_SCROLL_INSENSITIVE',the background buffer is not modified.
=>In 'TYPE_SCROLL_SENSITIVE',the backgound buffer is modified.
--------------------------------------------------------------------
=>The following are some important method to control cursor on
Scrollable ResultSet object:
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()

[Link]():
=>afterLast() method will move cursor after the last row of ResultSet

[Link]():
=>beforeFirst() method will move the cursor before the first row of
ResultSet

[Link]():
=>last() method make the cursor point to the last row of ResultSet.

[Link]():
=>first() method make the cursor point to the first row of ResultSet.

[Link]():
=>previous() method will move the cursor in backward direction.
[Link]():
=>next() method will move the cursor in forward direction.

[Link](int):
=>absolute(int) method is used move the cursor to the specified row
number on the ResultSet object

[Link]():
=>relative() method is used to move the cursor from current position
to forward or backward by taking incre/decre value as parameter.
Ex:
[Link](+2);
[Link](-4);
----------------------------------------------------------------
Ex-1:
program : [Link]
package test;
import [Link].*;
public class DBCon5 {
public static void main(String[] args) {
try {
[Link]("[Link]");
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
Statement stm = [Link]
(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
/*
[Link](ResultSet.TYPE_FORWARD_ONLY);

[Link](ResultSet.TYPE_SCROLL_INSENSITIVE);
[Link](ResultSet.TYPE_SCROLL_SENSITIVE);
[Link](ResultSet.CONCUR_READ_ONLY);
[Link](ResultSet.CONCUR_UPDATABLE);
*/
ResultSet rs = [Link]
("select * from Customer57");
[Link]();
//Cursor pointing after the last row
[Link]("****Details****");
while([Link]())
{
[Link]([Link](1)+"\t"+
[Link](2)+"\t"+[Link](3)+
"\t"+[Link](4)+"\t"+

[Link](5)+"\t"+[Link](6)+"\t"+
[Link](7));
}
[Link]("====row-2=====");
[Link](2);
[Link]([Link](1)+"\t"+
[Link](2)+"\t"+[Link](3)+
"\t"+[Link](4)+"\t"+
[Link](5)+"\t"+[Link](6)+"\t"+
[Link](7));
[Link]("====relative(+2)=====");
[Link](+2);
[Link]([Link](1)+"\t"+
[Link](2)+"\t"+[Link](3)+
"\t"+[Link](4)+"\t"+
[Link](5)+"\t"+[Link](6)+"\t"+
[Link](7));

}catch(Exception e) {[Link]();}
}
}

o/p:
****Details****
B123 RETY Hyd TS 61234 r@ 6767671234
A234 Alex Hyd TS 65432 a@[Link] 7676761234
E22 Raj Hyd TS 612345 rj@[Link] 7878781234
E111 Ram Hyd TS 612345 r@[Link] 9898981234
====row-2=====
E22 Raj Hyd TS 612345 rj@[Link] 7878781234
====relative(+2)=====
B123 RETY Hyd TS 61234 r@ 6767671234
-----------------------------------------------------------------
Ex-2:
Program : [Link]
package test;
import [Link].*;
public class DBCon6 {
public static void main(String[] args) {
try {
[Link]("[Link]");
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
PreparedStatement ps = [Link]
("select * from Product57",1004,1007);
ResultSet rs = [Link]();
[Link]();
[Link]([Link](1)+"\t"+
[Link](2)+"\t"+[Link](3)+"\t"+
[Link](4));
}catch(Exception e) {[Link]();}
}
}

o/p:
A111 Mouse 1200.0 12
======================================================================
Dt : 9/11/2023
define 'RowSet'?
=>'RowSet' is an interface from [Link] package and which is extended
from [Link] interface.
java - represents JavaLib
javax - represents Extented-JavaLib
=>RowSet object will hold result-set data.
=>RowSet categorized into two types:
[Link]
[Link]

Hierarchy of RowSet:
--------------------------------------------------------------------
faq:
define 'RowSetFactory'?
=>'RowSetFactory' is an interface from [Link] package and
which provide the following method to create implementions for
'RowSet'.
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
=>we use newFactory() method from 'RowSetProvider' class to create
implementation object for 'RowSetFactory' interface.
syntax:
RowSetFactory rsf = [Link]();
---------------------------------------------------------------------
[Link]:
=>JdbcRowSet will hold data retrieved from DB-product and connection
to DB-product is not dis-connected automatically.
syntax:
JdbcRowSet jrs = [Link]();

[Link]:
=>CachedRowSet also hold the data retrieved from DB-product,but
Connection to DB-Product is closed automatically.
syntax:
CachedRowSet crs = [Link]();
--------------------------------------------------------------------
Note:
(i)FilteredRowSet will hold data retrieved based on Condition,which
means holds filtered data.
(ii)JoinRowSet will hold data by joining multiple RowSet-Objects
=====================================================================
Program : [Link]
package test;
import [Link].*;
import [Link].*;
public class DBCon7 {
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
try(s;){
try {
RowSetFactory rsf = [Link]();
//RowSetFactory Object created
[Link]("****Choice****");
[Link]("\[Link]"
+ "\n\[Link]");
[Link]("Enter the Choice:");
int choice = [Link]();
switch(choice)
{
case 1:
JdbcRowSet jrs = [Link]();
//JdbcRowSet Object created
[Link]("jdbc:oracle:thin:@localhost:1521:xe");
[Link]("system");
[Link]("manager");
[Link]("select * from Product57");
[Link]();
while([Link]()) {
[Link]([Link](1)+"\t"
+[Link](2)+"\t"
+[Link](3)+"\t"
+[Link](4));
}
[Link]();
break;
case 2:
CachedRowSet crs = [Link]();
//CachedRowSet Object
[Link]("jdbc:oracle:thin:@localhost:1521:xe");
[Link]("system");
[Link]("manager");
[Link]("select * from Product57");
[Link]();
while([Link]()) {
[Link]([Link](1)+"\t"
+[Link](2)+"\t"
+[Link](3)+"\t"
+[Link](4));
}
[Link]();
break;
default:
[Link]("Invalid Choice...");
}//end of switch
}catch(Exception e) {[Link]();}
}//end of try with resource
}
}

=======================================================================
Dt : 10/11/2023
Assignment:

DB table : UserReg57
(uname,pword,fname,lname,addr,mid,phN)
primary key : uname

Construct JDBC Application to perform the following Operations:


Choice:
[Link]-Registration
[Link]-Login

[Link]-Registration:
=>read all user details from console and Insert into DB table
o/p:
User registered Successfully...
[Link]-Registration
[Link]-Login

select => [Link]-Login


=>read uname and pword,and check the login process
=>If Login Successfull
Choice:
[Link]
[Link](addr,mid,phno)
[Link]
(choice is repeated until we exit)

=>If Login failed


o/p:
Invalid Login process...
Choice:
[Link]-Registration
[Link]-Login
=================================================================
[Link]:
=>'CallableStatement' is an interface from [Link] package and which
is used to execute 'Procedures and Functions' from the DB Product.
=>we use prepareCall() method from 'Connection' interface to create
implementation object for 'CallableStatement' interface.
Method Signature of prepareCall():
public abstract [Link] prepareCall([Link])
throws [Link];
syntax:
CallableStatement cs = [Link]("{call Proc/Func}");
------------------------------------------------------------------
Diagram:

define Functions?
=>The part of program which is executed out of main-program in C-lang
is known as Function.

define Member Function?


=>The Function which can be declared outside the Class or Inside the
Class in C++ lang,is known as Member Function

define Methods?
=>The functions which are declared only inside the class in Java-Lang
are known as Methods.
--------------------------------------------------------------------
faq:
define Procedure?
=>Procedure is a set-of-queries executed on DB product,and which
willnot return any value after execution.
(Procedure means NonReturn_type)

structure of procedure:

create or replace procedure Proc_name


(para_list) is
begin
query1;
query2;
...
end;
/

faq:
define Function?
=>Function is also a set-of-queries executed on DB product and which
will return value after execution.(Function means Return_type)

structure of Function:

create or replace function Func_name


(para_list)return data_type as var data_type;
begin
query1;
query2;
....
return var;
end;
/
========================================================
faq:
Types of Prcedures:(Stored Procedures)
=>Procedures are categorized into the following:
(i)IN Parameter Procedures
(ii)OUT Parameter Procedures
(iii)IN-OUT Parameter Procedures

(i)IN Parameter Procedures:


=>The Procedures which take the data from JavaPrograms and send to
DB Product are known as 'IN Parameter Procedures'

(ii)OUT Parameter Procedures:


=>The Procedures which take the data from DB Product and send to
JavaPrograms are known as 'OUT Parameter Procedures'

(iii)IN-OUT Parameter Procedures:


=>The procedures which take and send data from DB Product and
JavaPrograms,are known as IN-OUT Parameter Procedures.
Dt : 14/11/2023
Construct and Execute Stored Procedure:

step-1 : Create the following DB tables from SQLCommandLine

EmpData57(eid,ename,edesg)
EmpSalary57(eid,bsal,totsal)

create table EmpData57(eid varchar2(10),ename varchar2(15),


edesg varchar2(10),primary key(eid));

create table EmpSalary57(eid varchar2(10),bsal number(10),


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

step-2 : Construct Stored Procedure to insert Empdatails to DB-Tables

create or replace procedure InsertDetails57


(id varchar2,name varchar2,desg varchar2,bsl number,tsl number) is
begin
insert into EmpData57 values(id,name,desg);
insert into EmpSalary57 values(id,bsl,tsl);
end;
/

step-3 : Construct JDBC Application to execute Procedure

Layout:

Program : [Link]
package test;
import [Link].*;
import [Link].*;
public class DBCon8 {
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
try(s;){
try {
[Link]("[Link]");
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
CallableStatement cs = [Link]
("{call InsertDetails57(?,?,?,?,?)}");

//read data into Local Variables


[Link]("Enter the empId:");
String eId = [Link]();
[Link]("Enter the empName:");
String eName = [Link]();
[Link]("Enter the empDesg:");
String eDesg = [Link]();
[Link]("Enter the empBSal:");
int bSal = [Link]();
float totSal = bSal+(0.93F*bSal)+(0.61F*bSal);

//Add data to CallableStatement Object


[Link](1, eId);
[Link](2, eName);
[Link](3, eDesg);
[Link](4, bSal);
[Link](5, totSal);
[Link]();//Procedure executed with values
[Link]("EmpDetails inserted Successfully...");

}catch(Exception e) {[Link]();}
}//try with resource
}
}

o/p:
Enter the empId:
A111
Enter the empName:
Raj
Enter the empDesg:
SE
Enter the empBSal:
120000
EmpDetails inserted Successfully...

DBTables:

EID ENAME EDESG


---------- --------------- ----------
A111 Raj SE

EID BSAL TOTSAL


---------- ---------- ----------
A111 120000 304800
========================================================================
*imp
Construct and Execute Stored Procedure to Display EmpDetails based on
EmpId:

Layout:

step-1 : Construct Stored Procedure to retrieve EmpDetails

create or replace procedure RetrieveDetails57


(id varchar2,name OUT varchar2,desg OUT varchar2,bsl OUT number,
tsl OUT number) is
begin
select ename,edesg into name,desg from EmpData57 where eid=id;
select bsal,totsal into bsl,tsl from EmpSalary57 where eid=id;
end;
/

step-2 : Construct JDBC Application to execute Procedre

Program : [Link]
package test;
import [Link].*;
import [Link].*;
public class DBCon9 {
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
try(s;){
try {
[Link]("[Link]");
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
CallableStatement cs = [Link]
("{call RetrieveDetails57(?,?,?,?,?)}");

[Link]("Enter the EmpId:");


String eId = [Link]();
[Link](1, eId);
[Link](2, [Link]);
[Link](3, [Link]);
[Link](4, [Link]);
[Link](5, [Link]);

[Link]();

[Link]("====EmpDetails====");
[Link]("EmpId:"+eId);
[Link]("EmpName:"+[Link](2));
[Link]("EmpDesg:"+[Link](3));
[Link]("EmpBSal:"+[Link](4));
[Link]("EmpTotSal:"+[Link](5));
}catch(Exception e) {[Link]();}
}//try with resource
}
}
o/p:
Enter the EmpId:
A111
====EmpDetails====
EmpId:A111
EmpName:Raj
EmpDesg:SE
EmpBSal:120000
EmpTotSal:304800.0
=================================================================

Dt : 15/11/2023
faq:
define registerOutParameter() method?
=>registerOutParameter() method will specify the type of value to be
stored in Parameter-index-field
syntax:
[Link](para_index,[Link]);

Note:
=>'[Link]' is a class holding SQL-DataTypes and which are
represented part of registerOutParameter() method.
Ex:
public static final int INTEGER;
public static final int BIGINT;
public static final int FLOAT;
public static final int VARCHAR;
...
--------------------------------------------------------------------
Assignment-1:
step-1 : Construct the following DB tables

CustData57(cid,cname)
CustAddress57(cid,city,state,pincode)
CustContact57(cid,mid,phno)

step-2 : Construct Stored Procedure to insert the data to DB tables

step-3 : Construct JDBC Application to execute Procedures


-------------------------------------------------------------
Assignment-2:
step-1 : Construct Stored Procedure to display Customer details based on
CustId

step-2 : Construct JDBC Application to execute Procedure.


====================================================================
*imp
Construct and Execute Functions:

step-1 : Construct Function to display Employee totSal based on empId.

create or replace function RetrieveTotSal57


(id varchar2)return number as tsl number;
begin
select totsal into tsl from EmpSalary57 where eid=id;
return tsl;
end;
/

step-2 : Construct JDBC Application to execute function

Program : [Link]
package test;
import [Link].*;
import [Link].*;
public class DBCon10 {
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
try(s;){
try {
[Link]("[Link]");
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
CallableStatement cs = [Link]
("{call ?:=RetrieveTotSal57(?)}");
[Link]("Enter EmpId:");
String eId = [Link]();
[Link](1, [Link]);
[Link](2, eId);
[Link]();
[Link]("====Details====");
[Link]("Emp-Id:"+eId);
[Link]("Emp-TotSal:"+[Link](1));
}catch(Exception e) {[Link]();}
}//end of try with resource
}
}

o/p:
Enter EmpId:
A111
====Details====
Emp-Id:A111
Emp-TotSal:304800.0
Diagram:

========================================================
Assignment-3:
step-1 : Construct Function to retrieve PhoneNo based on CustId
step-2 : Construct JDBC Application to execute Function
==========================================================
*imp
Transaction Management in JDBC:

define Transaction?
=>set-of-statements executed on a resource or resources using ACID
properties is known as Transaction.

A - Atomicity
C - Consistency
I - Isolation
D - Durability

A - Atomicity
=>Atomicity means all statements in the Transaction are completed
Successfully or not happened Successfully
C - Consistency
=>The resource state which is selected by the user,remains same
until the transaction is completed is known as Consistency.
I - Isolation
=>The process of running multiple users independently is known as
Isolation process.
D - Durability
=>The process of storing Transaction details and making it available
to user,is known as Durability.
==============================================================

Dt : 16/11/2023
faq:
define Transaction Management?
=>The process of controling the transaction from starting to ending is
known as Transaction Management.
Note:
=>JDBC Applications will perform auto-commit operation,which means
Commit-operation is performed automatically
=>Part of Transaction Management the auto-commit operation must be
stopped,which means we perform commit-operation manually.
----------------------------------------------------------------
=>To perform Transaction Management,we use the following methods:
(a)getAutoCommit()
(b)setAutoCommit()
(c)setSavepoint()
(d)releaseSavepoint()
(e)commit()
(f)rollback()

(a)getAutoCommit():
=>getAutoCommit() method is used know the status of commit-operation
syntax:
boolean b1 = [Link]();

(b)setAutoCommit():
=>setAutoCommit() method is used to set auto-commit-operation to 'false'
syntax:
[Link](false);

(c)setSavepoint():
=>setSavepoint() method is used to take one status-point to perform
rollback-operation when transaction-failed
syntax:
Savepoint sp = [Link]();
(d)releaseSavepoint():
=>releaseSavepoint() method is used to delete savepoints.
syntax:
[Link](sp);

(e)commit():
=>commit() method is used to save the data from temporary buffer to DB
product permanently.
syntax:
[Link]();

(f)rollback():
=>rollback() method is used to perform rollback-operation.
syntax:
[Link](sp);
---------------------------------------------------------------
Ex-program:(Demonstrating Transaction Management)

DB Table : BankCutomer57(accno,cname,bal,acctype)
primary key : accno

create table BankCustomer57(accno number(15),cname varchar2(15),


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

insert into BankCustomer57 values(6123456,'Alex',12000,'savings');


insert into BankCustomer57 values(313131,'Raj',500,'savings');

ACCNO CNAME BAL ACCTYPE


---------- --------------- ---------- ---------------
6123456 Alex 12000 savings
313131 Raj 500 savings
-------------------------------------------------------------------

Transaction : Transfer 3000/- from accNo:6123456 to accNo:313131

Statement-1 : Subtract 3000/- from accNo:6123456


Statement-2 : Add 3000/- to accNo:313131

Program : [Link]
package test;
import [Link].*;
import [Link].*;
public class DBCon11 {
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
try(s;){
try {
[Link]("[Link]");
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
[Link]("Commit-status :
"+[Link]());
[Link](false);
[Link]("Commit-status :
"+[Link]());
PreparedStatement ps1 = [Link]
("select * from BankCustomer57 where accno=?");
PreparedStatement ps2 = [Link]
("update BankCustomer57 set bal=bal+? where
accno=?");
Savepoint sp = [Link]();
[Link]("Enter the HomeAccNo:");
long hAccNo = [Link]();
[Link](1, hAccNo);
ResultSet rs1 = [Link]();
if([Link]()) {
float bl = [Link](3);
[Link]("Enter benifiecieryAccNo:");
long bAccNo = [Link]();
[Link](1, bAccNo);
ResultSet rs2 = [Link]();
if([Link]()) {
[Link]("Enter the amt to be
transferred:");
int amt = [Link]();
if(amt<=bl) {
[Link](1, -amt);
[Link](2, hAccNo);
int k = [Link]();//Buffer
Updated

[Link](1, +amt);
[Link](2, bAccNo);
int z = [Link]();//Buffer
Updated

if(k==1 && z==1) {


[Link]();//Database Updated
[Link]("Transaction
Successfull..");
}else {
[Link](sp);
[Link]("Transaction
failed..");
}

}else {
[Link]("Insuffiecient
fund...");
}
}else {
[Link]("Invalid bAccNo...");
}
}else {
[Link]("Invalid homeAccNo...");
}
}catch(Exception e) {[Link]();}
}//end of try with resource
}
}

o/p:
Commit-status : true
Commit-status : false
Enter the HomeAccNo:
6123456
Enter benifiecieryAccNo:
313131
Enter the amt to be transferred:
3000
Transaction Successfull..

ACCNO CNAME BAL ACCTYPE


---------- --------------- ---------- ---------------
6123456 Alex 9000 savings
313131 Raj 3500 savings
====================================================================

Note:
step-1 : set auto-commit-operation to false
step-2 : Take savepoint to perform rollback
step-3 : Execute all sub-statements in Transaction
step-4 : Check all sub-statements are executed successfully or not
step-5 : If all sub-statements are executed successfully then perform
commit-operation,else perform rollback-operation
==================================================================
Assignment:
Update above application by converting else-block messages to catch-block
messages(exception-messages)
=====================================================================
Dt : 17/11/2023
*imp
Connection Pooling in JDBC:
=>The process of organizing multiple pre-initialized database connections
among multiple users,is known as Connection Pooling Concept.

Note:
=>In realtime [Link]<E> is used to hold multiple
Pre-Initialized Database Connections(Connection-Objects)
Hierarchy of Vector<E>:

------------------------------------------------------------
Layout:

Ex-program:
[Link]
package test;
import [Link].*;
import [Link].*;
public class ConnectionPooling
{
public String url,uName,pWord;
public ConnectionPooling(String url,String uName,String pWord)
{
[Link]=url;
[Link]=uName;
[Link]=pWord;
}
public Vector<Connection> v = new Vector<Connection>();
public void addConnectionsToPool()
{
try {
while([Link]()<5)
{
[Link]("Pool is Not full....");
Connection con = [Link]
(url,uName,pWord);
[Link](con);//Adding Connection to Pool
[Link](con);
}//end of loop
if([Link]()==5)
{
[Link]("pool is full...");
}
}catch(Exception e) {[Link]();}
}//end of loop
public Connection userConnectionFromPool()
{
Connection con = [Link](0);
[Link](0);
return con;
}//end of method
public void returnConnectionToPool(Connection con)
{
[Link](con);//Adding Connection back to pool
[Link]("Connection added back to pool...");
}//end of method
}
[Link](MainClass)
package test;
import [Link].*;
public class DBCon12 {
public static void main(String[] args) {
try {
ConnectionPooling cp =
new ConnectionPooling
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
[Link]();
[Link]("Size of Pool : "+[Link]());
[Link]("*****User-1*****");
Connection con1 = [Link]();
[Link](con1);
[Link]("Size of Pool : "+[Link]());
[Link]("****User-2****");
Connection con2 = [Link]();
[Link](con2);
[Link]("Size of Pool : "+[Link]());
[Link]("****User-1*****");
[Link](con1);
[Link]("Size of Pool : "+[Link]());
[Link]("****User-2*****");
[Link](con2);
[Link]("Size of Pool : "+[Link]());
[Link]("====Connections=====");
[Link]((k)->
{
[Link](k);
});
}catch(Exception e) {[Link]();}
}
}
o/p:
Pool is Not full....
[Link].T4CConnection@3159c4b8
Pool is Not full....
[Link].T4CConnection@525f1e4e
Pool is Not full....
[Link].T4CConnection@75f9eccc
Pool is Not full....
[Link].T4CConnection@67e2d983
Pool is Not full....
[Link].T4CConnection@5d47c63f
pool is full...
Size of Pool : 5
*****User-1*****
[Link].T4CConnection@3159c4b8
Size of Pool : 4
****User-2****
[Link].T4CConnection@525f1e4e
Size of Pool : 3
****User-1*****
Connection added back to pool...
Size of Pool : 4
****User-2*****
Connection added back to pool...
Size of Pool : 5
====Connections=====
[Link].T4CConnection@75f9eccc
[Link].T4CConnection@67e2d983
[Link].T4CConnection@5d47c63f
[Link].T4CConnection@3159c4b8
[Link].T4CConnection@525f1e4e
================================================================
Dt : 18/11/2023
*imp
process of Connection Pooling:

Step-1 : User will take the Connection from the pool.


Step-2 : Using Connection user will interact with Database and perform
operations
Step-3 : After Completing all operations on Database,the user will return
the Connection back to the pool
=====================================================================
Summary of Objects created in JDBC:

[Link] Object
[Link] Object
[Link] Object
[Link] Object
[Link] Object
(i)Scrollable ResultSet Object
(ii)NonScrollable ResultSet Object
[Link] Object
(i)JdbcRowSet Object
(ii)CachedRowSet Object
=>WebRowSet Object
(i)FilteredRowSet Object
(ii)JoinRowSet Object
[Link] Object
[Link] Object
[Link] Object
[Link] Object

Diagram:

--------------------------------------------------------------------
faq:
define Metadata?
=>The data which is holding information about other data is known as
Metadata.
=>The following are some important metadata components in JDBC:
[Link]
[Link]
[Link]
[Link]

[Link]:
=>DatabaseMetaData object will hold information about Connection-Object.
syntax:
DatabaseMetaData dmd = [Link]();

[Link]:
=>ParameterMetaData object will hold information about PreparedStatement
Object
syntax:
ParameterMetaData pmd = [Link]();

[Link]:
=>ResultSetMetaData object will hold information about ResultSet Object.
syntax:
ResultSetMetaData rsmd = [Link]();

[Link]:
=>RowSetMetaData Object will hold information about RowSet Objects
syntax:
RowSetMetaData rsd = (RowSetMetaData)[Link]();

Program : [Link]
package test;
import [Link].*;
import [Link].*;
import [Link];
public class DBCon13 {
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
try(s;){
try {
[Link]("[Link]");
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
[Link]("***DatabaseMetaData****");
DatabaseMetaData dmd = [Link]();
[Link]("DB
Version:"+[Link]());
[Link]("DB Driver:"+[Link]());
PreparedStatement ps = [Link]
("select fname,mid,phno from Admin56 where uname=?
and pword=?");
[Link]("***ParameterMetaData****");
ParameterMetaData pmd = [Link]();
[Link]("Count of
Parameters:"+[Link]());
[Link]("Enter the UserName:");
String uName = [Link]();
[Link]("Enter the PassWord:");
String pWord = [Link]();
[Link](1, uName);
[Link](2, pWord);
ResultSet rs = [Link]();
[Link]("****ResultSetMetaData****");
ResultSetMetaData rsmd = [Link]();
int count = [Link]();
[Link]("Count of Column:"+count);
for(int i=1;i<=count;i++)
{
String nm = [Link](i);
[Link]("Column Name : "+nm);
}//end of loop
[Link]("====Details====");
if([Link]()) {
[Link]([Link](1)+"\t"+
[Link](2)+"\t"+[Link](3));
}//end of if
else {
[Link]("Inavlid UName or PWord..");
[Link](0);
}
//RowSetMetaData rsd =
(RowSetMetaData)[Link]();

}catch(Exception e) {[Link]();}
}//end of try with resource
}
}

o/p:
***DatabaseMetaData****
DB Version:11
DB Driver:Oracle JDBC driver
***ParameterMetaData****
Count of Parameters:2
Enter the UserName:
nit.v
Enter the PassWord:
mzu672
****ResultSetMetaData****
Count of Column:3
Column Name : FNAME
Column Name : MID
Column Name : PHNO
====Details====
Venkat v@[Link] 9898981234
===========================================================
Dt : 20/11/2023
*imp
Streams with Database:
define Stream?
=>The contineous flow of data is known as Stream.

Types of Streams:
=>Streams in Java are categorized into two types:
(i)Byte Stream
(ii)Character Stream

(i)Byte Stream:
=>The contineous flow of data in the form of 8-bits is known as
Byte Stream or Binary Stream.
=>Byte Stream supports all multi-media data formats like Audio,Video,
Image,Animation and Text.

(ii)Character Stream:
=>The contineous flow of data in the form of 16-bits is known as
Character Stream or Text Stream.
=>Character Stream is preferable for Text data and not preferable
for Audio,Video,Image and Animations files.

faq:
define Input Stream?
=>The stream coming into JavaProgram is known as Input Stream.

faq:
define Output Stream?
=>The stream going outof JavaProgram is known as Output Stream
---------------------------------------------------------------------
=>The following SQL-types will support Stream data:
(a)BLOB
(b)CLOB

(a)BLOB:
=>BLOB stands for 'Binary Large OBjects' and which support Byte
Stream data.

(b)CLOB:
=>CLOB stands for 'Character Large OBjects' and which support
Character Stream data.
--------------------------------------------------------------------
*imp
Construct JDBC Application to Store Image onto DB product:
step-1 : Create table with name StreamTab57 from SQLCommandLine

create table StreamTab57(id varchar2(10),mfile BLOB,primary key(id));

step-2 : Construct the Application


Program : [Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
public class DBCon14 {
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
try(s;){
try {
[Link]("[Link]");
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
PreparedStatement ps = [Link]
("insert into StreamTab57 values(?,?)");
[Link]("Enter the Id:");
String id = [Link]();
[Link](1, id);
[Link]("Enter the fPath&fName:(Source)");
File f = new File([Link]());
if([Link]()) {
FileInputStream fis=new FileInputStream(f);
[Link](2, fis, [Link]());
int k = [Link]();
if(k>0) {
[Link]("Image Stored Successfully..");
}
}else {
[Link]("Invalif fPath or fName...");
}
[Link]();
}catch(Exception e) {[Link]();}
}//end of try with resource
}
}
o/p:
Enter the Id:
A111
Enter the fPath&fName:(Source)
C:\Images\IMG_4917.JPG
Image Stored Successfully..

Diagram:
======================================================================
*imp
Construct JDBC Application to retrieve image from DB Product:

Program : [Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
public class DBCon15 {
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
try(s;){
try {
[Link]("[Link]");
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
PreparedStatement ps = [Link]
("select * from StreamTab57 where id=?");
[Link]("Enter the id:");
String id = [Link]();
[Link](1, id);
ResultSet rs = [Link]();
if([Link]()) {
Blob b = [Link](2);
byte by[] = [Link](1, (int)[Link]());
[Link]("Enter the fPath&fName:(Destination)");
File f = new File([Link]());
FileOutputStream fos = new FileOutputStream(f);
[Link](by);
[Link]("Image retrieved Successfully...");
[Link]();
}else {
[Link]("Invalid id...");
}
[Link]();
}catch(Exception e) {[Link]();}
}//end of try with resource
}
}
o/p:
Enter the id:
A111
Enter the fPath&fName:(Destination)
D:\Images\[Link]
Image retrieved Successfully...

Diagram:
======================================================================

Dt : 21/11/2023
faq:
define FileInputStream?
=>FileInputStream is a class from [Link] package and which is used to
find the file and opens the file to read byte-stream data.
syntax:
FileInputStream fis = new FileInputStream("fPath&fName");

faq:
define FileOutputStream?
=>FileOutputStream is also a class from [Link] package and which is
used to create a new file and opens the file to write byte-stream
data.
syntax:
FileOutputStream fos = new FileOutputStream("fPath&fName");

faq:
define 'File' class?
=>'File' class is from [Link] package and which is used to find the
properties of file like file_length,file_path,file_exists or not,...
syntax:
File f = new File("fPath&fname");

faq:
define Blob?
=>'Blob' is an interface from [Link] package and which supports to
retrieve byte-stream data from the DB Product.
=>The following are some important methods from 'Blob' interface:
public abstract long length() throws [Link];
public abstract byte[] getBytes(long, int)
throws [Link];

=>we use getBlob() method from 'ResultSet' to create implementation


object for Blob-Interface.
Method Signature of getBlob():
public abstract [Link] getBlob(int)throws [Link];
syntax:
Blob b = [Link](2);
---------------------------------------------------------------
faq:
define getBytes() method?
=>getBytes() method is used to convert byte-stream data into byte-array
syntax:
byte by[] = [Link](1, (int)[Link]());
==================================================================
*imp
Hierarchy of JDBC Statements:

===================================================================
faq:
define 'Wrapper'?
=>'Wrapper' is an interface from [Link] package and which is Parent
interface of '[Link]' interface and '[Link]'
interface.
=>This 'Wrapper' supports binding components to Objects.
(Supports binding process)
=====================================================================
faq:
define 'AutoCloseable'?
=>The resources which are used in try-with-resource statement must be
implementations of 'AutoCloseable' interface,then the resources are
closed automatically.
Note:
=>Connection,Statement,PreparedStatement and CallableStatement can be
used part of try-with-resource statement.
=====================================================================
Dt : 22/11/2023
Ex-program:
JDBC Application to execute create-query from Java Program.

Program : [Link]
package maccess;
import [Link].*;
import [Link].*;
public class DBCon16 {
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
try(s;){
try {
[Link]("[Link]");
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
Statement stm = [Link]();
[Link]("Enter query(Create/insert/update/delete)");
String qr = [Link]();
int k = [Link](qr);
[Link]("The value k:"+k);
if(k>=0) {
[Link]("qurey executed...");
}
[Link]("Enter select query:");
String qr2 = [Link]();
ResultSet rs = [Link](qr2);
while([Link]()) {
[Link]([Link](1)+"\t"+
[Link](2));
}
}catch(Exception e) {[Link]();}
}//end of try with resource
}
}
o/p:
Enter query(Create/insert/update/delete)
insert into Emp7 values('A22','Alex')
The value k:1
qurey executed...
Enter select query:
select * from Emp7
A11 Raj
A22 Alex
===================================================================
faq:
define Batch Processing in JDBC?
=>The process of collecting multiple queries as batch and executing
at-a-time on DB product,is known as Batch Processing.
=>The queries declared in batch must be only NonSelect queries,because
of this reason Batch processing is also known as Batch Update
processing
=>we use the following methods in Batch Processing:
(a)addBatch()
(b)executeBatch()
(c)clearBatch()

(a)addBatch():
=>addBatch() method is used to add query to the batch.
Method Signature:
public abstract void addBatch([Link])throws [Link];

(b)executeBatch():
=>executeBatch() method executed execute batch on DB product.
Method Signature:
public abstract int[] executeBatch()throws [Link];

(c)clearBatch():
=>clearBatch() method is used to delete all queries from the batch and
destroy the batch.
Method Signature:
public abstract void clearBatch() throws [Link];
---------------------------------------------------------------
Ex-program:
Batch:
query-1 : create table emp9(id,name)
query-2 : create table cust9(id,name,phno)
query-3 : insert into emp9
query-4 : insert into cust9

Program : [Link]
package maccess;
import [Link].*;
import [Link].*;
public class DBCon17 {
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
try(s;){
try {
[Link]("[Link]");
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
Statement stm = [Link]();
[Link]("Enter number of queries to be added to batch:");
int n = [Link]([Link]());
[Link]("Enter "+n+" queries..");
for(int i=1;i<=n;i++)
{
[Link]("Enter the query-"+i);
String qr = [Link]();
[Link](qr);
}//end of loop
int k[] = [Link]();
for(int i : k) {
[Link]("value i : "+i);
[Link]("query executed...");
}//end of loop
[Link]();
}catch(Exception e) {[Link]();}
}//end of try
}
}
o/p:
Enter number of queries to be added to batch:
4
Enter 4 queries..
Enter the query-1
create table Emp9(id varchar2(10),name varchar2(15),primary key(id))
Enter the query-2
create table Cust9(id varchar2(10),name varchar2(15),phno number(15),primary key(id))
Enter the query-3
insert into emp9 values('A11','Raj')
Enter the query-4
insert into cust9 values('A11','Raj',989898)
value i : 0
query executed...
value i : 0
query executed...
value i : 1
query executed...
value i : 1
query executed...
=================================================================
Note:
(i)we can perform batch processing using 'Statement' and
'PreparedStatement'
(ii)Batch Processing using 'Statement' we can perform operations on
Multiple DB tables.
(iii)Batch Processing using 'PreparedStatement' we can perform operations
only on single DB Table.
================================================================
faq:
wt is the diff b/w
(i)Procedures
(ii)Batch Processing

=>using procedures we can execute all types of queries,which means we can


execute select and NonSelect queries.
=>Using Batch Processing we can execute only NonSelect queries
====================================================================
faq:
define JDBC driver?
=>The driver which is used to establish connection b/w JavaProgram and
Database product is known as JDBC driver.
(Java DataBase Connectivity driver)

Types of JDBC drivers:


=>JDBC drivers are categorized into four types:
[Link]-ODBC bridge driver(Type-1)
[Link] API driver(Type-2)
[Link] Protocol driver(Type-3)
[Link] driver(Type-4)

[Link]-ODBC bridge driver(Type-1):


=>The JDBC-ODBC driver will use ODBC-driver to connect to the DB product.
=>This JDBC-ODBC driver will convert JDBC method calls into ODBC
function calls,which establishes connection to DB Product.
Diagram:

Advantage:
=>Type-1 driver will connect to any database.

DisAdvatage:
=>Type-1 driver will degrade the performance of an application,because
more conversions are available and which consumes more execution time.

Note:
=>From Java8 version onwards Type-1 driver support is not available.
---------------------------------------------------------------
faq:
define ODBC driver?
=>ODBC stands for Open DataBase Connectivity and this ODBC driver will
support connect to any type of database.
=>ODBC driver internally having c/c++ code and which is Platform
dependent driver.
=======================================================================
Dt : 23/11/2023
[Link] API driver(Type-2):
=>Native API driver will take the support of Database Client Libraries
to establish connection to Database product.
=>when we use Native API driver then the Client Computer must be
installed with Database related Client Libraries.

Diagram:

Advantage:
=>In Type-2 driver ODBC-driver is not involved and which saves the
execution time and generate HighPerformance of an application.

DisAdvantage:
=>The Client Computer must be installed with Database related Client
libraries and which makes the application Database dependent.
===============================================================
[Link] Protocol driver(Type-3):
=>Network Protocol driver will take the support of Middleware Servers
to Communicate database product.
Diagram:

Advantage:
=>Middleware Servers will hold database related code.
=>ODBC-driver and Database related Client libraries are not involved.

DisAdvantage:
=>In Network Protocol driver,the network related components and code
invloved in execution process and degrade the performance of an
application.
======================================================================
[Link] driver(Type-4)
=>Thin driver will take the support of Database Network protocol to
Communicate with database product directly.
=>Thin driver is Pure Java Driver and Platform independent driver,
and which generate HighPerformance of an application.

Diagram:
Advantage:
=>HighPerformance driver
=>ODBC-driver,database related Client Libraries and MiddleWare Servers
are not involved.
======================================================================
*imp
Summary of Objects created from CoreJava:
[Link] defined Class Objects
[Link]-Objects
[Link]-Objects
[Link]-Objects
[Link]<E>-Objects
[Link]<K,V>-Objects
[Link]<E>-Objects

Summary of Objects created in JDBC:


[Link] Object
[Link] Object
[Link] Object
[Link] Object
[Link] Object
(i)Scrollable ResultSet Object
(ii)NonScrollable ResultSet Object
[Link] Object
(i)JdbcRowSet Object
(ii)CachedRowSet Object
=>WebRowSet Object
(i)FilteredRowSet Object
(ii)JoinRowSet Object
[Link] Object
[Link] Object
[Link] Object
[Link] Object
====================================================================
faq:
define Serialization process?
=>The process of converting Object state into binary Stream or Byte
Stream is known as Serialization process.

Coding Rule:
=>To perform Serialization process the class must be implemented from
'[Link]' interface.
===================================================================
=>Based on Serialization process the Objects in Java are categorized
into two types:
(i)Serializable Objects
(ii)NonSerializable Objects
(i)Serializable Objects:
=>The Objects which are generated from implementation classes of
"[Link]" interface are Serializable Objects.
Ex:
All CoreJava Objects

(ii)NonSerializable Objects:
=>The Objects which are generated from NonImplementation classes of
"[Link]" interface are NonSerializable Objects.
Ex:
All JDBC Objects
==================================================================
faq:
why we have to perform Serialization process?
=>Through Serialization process we can make objects available in the
form of Stream and can be moved on the Network from one location to
another location.

Conclusion:
=>Serializable CoreJava Objects can be moved on the Network directly,
but NonSerializable JDBC Objects cannot be moved on the Network
directly
======================================================================
Dt : 24/11/2023
Java Technology:
=>The process of applying the knowledge for realtime world application
development is known as Technology.
=>Java Technology internally categorized into two parts:
[Link]
[Link]
[Link]:
=>Java is a Language because it is having its own syntax(grammer),
alphabets(programming components) and Construction rules.

[Link]:
=>Java is also a PlatForm,beacuse it is having its own environment
for execution.
=>Java Paltforms are categorized into the following:
(a)JavaSE
(b)JavaEE
(c)JavaME

(a)JavaSE:
=>JavaSE means 'Java Standard Edition' and which is used for NonServer
application development.
=>JavaSE means 'CoreJava+JDBC'

(b)JavaEE:
=>JavaEE means 'Java Enterprise Edition' and which is used for Server
based application Development.
=>Part of JavaEE,AdvJava covers Servet and JSP.

(c)JavaME:
=>JavaME means 'Java Micro Edition' and which is used for Machine and
Mobile related application development.
=>JavaME also known as Machine Edition or Mobile Edition.
=====================================================================
*imp
Servlet Programming:(Part-2)
define Servlet?
=>The platform independent JavaProgram which is executed in Server
environment and interacts with user through WebBrowser is knwon as
Servlet Program or Server Program.
=>Servlet Programs will extent the functionality of Server.
=>Servlet program will accept the request from the User and provides the
response.

Diagram:

------------------------------------------------------------------
faq:
define Web Application?
=>The application which is executed in Web Environment or Internet
environment is known as Web Application.
=>These WebApplications will interact with WebBrowsers.
--------------------------------------------------------------------
=>These Web Applications are loaded to Web-Container of Server for
execution.
------------------------------------------------------------------
faq:
define Server?
=>Server means Service provider,which means accepts the request and
provides the response.
=>Servers are categorized into two types:
[Link] Servers
[Link] Servers

[Link] Servers:
=>Web Servers will have only Web-Container.
=>Web Servers are used to execute Web Applications.
=>Web Servers will accept request from HTTP protocol.
Ex:
Tomcat

[Link] Servers:
=>Application Servers will have both Web-Container and EJB Container
(EJB - Enterprise Java Bean)
=>Applications Servers are used to execute both Web Applications and
Enterprise Applications.
=>Application Servers will request from HTTP,RMI and RPC protocols
(RMI - Remote Method Inovacation)
(RPC - Remote Procedure Call)
Ex:
WebSphere,JBoss,IIS,...
===============================================================
Dt : 25/11/2023
*imp
Installing Web Server(Tomcat Server):

step-1 : Download Tomcat9 and above using the following link


Link=> [Link]

step-2 : Install Tomcat Server

while installation process,


Select the type of install : Full
(click on Next)
Server Shutdown Port : 8089

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

User Name :V
Password : nit
(click on Next)

step-3 : start the Tomcat Server

=>To Start Server,click 'startup' or 'Tomcat9w' file from 'bin' folder


of Tomcat
C:\Tomcat 9.0\bin

step-4 : Check Tomact server responding to WebBrowser or not,using the


following url:
[Link]

step-5 : stop the Tomcat Server


=>To Stop Server,click 'shutdown' or 'Tomcat9w' file from 'bin' folder
of Tomcat
C:\Tomcat 9.0\bin

=================================================================
*imp
Servlet API:
=>'[Link]' package is known as Servlet-API
=>'[Link]' interface is a root of Servlet-Programming or
Servlet-API.
=>The following are some important methods of 'Servlet' interface:
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()

[Link]():
=>we use init() method to perform initialization process,which means
making the programming components ready for service() method.
Method Signature:
public abstract void init([Link])
throws [Link];

[Link]():
=>Using service() method we provide service to user,which means accepts
the request and provides the response.
Method Signature:
public abstract void service([Link],
[Link]) throws [Link],
[Link];

[Link]():
=>we use destroy() method to perform destroying process.
Method Signature:
public abstract void destroy();

Note:
=>init(),service() and destroy() methods are known as Life-cycle methods
and which are executed automatically in the same order.

[Link]():
=>getServletInfo() method is coded with servlet information and which
is not Life-cycle method.
Method Signature:
public abstract [Link] getServletInfo();

[Link]():
=>getServletConfig() method is used get Servlet Configuratiuon details
and which is alos not Life-cycle method.
Method Signature:
public abstract [Link] getServletConfig();
===============================================================
Dt : 28/11/2023
Hierarchy of 'Servlet' interface:

=================================================================
=>In the process of constructing Servlet programs,we use any one of the
following model:
(a)Servlet-program implementing from 'Servlet' interface
(b)Servlet-program extending from 'GenericServlet' AbstractClass
(c)Servlet-program extending from 'HttpServlet' AbstractClass

(a)Servlet-program implementing from 'Servlet' interface:


=>If the Servlet-program implemented from 'Servlet' interface,then we
must Construct the body for all five abstract methods of 'Servlet'
interface.
Diagram:

-------------------------------------------------------
(b)Servlet-program extending from 'GenericServlet' AbstractClass:
=>If the Servlet-program extends from 'GenericServlet' AbstractClass,
then we must construct body for only service() method and remaining
methods are optional methods.
Diagram:

(c)Servlet-program extending from 'HttpServlet' AbstractClass:


=>If the Servlet-program extends from 'HttpServlet' AbstractClass,then
all the methods are optional methods.
init() - Initialization
service() - any type of request(POST/GET)
doPost() - for POST request
doGet() - for GET request
destroy() - for destroying process
Diagram:

--------------------------------------------------------------------
Conclusion:
=>The Servlet-Objects generated from 'Servlet' interface are
NonSerializable Objects
=>The Servlet-Objects generated from 'GenericServlet' and 'HttpServlet'
are Serializable Objects.
====================================================================
*imp
Construct Servlet Application(Web Application) using IDE Eclipse:
step-1 : Open IDE Eclipse,while opening name the WorkSpace and click
'Launch'
step-2 : Create 'Dynamic Web Project'

Click on File->New->Project->Web->select 'Dynamic Web Project' and click


on 'Next'->name the project and click 'Finish'

step-3 : Add '[Link]' file to Project

RightClick on Project->Build Path->Configure Build Path->Libraries->


select 'Classpath' and click 'Add Exteranal Jars'->Browse and Select
'[Link]' file from 'lib' folder of Tomcat->Open->Apply->
Apply nad Close

step-4 : Add Web Server(Tomcat) to IDE Eclipse(One time process)

Click on 'Servers'->click on 'click this link to create a new Server'->


select the required Server and click 'Next'->Browse 'Tomcat Installation
Directory->select the Folder and click 'Finish'

step-5 : Construct HTML file

RightClick on webapp->new->HTML file->name the file and click 'Finish'

[Link]

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

step-6 : Construct [Link] file(to start the execution process)

RightClick on WEB-INF->new->Other->XML->XML file->name the file as


"[Link]" and click 'Finish'

[Link]

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


<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>

step-7 : Create package in 'src/main/java' of Java Resources

step-8 : Construct Servlet-programm in package

[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/dis")
public class DisplayServlet extends GenericServlet
{
@Override
public void init()throws ServletException
{
//NoCode
}
@Override
public void service(ServletRequest req,ServletResponse res)throws
ServletException,IOException
{
PrintWriter pw = [Link]();
[Link]("text/html");
String uName = [Link]("uname");
String mId = [Link]("mid");
[Link]("*****DisplayServlet****");
[Link]("<br>UserName:"+uName);
[Link]("<br>MailId:"+mId);
}
@Override
public void destroy()
{
//NoCode
}
}

step-9 : Deploy Web Application into Server for execution

RightClick on Project->Run AS->Run on Server->select the server and click


'Finish'

[Link]
======================================================================
Dt : 29/11/2023
Execution flow of above application:
[Link]
----------------------------------------------------------------------
ServletContext:
=>ServletContext is an interface from [Link] package and which
is instantiated automatically when Web-Application deployed into
Server.
=>This ServletContext object is loaded with Server Information.

ServletConfig:
=>ServletConfig is an interface from [Link] package and which is
instantiated automatically when Servlet-program loaded for execution.
=>This ServletConfig Object is loaded with Servlet_name.

Note:
=>After ServletConfig Object instantiation completed,then Servlet
Object is created.
=>After Servlet Object creation completed,then we can find three life
cycle methods and executed automatically

ServletRequest:
=>ServletRequest is an interface from [Link] package and which is
instantiated automatically while service()-method execution.
=>This ServletRequest object will hold the data submitted from HTML
forms.

ServletResponse:
=>ServletResponse is an interface from [Link] package and which
is instantiated automatically while service()-method execution.
=>This ServletResponse object is loaded with response data or output
data.

faq:
define getWriter() method?
=>getWriter() method is from ServletResponse and which is used to
create object for "[Link]" Class.
Method Signature:
public abstract [Link] getWriter()
throws [Link];
syntax:
PrintWriter pw = [Link]();

faq:
define setContentType() method?
=>setContentType() method will specify the type of data sending as
output(sending as response).
=>This setContentType() method is also available from 'ServletResponse'
Method Signature:
public abstract void setContentType([Link]);

syntax:
[Link]("text/html");
faq:
define getParameter() method?
=>getParameter() method is used to get the data from ServletRequest
object into Servlet-program.
=>This getParameter() method is from "ServletRequest".
Method Signature:
public abstract [Link] getParameter([Link]);

syntax:
String var = [Link]("para_name");
====================================================================
Assignment-1:
Construct Servlet-Application to read and display Product details.
(code,name,price,qty)

Assignment-2:
Construct Servlet-Application to read and display Customer details.
(CustId,CustName,CustCity,CustState,CustMailId,CustPhNo)
===================================================================
Dt : 1/12/2023
*imp
RequestDispatcher:
=>RequestDispatcher is an interface from [Link] package and which
is used to perform the following Servlet-Communications:
(i)Servlet to Servlet Communication
(ii)Servlet to HTML Communication
(iii)Servlet to JSP Communication
=>Servlet-Communications are categorized into two types:
(a)forward communication
(b)include communication
(a)forward communication:
=>In forward Communication process,ServletProgram1 will take the request
and forwards the request to ServletProgram2,in this process the
response is generated from ServletProgram2.
=>This ServletProgram2 can be replace with HTML file or JSP file.
=>we use forward() method from 'RequestDispatcher' to perform forward
communication process.
Method Signature of forward():
public abstract void forward([Link],
[Link]) throws [Link],
[Link];

Diagram:

-------------------------------------------------------------------
(b)include communication:
=>In include communication process,the ServletProgram1 will take the
request and generate response,but the response is included with the
response of ServletProgram2.
=>This ServletProgram2 can be replaced with HTML file or JSP file.
=>we use include() method from 'RequestDispatcher' to perform include
Communication process.
Method Signature of include():
public abstract void include([Link],
[Link]) throws [Link],
[Link];

Diagram:

======================================================================
=>we use getRequestDispatcher() method from 'ServletRequest' to create
implementation object for 'RequestDispatcher' interface.
Method Signature of getRequestDispatcher();
public abstract [Link]
getRequestDispatcher([Link]);
syntax:
RequestDispatcher rd = [Link]("Servlet-url/HTML/JSP");

[Link](req,res);
[Link](req,res);
================================================================
Ex-Application:(Demonstrating RequestDispatcher)

Layout:

[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="choice" method="post">
Enter the Value:<input type="text" name="val"><br>
<input type="submit" value="Factorial" name="s1">
<input type="submit" value="Prime" name="s1">
</form>
</body>
</html>
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/choice")
public class ChoiceServlet extends GenericServlet
{
@Override
public void service(ServletRequest req,ServletResponse res)throws
ServletException,IOException{
String s1 = [Link]("s1");
if([Link]("Factorial")) {
RequestDispatcher rd =
[Link]("xyz");
[Link](req, res);
}else {
RequestDispatcher rd =
[Link]("pqr");
[Link](req, res);
}
}
}
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/xyz")
public class FactorialServlet extends GenericServlet{
@Override
public void service(ServletRequest req,ServletResponse res)throws
ServletException,IOException{
PrintWriter pw = [Link]();
[Link]("text/html");
int n = [Link]([Link]("val"));
int fact=1;
for(int i=n;i>=1;i--)
{
fact=fact*i;
}
[Link]("Factorial : "+fact+"<br>");
RequestDispatcher rd =
[Link]("[Link]");
[Link](req, res);
}
}
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/pqr")
public class PrimeServlet extends GenericServlet{
@Override
public void service(ServletRequest req,ServletResponse res)throws
ServletException,IOException{
PrintWriter pw = [Link]();
[Link]("text/html");
int n = [Link]([Link]("val"));
int count=0;
for(int i=1;i<=n;i++)
{
if(n%i==0)
{
count++;
}
}
if(count==2) [Link]("Prime Number..<br>");
else [Link]("Not Prime Number...<br>");
RequestDispatcher rd =
[Link]("[Link]");
[Link](req, res);
}
}
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
=============================================================
Assignment:
Construct Servlet Application to perform the following operations
Add,Sub,Mul,Div,ModDiv,Greater,Smaller
===============================================================
Dt : 2/12/2023

*imp
JSP Programming:
=>JSP stands for 'Java Server Page' and which is response from Web-App.
=>JSP is more simple when compared with Servlet-programming,because JSP
is tag-based-programming language.
=>In JSP,the programs are saved with (.jsp) as an extention.
=>JSP programs will hold both HTML-Code and Java-Code.
=>JSP used the followimg tags to write Java-code in JSP programs:
[Link] tags
[Link] tags
[Link] tags

[Link] tags:
=>The Scripting tags are used to write JavaCode in JSP programs.
=>These Scripting tags are categorized into the following:
(a)Scriptlet tag
(b)Expression tag
(c)Declarative tag

(a)Scriptlet tag:
=>Scriptlet tag is used to write Normal JavaCode or ServletCode in JSP
programs.
syntax:
<% code %>

(b)Expression tag:
=>Expression tag is used to assign the value to variable or used to
display the data to WebBrowser directly.
syntax:
<%= value/Expression %>

(c)Declarative tag:
=>Declarative tag is used to declare variables and methods in JSP
Programs.
syntax:
<%! Variables;Methods %>
---------------------------------------------------------------
[Link] tags:
=>The tags which are used to specify the directions in translation
process of JSP Programs.
=>Directive tags are categorized into the following:
(a)@page
(b)@include
(c)@taglib

(a)@page:
=>'@page' will specify Langauge used in JSP,contextType,pageEncoding,
importing and so on...
(Specifications about the JSP page)
syntax:
<%@page ... %>

(b)@include:
=>'@include' will specify which page must be included to current running
JSP program
syntax:
<%@include file="File_name"/%>

(c)@taglib:
=>'@taglib' is used to link external libraries to current JSP program.
syntax:
<%@tablib ....%>
---------------------------------------------------------------------
[Link] tags:
=>Action tage used to perform some actions related to JSP programs while
execution process.
=>These Action tage are categorized into the following:
(a)<jsp:include>
(b)<jsp:forward>
(c)<jsp:param>
(d)<jsp:useBean>
(e)<jsp:setProperty>
(f)<jsp:getProperty>
======================================================================
Ex-application:(Demonstrating Communication b/w Servlet and JSP)

Layout:

[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="dis" 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>
<input type="submit" name="Dispaly">
</form>
</body>
</html>
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/dis")
public class ControllerServlet extends GenericServlet{
@Override
public void service(ServletRequest req,ServletResponse res)throws
ServletException,IOException{
RequestDispatcher rd =
[Link]("[Link]");
[Link](req, res);
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String code = [Link]("pcode");
String name = [Link]("pname");
float price =
[Link]([Link]("pprice"));
int qty = [Link]([Link]("pqty"));
[Link]("Code="+code);
[Link]("<br>Name="+name);
[Link]("<br>Price="+price);
[Link]("<br>Qty="+qty);
%>
</body>
</html>
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
====================================================================
Dt : 4/12/2023
define Java Bean Class?
=>The class which is constructed with the following rules is known as
Java Bean Class.
Rule-1 : The class must be implemented from '[Link]'
interface
Rule-2 : The variables declared in the class must be 'private' variables
Rule-3 : The Class must be declared with 0-argument Constructor or
0-parameter Constructor.
Rule-4 : The class must be declared with "Getter" and "Setter" methods.

Note:
=>These Bean-classes will generate bean-objects and the bean-objects will
hold data going onto Database product and also will hold coming from
Database product.
(bean-objecst are intermediate storages b/w Servlet-program and Database
product)
----------------------------------------------------------------------
faq:
define Getter methods?
=>The methods which are used to get the data from the objects are known
as Getter methods.

faq:
define Setter methods?
=>The methods which are used to set the data for the objects are known as
Setter methods.

Coding rule of Getter and Setter methods:


=>Every variable in the class must have its own 'Getter' method. and
'Setter' method.
=======================================================================
faq:
define DAO?
=>DAO stands for 'Data Access Object' and which is separate layer in
MVC(Model View Controller) to hold database related code,which means
holding persistent logics.

Diagram:
=======================================================================
*imp
Objects in ServletProgramming:

========================================================================
*imp
"attribute" in ServletProgramming"
=>'attribute' is a variable in ServletProgramming which can be added to
ServletContext object,ServletRequest object and HttpSession Object.
=>The following are some important methods related to 'attribute':
(i)setAttribute()
(ii)getAttribute()
(iii)removeAttribute()
(iv)getAttributeNames()

(i)setAttribute():
=>setAttribute() method is used to add variable to objects.
Method Signature:
public abstract void setAttribute([Link],[Link]);

(ii)getAttribute():
=>getAttribute() method is used to get the attribute from the Objects.
Method Signature:
public abstract [Link] getAttribute([Link]);

(iii)removeAttribute():
=>removeAttribute() method is used to remove the attribute from the
Objects.
Method Signatute:
public abstract void removeAttribute([Link]);

(iv)getAttributeNames():
=>getAttributeNames() method is used to get all attribute names from the
Objects.
Method Signature:
public abstract [Link]<[Link]>
getAttributeNames();

========================================================================
faq:
define request?
=>The query which is generated from the WebBrowser(Client) to Server
program is known as request.
=>requests generated from the Client are categorized into two types:
[Link] request
[Link] request

[Link] request:
=>The request which is generated to send data to Server is known as
POST request.
=>Through POST request we can send all types of data,which means we can
send Text,Audio,Video,Image and Animation data.
=>Through POST request we can send UnLimited data.
=>The POST request data is secure,because the data is encapsulated to the
body-part of HTTP protocol.
=>We use the following syntax to raise POST request:
<form action="url" method="POST">
.....
</form>
=>we use doPost() method from 'HttpServlet' to accept POST request.
Method Signature of doPost():
protected void doPost([Link],
[Link])throws
[Link],[Link];
-----------------------------------------------------------------
[Link] request:
=>The request which is generated to get the data from the server is known
as GET request.
=>Through GET request we can send only Text data.
=>Through GET request we can send only 4KB or 8KB data.
=>The GET request data is not secure,because the data is added to query
String and displayed in AddressBar.
=>We use the following four ways to raise GET request:
(i)declare method="GET" in <form> tag
syntax:
<form action="url" method="GET">
...
</form>
(ii)declare <form> tag without "method"
syntax:
<form action="url">
...
</form>
(iii)The request raised through hyperlinks is GET request
(iv)Raising request by declared servlet-url-pattern in AddressBar is
GET request
=>we use doGet() method from [Link] to accept
GET request.
Method Signature of doGet():
protected void doGet([Link],
[Link])throws
[Link],[Link];
==================================================================
Dt : 5/12/2023
Ex-Application:
Construct Servlet-Application to perform the following operations:
[Link]
[Link]

DB Table : Product57(code,name,price,qty)

Layout:
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="[Link]">AddProduct</a>
<a href="view">ViewProducts</a>
</body>
</html>
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="add" method="post">
ProductCode:<input type="text" name="code"><br>
ProductName:<input type="text" name="name"><br>
ProductPrice:<input type="text" name="price"><br>
ProductQty:<input type="text" name="qty"><br>
<input type="submit" value="AddProduct">
</form>
</body>
</html>
[Link]
package test;
import [Link].*;
@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) {
[Link] = code;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
[Link] = price;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
[Link] = qty;
}

[Link](Interface)
package test;
public interface DBInfo
{
public static final String
dbUrl="jdbc:oracle:thin:@localhost:1521:xe";
public static final String uName="system";
public static final String pWord="manager";

[Link]
package test;
import [Link].*;
import static [Link].*;
public class DBConnection
{
private static Connection con=null;
private DBConnection() {}
static
{
try {
[Link]("[Link]");
con = [Link](dbUrl,uName,pWord);
}catch(Exception e) {[Link]();}
}
public static Connection getCon()
{
return con;
}
}
[Link]
package test;
import [Link].*;
public class AddProductDAO
{
public int k=0;
public int insert(ProductBean pb)
{
try {
Connection con = [Link]();
//Access Database connection
PreparedStatement ps = [Link]
("insert into Product57 values(?,?,?,?)");
[Link](1, [Link]());
[Link](2, [Link]());
[Link](3, [Link]());
[Link](4, [Link]());
k = [Link]();
}catch(Exception e) {[Link]();}
return k;
}
}

[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/add")
public class AddProductServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req,
HttpServletResponse res)throws ServletException,
IOException{
ProductBean pb = new ProductBean();
[Link]([Link]("code"));
[Link]([Link]("name"));
[Link]([Link]([Link]("price")));
[Link]([Link]([Link]("qty")));
int k = new AddProductDAO().insert(pb);
if(k>0) {
[Link]("msg", "Product Added Successfully..<br>");
RequestDispatcher rd =
[Link]("[Link]");
[Link](req, res);
}
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String msg = (String)[Link]("msg");
[Link](msg);
%>
<a href="[Link]">AddProduct</a>
<a href="view">ViewProducts</a>
</body>
</html>
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
===================================================================
Asignment:
Construct Servlet application to perform the following operations:
[Link]
[Link]

DB Table : Employee57(eid,ename,edesg,bsal,hra,da,totsal)
===================================================================
Dt : 6/12/2023
Layout:
[Link]
package test;
import [Link].*;
import [Link].*;
public class ViewProductsDAO
{
public ArrayList<ProductBean> al = new ArrayList<ProductBean>();
public ArrayList<ProductBean> retrieve()
{
try {
Connection con = [Link]();
PreparedStatement ps = [Link]
("select * from Product57");
ResultSet rs = [Link]();
while([Link]()) {
ProductBean pb = new ProductBean();
[Link]([Link](1));
[Link]([Link](2));
[Link]([Link](3));
[Link]([Link](4));
[Link](pb);//Bean Object added to ArrayList
}//end of loop
}catch(Exception e) {[Link]();}
return al;
}
}

[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/view")
public class ViewProductsServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
ArrayList<ProductBean> al = new ViewProductsDAO().retrieve();
[Link]("list", al);
RequestDispatcher rd =
[Link]("[Link]");
[Link](req, res);
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="[Link].*,[Link]"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
ArrayList<ProductBean> al =
(ArrayList<ProductBean>)[Link]("list");
if([Link]()==0){
[Link]("No Product available...<br>");
}else{
Iterator<ProductBean> it = [Link]();
while([Link]()){
ProductBean pb = [Link]();
[Link]([Link]()+"&nbsp&nbsp"+
"&nbsp&nbsp"+[Link]()+"&nbsp&nbsp"+

[Link]()+"&nbsp&nbsp"+[Link]()+"<br>");
}
}
%>
<jsp:include page="[Link]"/>
</body>
</html>

=================================================================
Asignment:(Update Assignment)
Construct Servlet application to perform the following operations:
[Link]
[Link]
[Link]

DB Table : Employee57(eid,ename,edesg,bsal,hra,da,totsal)
===================================================================
Summary:
Dt : 7/12/2023
Session Tracking in Servlet Programming:
define 'Session'?
=>The time interval b/w login to logout is known as Session.

define Session Management?


=>The process of recording the state of user and managing the state of
user until user-logout,is known as Session Management or Session
Tracking.
=>The following are some important Session Tracking techniques:
[Link]
[Link]
[Link] re-write
[Link] form fields

[Link]:
=>The small piece of information available b/w multiple requests is
knwon as cookie.
=>The cookie is generated from Server-application,but Stored in Web
Browser to track the user.
=>These cookies are categorized into two types:
(i)persistent cookies
(ii)NonPersistent cookies
(i)persistent cookies:
=>persistent cookies will be stored and available in WebBrowsers until
User logout.
(ii)NonPersistent cookies:
=>NonPersistent cookies will be destroyed automatically when WebBrowser
is closed.
Note:
=>we use '[Link]' class to construct Cookie Session
Tracking process.
=>The following are some important methods from 'Cookie' class:
public [Link]([Link], [Link]);

public void setMaxAge(int);


public int getMaxAge();

public [Link] getName();

public void setValue([Link]);


public [Link] getValue();

Hierarchy of Cookie:

Note:
=>Cookie-Objects are Serializable objects and Cloneable Objects.
=====================================================================
Ex-Application : UserApp_Cookie_Session_Tracking

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

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


fname varchar2(15),lname varchar2(15),addr varchar2(15),mid varchar2(25),
phno number(15),primary key(uname));

Layout:

[Link]
<!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="[Link]">NewUser?</a>
</form>
</body>
</html>
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="reg" method="post">
UserName:<input type="text" name="uname"><br>
Password:<input type="password" name="pword"><br>
FirstName:<input type="text" name="fname"><br>
LastName:<input type="text" name="lname"><br>
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>
</html>
[Link]
package test;
public interface DBInfo
{
public static final String
dbUrl="jdbc:oracle:thin:@localhost:1521:xe";
public static final String uName="system";
public static final String pWord="manager";

[Link]
package test;
import [Link].*;
import static [Link].*;
public class DBConnection
{
private static Connection con=null;
private DBConnection() {}
static
{
try {
[Link]("[Link]");
con = [Link](dbUrl,uName,pWord);
}catch(Exception e) {[Link]();}
}
public static Connection getCon()
{
return con;
}
}
[Link]
package test;
import [Link].*;
@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) {
[Link] = uName;
}
public String getpWord() {
return pWord;
}
public void setpWord(String pWord) {
[Link] = pWord;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
[Link] = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
[Link] = lName;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
[Link] = addr;
}
public String getmId() {
return mId;
}
public void setmId(String mId) {
[Link] = mId;
}
public long getPhNo() {
return phNo;
}
public void setPhNo(long phNo) {
[Link] = phNo;
}

[Link]
package test;
import [Link].*;
public class RegisterDAO {
public int k=0;
public int register(UserBean ub) {
try {
Connection con = [Link]();
PreparedStatement ps = [Link]
("insert into UserReg57 values(?,?,?,?,?,?,?)");
[Link](1, [Link]());
[Link](2, [Link]());
[Link](3, [Link]());
[Link](4, [Link]());
[Link](5, [Link]());
[Link](6, [Link]());
[Link](7, [Link]());
k = [Link]();
}catch(Exception e) {[Link]();}
return k;
}
}

[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/reg")
public class RegServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
UserBean ub = new UserBean();
[Link]([Link]("uname"));
[Link]([Link]("pword"));
[Link]([Link]("fname"));
[Link]([Link]("lname"));
[Link]([Link]("addr"));
[Link]([Link]("mid"));
[Link]([Link]([Link]("phno")));

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


if(k>0) {
[Link]("msg","User Registered Successfully..<br>");
RequestDispatcher rd =
[Link]("[Link]");
[Link](req, res);
}
}
}

[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String msg = (String)[Link]("msg");
[Link](msg);
%>
<jsp:include page="[Link]"/>
</body>
</html>
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
==================================================================
Dt : 8/12/2023
Layout:

[Link]
package test;
import [Link].*;
public class LoginDAO {
public UserBean ub=null;
public UserBean login(String uName,String pWord) {
try {
Connection con = [Link]();
PreparedStatement ps = [Link]
("select * from UserReg57 where uname=? and
pword=?");
[Link](1, uName);
[Link](2, pWord);
ResultSet rs = [Link]();
if([Link]()) {
ub = new UserBean();
[Link]([Link](1));
[Link]([Link](2));
[Link]([Link](3));
[Link]([Link](4));
[Link]([Link](5));
[Link]([Link](6));
[Link]([Link](7));
}
}catch(Exception e) {[Link]();}
return ub;
}
}

[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/log")
public class LoginServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
UserBean ub =new LoginDAO().login([Link]("uname"),
[Link]("pword"));
if(ub==null) {
[Link]("msg","Invalid Login process...<br>");
RequestDispatcher rd = [Link]("[Link]");
[Link](req, res);
}else {
ServletContext sct = [Link]();
//Getting the reference of ServletContext
[Link]("ubean", ub);
//Adding attribute to Context
Cookie ck = new Cookie("name",[Link]());
[Link](ck);//Adding Cookie to response
RequestDispatcher rd = [Link]("[Link]");
[Link](req, res);
}
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String msg = (String)[Link]("msg");
[Link](msg);
%>
<jsp:include page="[Link]"/>
</body>
</html>
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="[Link]"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
UserBean ub = (UserBean)[Link]("ubean");
[Link]("Welcome User : "+[Link]()+"<br>");
%>
<a href="view">ViewProfile</a>
<a href="logout">Logout</a>
</body>
</html>
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/view")
public class ViewProfileServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
Cookie c[] = [Link]();
if(c==null) {
[Link]("msg","Session Expired..<br>");
RequestDispatcher rd = [Link]("[Link]");
[Link](req, res);
}else {
String fName = c[0].getValue();
[Link]("fname", fName);
RequestDispatcher rd =
[Link]("[Link]");
[Link](req, res);
}
} }
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="[Link]"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String fName = (String)[Link]("fname");
UserBean ub = (UserBean)[Link]("ubean");
[Link]("Page belongs to : "+fName+"<br>");
[Link]([Link]()+"&nbsp&nbsp"+[Link]()+"&nbsp&nb
sp"+
[Link]()+"&nbsp&nbsp"+[Link]()+"&nbsp&nbsp"+
[Link]()+"<br>");
%>
<a href="logout">Logout</a>
</body>
</html>
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/logout")
public class LogoutServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
Cookie c[] = [Link]();
if(c==null) {
[Link]("msg", "Session Expired...");
}else {
ServletContext sct = [Link]();
[Link]("ubean");
c[0].setMaxAge(0);
[Link](c[0]);
[Link]("msg", "User loggedout Successfully..<br>");
}
RequestDispatcher rd = [Link]("[Link]");
[Link](req, res);
} }
=============================================================
Dt : 9/12/2023
Layout:
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/edit")
public class EditProfileServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
Cookie c[] = [Link]();
if(c==null) {
[Link]("msg", "Session Expired...<br>");
RequestDispatcher rd = [Link]("[Link]");
[Link](req, res);
}else {
String fName = c[0].getValue();
[Link]("fname",fName);
RequestDispatcher rd = [Link]
("[Link]");
[Link](req, res);
}
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="[Link]"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String fName = (String)[Link]("fname");
UserBean ub = (UserBean)[Link]("ubean");
[Link]("Page belongs to : "+fName+"<br>");
%>
<form action="update" method="post">
Address:<input type="text" name="addr" value=<%=[Link]()
%>><br>
MailId:<input type="text" name="mid" value=<%=[Link]()
%>><br>
PhoneNo:<input type="text" name="phno" value=<%=[Link]()
%>><br>
<input type="submit" value="UpdateProfile">
</form>
</body>
</html>

[Link]
package test;
import [Link].*;
public class UpdateProfileDAO {
public int k=0;
public int update(UserBean ub) {
try {
Connection con = [Link]();
PreparedStatement ps = [Link]
("update UserReg57 set addr=?,mid=?,phno=? where
uname=? and pword=?");
[Link](1, [Link]());
[Link](2, [Link]());
[Link](3, [Link]());
[Link](4, [Link]());
[Link](5, [Link]());
k = [Link]();
}catch(Exception e) {[Link]();}
return k;
}
}
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/update")
public class UpdateProfileServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
Cookie c[] = [Link]();
if(c==null) {
[Link]("msg", "Session Expired...<br>");
RequestDispatcher rd =
[Link]("[Link]");
[Link](req, res);
}else {
ServletContext sct = [Link]();
//Accessing the reference of ServletContext Object
UserBean ub = (UserBean)[Link]("ubean");
[Link]([Link]("addr"));
[Link]([Link]("mid"));
[Link]([Link]([Link]("phno")));
int k = new UpdateProfileDAO().update(ub);
String fName = c[0].getValue();
[Link]("fname", fName);
if(k>0) {
[Link]("msg", "Profile Updated Successfully..<br>");
}
RequestDispatcher rd = [Link]
("[Link]");
[Link](req, res);
}
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String fName = (String)[Link]("fname");
String msg = (String)[Link]("msg");
[Link]("Page belongs to : "+fName+"<br>");
[Link](msg);
%>
<a href="view">ViewProfile</a>
<a href="logout">Logout</a>
</body>
</html>
====================================================================
Assignment:
ApplicationName : EmployeeMangement

DB Tables :
AdminTab57(uname,pword,fname,lname,addr,mid,phno)
Employee57(eid,ename,edesg,bsal,hra,da,totsal)

Layout:
=======================================================================
Dt : 11/12/2023
Summary Diagram:

==========================================================================
faq:
define addCookie()?
=>addCookie() method is from HttpServletResponse and which is used to add
Cookie-Object to response.
Method Signature of addCookie():
public abstract void addCookie([Link]);
syntax:
[Link](ck);
=>This addCookie() method will perform serialization process,which means converts
Cookie-Object into Stream.
=========================================================================
faq:
define getCookies()?
=>getCookies() method is from HttpServletRequest and which is used to get all
cookies from the request object.
Method Signature of getCookie():
public abstract [Link][] getCookies();
syntax>
Cookie c[] = [Link]();
=>getCookies() method internally perform De-Serialization process,which means
convers Stream into Objects
===========================================================================
=
Application : HTML-FORM to Servlet Program
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="dis" method="post">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="tname" value=""></td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" name="tage" value=""></td>
</tr>
<tr>
<td>Gender</td>
<td><input type="radio" name="gen" value="M"
checked="checked"/>Male
<input type="radio" name="gen" value="F"/>Female
</td>
</tr>
<tr>
<td>Address</td>
<td>
<textarea name="taddress" rows="4" cols="20">enter
address</textarea>
</td>
</tr>
<tr>
<td>MaritalStatus</td>
<td><input type="checkbox" name="ms"
value="married"/>Married</td>
</tr>
<tr>
<td>Qualification</td>
<td>
<select name="qlfy">
<option value="[Link]">Engg</option>
<option value="MBBS">Medical</option>
<option value="B.A">Arts</option>
</select>
</td>
</tr>
<tr>
<td>Courses</td>
<td>
<select name="crs" size="3" multiple="multiple">
<option value="java">JAVA</option>
<option value=".net">.Net</option>
<option value="Testing">Testing</option>
</select>
</td>
</tr>
<tr>
<td>Hobbies</td>
<td>
<input type="checkbox" name="hb" value="read" checked/>
Reading
<input type="checkbox" name="hb" value="stamps"/> Stamp
Collection
<input type="checkbox" name="hb" value="travel"/>
Traveling
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="submit">
<input type="reset" value="cancel">
</td>
</tr>
</table>
</form>
</body>
</html>
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/dis")
public class ControllerServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
RequestDispatcher rd =
[Link]("[Link]");
[Link](req, res);
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String name = [Link]("tname");
int age = [Link]([Link]("tage"));
String gen = [Link]("gen");
String addr = [Link]("taddress");
String ms = [Link]("ms");
String qlfy = [Link]("qlfy");
String course = [Link]("crs");
String hb[] = [Link]("hb");
[Link]("Name:"+name);
[Link]("<br>Age:"+age);
[Link]("<br>Gen:"+gen);
[Link]("<br>Address:"+addr);
[Link]("<br>MS:"+ms);
[Link]("<br>Qlfy:"+qlfy);
[Link]("<br>Course:"+course);
[Link]("<br>Hobbies : ");
for(String k : hb)
{
[Link](k+"&nbsp&nbsp");

%>
</body>
</html>

[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
Dt : 12/12/2023
faq:
wt is the diff b/w
(i)getParameter()
(ii)getParameterValues()

(i)getParameter():
=>getParameter() method is used to get single parameter-value from the request-object.
syntax:
String var = [Link]("para_name");

(ii)getParameterValues():
=>getParameterValues() method is used to get group parameter-values from the request
object.
syntax:
String arr_var[] = [Link]("para_name");
==========================================================================
===
*imp
[Link]:
=>HttpSession is an interface from [Link] package and which is used in
Session tracking process.
=>The following are some important methods of HttpSession:
public abstract void setAttribute([Link], [Link]);
public abstract [Link] getAttribute([Link]);
public abstract void removeAttribute([Link]);
public abstract [Link]<[Link]> getAttributeNames();

public abstract void putValue([Link], [Link]);


public abstract [Link] getValue([Link]);
public abstract void removeValue([Link]);
public abstract [Link][] getValueNames();

public abstract void invalidate();

public abstract [Link] getServletContext();


public abstract [Link] getSessionContext();
---------------------------------------------------------------------------------
=>we use getSession() method from HttpServletRequest to create implementation object
for HttpSession-Interface.
Method Signature of getSession():
public abstract [Link] getSession();
public abstract [Link] getSession(boolean);
===========================================================================
========
[Link] re-write:
=>The process of adding parameter-values to servlet-url-pattern is known as
URL re-writing process.

syntax:
servlet-url-pattern?para=value&para=value&...

"?" - symbol is separator b/w url-pattern and parameters.


"&" - symbol is separator b/w parameters

Ex:
[Link]
===========================================================================
========
[Link] form fields:
=>The process of declaring <input type="hidden"...> in <form> tag of HTML is known as
Hidden form fields.
=>The values in Hidden form fields are not displayed to the end-user,which means not
shown to the end-user.
syntax:
<form action="url" method="POST/GET">
<input type="hidden" name="name" value="value">
....
</form>
===========================================================================
=====
Note:
=>'URL re-write' and 'Hidden form fields' are Sub-techniques in Session Tracking
process and which are also used to send data from one Servlet-program to another
Servlet-program
===========================================================================
==========
ProjectName : OnlineBookStore

Users :
Admin
Customer

DB tables:
Admin57(uname,pword,fname,lname,addr,mid,phno)
Customer57(uname,pword,fname,lname,addr,mid,phno)

create table Admin57(uname varchar2(15),pword varchar2(15),fname varchar2(15),


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

create table Customer57(uname varchar2(15),pword varchar2(15),fname varchar2(15),


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

BookDetails57(code,name,author,price,qty)

create table BookDetails57(code varchar2(10),name varchar2(15),author varchar2(15),


price number(10,2),qty number(10),primary key(code));
-----------------------------------------------------------------------------
Layout:

[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="[Link]">AdminLogin</a>
<a href="[Link]">CutomerLogin</a>
</body>
</html>
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="adminLog" method="post">
UserName:<input type="text" name="uname"><br>
Password:<input type="password" name="pword"><br>
<input type="submit" value="AdminLogin">
</form>
</body>
</html>
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="customerLog" method="post">
UserName:<input type="text" name="uname"><br>
Password:<input type="password" name="pword"><br>
<input type="submit" value="CutomerLogin">
<a href="[Link]">NewCutomer?</a>
</form>
</body>
</html>
[Link]
package test;
public interface DBInfo
{
public static final String
dbUrl="jdbc:oracle:thin:@localhost:1521:xe";
public static final String uName="system";
public static final String pWord="manager";

[Link]
package test;
import [Link].*;
import static [Link].*;
public class DBConnection
{
private static Connection con=null;
private DBConnection() {}
static
{
try {
[Link]("[Link]");
con = [Link](dbUrl,uName,pWord);
}catch(Exception e) {[Link]();}
}
public static Connection getCon()
{
return con;
}
}
[Link]
package test;
import [Link].*;
@SuppressWarnings("serial")
public class AdminBean implements Serializable{
private String uName,pWord,fName,lName,addr,mId;
private long phNo;
public AdminBean() {}
public String getuName() {
return uName;
}
public void setuName(String uName) {
[Link] = uName;
}
public String getpWord() {
return pWord;
}
public void setpWord(String pWord) {
[Link] = pWord;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
[Link] = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
[Link] = lName;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
[Link] = addr;
}
public String getmId() {
return mId;
}
public void setmId(String mId) {
[Link] = mId;
}
public long getPhNo() {
return phNo;
}
public void setPhNo(long phNo) {
[Link] = phNo;
}

[Link]
package test;
import [Link].*;
public class AdminLoginDAO {
public AdminBean ab=null;
public AdminBean login(String uName,String pWord) {
try {
Connection con = [Link]();
PreparedStatement ps = [Link]
("select * from Admin57 where uname=? and pword=?");
[Link](1, uName);
[Link](2, pWord);
ResultSet rs = [Link]();
if([Link]()) {
ab = new AdminBean();
[Link]([Link](1));
[Link]([Link](2));
[Link]([Link](3));
[Link]([Link](4));
[Link]([Link](5));
[Link]([Link](6));
[Link]([Link](7));
}
}catch(Exception e) {[Link]();}
return ab;
}
}

[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/adminLog")
public class AdminLoginServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException{
AdminBean ab = new AdminLoginDAO().login([Link]("uname"),
[Link]("pword"));
if(ab==null) {
[Link]("msg","Invalid Login process...<br>");
[Link]("[Link]").forward(req, res);
}else {
HttpSession hs = [Link]();//Creating new Session
[Link]("abean", ab);
[Link]("[Link]").forward(req, res);
}
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="[Link]"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
AdminBean ab = (AdminBean)[Link]("abean");
[Link]("Welcome Admin : "+[Link]()+"<br>");
%>
<a href="[Link]">AddBookDetails</a>
<a href="view1">ViewAllBookDetails</a>
<a href="logout">Logout</a>
</body>
</html>
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String msg = (String)[Link]("msg");
[Link](msg);
%>
<jsp:include page="[Link]"/>
</body>
</html>
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
Dt : 13/12/2023
Layout:

[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="add" method="post">
BookCode:<input type="text" name="code"><br>
BookName:<input type="text" name="name"><br>
BookAuthor:<input type="text" name="author"><br>
BookPrice:<input type="text" name="price"><br>
BookQty:<input type="text" name="qty"><br>
<input type="submit" value="AddBookDetails">
</form>
</body>
</html>
[Link]
package test;
import [Link].*;
@SuppressWarnings("serial")
public class BookBean implements Serializable{
private String code,name,author;
private float price;
private int qty;
public BookBean() {}
public String getCode() {
return code;
}
public void setCode(String code) {
[Link] = code;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
[Link] = author;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
[Link] = price;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
[Link] = qty;
}

[Link]
package test;
import [Link].*;
public class AddBookDetailsDAO {
public int k=0;
public int insert(BookBean bb) {
try {
Connection con = [Link]();
PreparedStatement ps = [Link]
("insert into BookDetails57
values(?,?,?,?,?)");
[Link](1, [Link]());
[Link](2, [Link]());
[Link](3, [Link]());
[Link](4, [Link]());
[Link](5, [Link]());
k=[Link]();
}catch(Exception e) {[Link]();}
return k;
}
}

[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/add")
public class AddBookDetailsServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException{
HttpSession hs = [Link](false);//Accessing existing session
if(hs==null) {
[Link]("msg","Session Expired...<br>");
RequestDispatcher rd = [Link]("[Link]");
[Link](req, res);
}else {
BookBean bb = new BookBean();
[Link]([Link]("code"));
[Link]([Link]("name"));
[Link]([Link]("author"));
[Link]([Link]([Link]("price")));
[Link]([Link]([Link]("qty")));
int k = new AddBookDetailsDAO().insert(bb);
if(k>0) {
[Link]("msg", "Book details added Successfully...<br>");
}
RequestDispatcher rd = [Link]("[Link]");
[Link](req, res);
}
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="[Link]"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
AdminBean ab = (AdminBean)[Link]("abean");
String msg = (String)[Link]("msg");
[Link]("Page belongs to : "+[Link]()+"<br>");
[Link](msg);
%>
<a href="[Link]">AddBookDetails</a>
<a href="view1">ViewAllBookDetails</a>
<a href="logout">Logout</a>
</body>
</html>
[Link]
package test;
import [Link].*;
import [Link].*;
public class ViewAllBooksDAO {
public ArrayList<BookBean> al = new ArrayList<BookBean>();
public ArrayList<BookBean> retrieve(){
try {
Connection con = [Link]();
PreparedStatement ps = [Link]
("select * from BookDetails57");
ResultSet rs = [Link]();
while([Link]()) {
BookBean bb = new BookBean();
[Link]([Link](1));
[Link]([Link](2));
[Link]([Link](3));
[Link]([Link](4));
[Link]([Link](5));
[Link](bb);
}
}catch(Exception e) {[Link]();}
return al;
}
}
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/view1")
public class ViewAllBooksServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException{
HttpSession hs = [Link](false);
if(hs==null) {
[Link]("msg", "Session Expired...<br>");
[Link]("[Link]").forward(req, res);
}else {
ArrayList<BookBean> al = new ViewAllBooksDAO().retrieve();
[Link]("alist", al);
[Link]("[Link]").forward(req, res);
}
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="test.*,[Link].*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
AdminBean ab = (AdminBean)[Link]("abean");
ArrayList<BookBean> al =
(ArrayList<BookBean>)[Link]("alist");
[Link]("Page belongs to : "+[Link]()+"<br>");
if([Link]()==0){
[Link]("Books Not Available...<br>");
}else{
Iterator<BookBean> it = [Link]();
while([Link]()){
BookBean bb = [Link]();

[Link]([Link]()+"&nbsp&nbsp"+[Link]()+"&nbsp&
nbsp"+

[Link]()+"&nbsp&nbsp"+[Link]()+"&nbsp&nbsp"+
[Link]()+"&nbsp&nbsp"+"<a
href='edit?bcode="+[Link]()+"'>Edit</a>"+"&nbsp&nbsp"+
"<a
href='delete?bcode="+[Link]()+"'>Delete</a>"+"<br>");
}
}
%>
<a href="logout">Logout</a>
</body>
</html>
===========================================================================
=====

Dt : 14/12/2023
Layout:

[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/edit")
public class EditBookDetailsServlet extends HttpServlet{
@SuppressWarnings("unchecked")
@Override
protected void doGet(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException{
HttpSession hs = [Link](false);
if(hs==null) {
[Link]("msg","Session Expired...<br>");
[Link]("[Link]").forward(req, res);
}else {
String bCode = [Link]("bcode");
ArrayList<BookBean> al = (ArrayList<BookBean>)[Link]("alist");
BookBean bb = null;
Iterator<BookBean> it = [Link]();
while([Link]()) {
bb = [Link]();
if([Link]([Link]())) {
break;
}
}//end of loop
[Link]("bbean", bb);
[Link]("[Link]").forward(req, res);
} }
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="test.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
AdminBean ab = (AdminBean)[Link]("abean");
BookBean bb = (BookBean)[Link]("bbean");
[Link]("Page belongs to : "+[Link]()+"<br>");
%>
<form action="update" method="post">
<input type="hidden" name="bcode" value=<%=[Link]() %>>
BookPrice:<input type="text" name="bprice"
value=<%=[Link]() %>><br>
BookQty:<input type="text" name ="bqty" value=<%=[Link]()
%>><br>
<input type="submit" value="UpdateBookDetails">
</form>
</body>
</html>

[Link]
package test;
import [Link].*;
public class UpdateBookDetailsDAO {
public int k=0;
public int update(BookBean bb) {
try {
Connection con = [Link]();
PreparedStatement ps = [Link]
("update BookDetails57 set price=?,qty=? where
code=?");
[Link](1, [Link]());
[Link](2, [Link]());
[Link](3, [Link]());
k = [Link]();
}catch(Exception e) {[Link]();}
return k;
}
}
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/update")
public class UpdateBookDetailsServlet extends HttpServlet{
@SuppressWarnings("unchecked")
@Override
protected void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException{
HttpSession hs = [Link](false);
if(hs==null) {
[Link]("msg", "Session Expired...<br>");
[Link]("[Link]").forward(req, res);
}else {
String bCode = [Link]("bcode");
ArrayList<BookBean> al = (ArrayList<BookBean>)[Link]("alist");
BookBean bb = null;
Iterator<BookBean> it = [Link]();
while([Link]()) {
bb = [Link]();
if([Link]([Link]())) {
break; }
} //end of loop
[Link]([Link]([Link]("bprice")));
[Link]([Link]([Link]("bqty")));
int k = new UpdateBookDetailsDAO().update(bb);
if(k>0) {
[Link]("msg", "Book details Updated Successfully..<br>");
[Link]("[Link]").forward(req, res);
}
}
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="test.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
AdminBean ab = (AdminBean)[Link]("abean");
String msg = (String)[Link]("msg");
[Link]("page belongs to : "+[Link]()+"<br>");
[Link](msg);
%>
<a href="[Link]">AddBookDetails</a>
<a href="view1">ViewAllBookDetails</a>
<a href="logout">Logout</a>
</body>
</html>
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/logout")
public class LogoutServlet extends HttpServlet{
protected void doGet(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException{
HttpSession hs = [Link](false);
if(hs==null) {
[Link]("msg","Session expired...<br>");
[Link]("[Link]").forward(req, res);
}else {
[Link]("[Link]").forward(req, res);
}
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
[Link]();
[Link]("Loggedout Successfully...<br>");
%>
<jsp:include page="[Link]"/>
</body>
</html>
===========================================================================
===
Dt : 15/12/2023
Assignment:(Construct Customer-Login for above appliaction using the following Layout)

===========================================================================
faq:
wt is the diff b/w
(i)Cookie
(ii)HttpSession

(i)Cookie:
=>Cookie is a Class from [Link] and which is used session tracking
process.
=>Cookie is created by Server-Application,but stored in WebBrowser to track the
user
=>Cookie Applications are Client dependent Application.

(ii)HttpSession:
=>HttpSession is an interface from [Link] and which is also used in
Session tracking process.
=>HttpSession object is created by Server-application and which is available in
Server only.
=>HttpSession Applications are Sever dependent applications
===========================================================================
======
faq:
wt is the diff b/w
(i)getSession()
(ii)getSession(false)
(iii)getSession(true)

(i)getSession():
=>getSession() method will search for existing session,if not available creates
new-session.

(ii)getSession(false):
=>getSession(false) method will also search for existing session,if available use
the session and if not available new session is not created.

(iii)getSession(true)
=>getSession(true) method also search for existing session,if available use the
session and if not available create a new session.
*imp ServletContext:
=>ServletContext is an interface from [Link] package and which is instantiated
automatically when Web Application is deployed into Server.
=>This ServletContext object is loaded with Server information.
=>we use getServletContext() method from ServletRequest to access the reference of
ServletContext Object.
syntax:
ServletContext sct = [Link]();
=>we use <context-param> tag part of [Link] to initialize parameter-values to
ServletContext object.
syntax:
<web-app>
<context-param>
<param-name> name </param-name>
<param-value> value </param-value>
</context-param>
...
</web-app>
=>we use getInitParameter() method to access initialized parameter-value from the
ServletContext Object.
Method signature of getInitParameter():
public abstract [Link] getInitParameter([Link]);
syntax:
String var = [Link]("para_name");
Dt : 16/12/2023
*imp
ServletConfig:
=>ServletConfig is an interface from [Link] package and which is instantiated
automatically when the Servlet-program loaded for execution.
=>This ServletConfig Object is loaded with Servlet-name.
=>we use getServletConfig() method from 'GenericServlet' to access the reference of
ServletConfig Object
syntax:
ServletConfig scf = [Link]();
=>we use <init-param> subtag of <servlet> tag to initialize parameter-values in
ServletConfig object.
syntax:
<web-app>
...
<servlet>
<servlet-name> name </servlet-name>
<servlet-class> class </servlet-class>
<init-param>
<param-name> name </param-name>
<param-value> value </param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name> name </servlet-name>
<url-pattern> /url </url-pattern>
</servlet-mapping>
...
</web-app>
=>we use getInitParameter() method to get the initialized parameter from ServletConfig
Object
Ex-Application:
Layout:
[Link]
<!DOCTYPE html>
<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>
<input type="submit" value="Display">
</form>
</body>
</html>
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
public class DisplayServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException{
ServletContext sct = [Link]();
ServletConfig scf = [Link]();
[Link]("sn", [Link]());
[Link]("c", [Link]("c"));
[Link]("a","NIT");

[Link]("[Link]").forward(req, res);
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String uName = [Link]("uname");
[Link]("Welcome User : "+uName+"<br>");
[Link]("====ServletContext=====");
[Link]("<br>ServerInfo:"+[Link]());
String a = (String)[Link]("a");
[Link]("<br>Attribute in Context:"+a);
int b = [Link]([Link]("b"));
[Link]("<br>Context-InitParameter:"+b);
[Link]("<br>====ServletConfig=====");
[Link]("<br>ServletName :"+[Link]("sn"));
[Link]("<br>Config-
InitParameter:"+[Link]("c"));
[Link]("<br>JSP Config:"+[Link]());
%>
</body>
</html>
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<context-param>
<param-name>b</param-name>
<param-value>200</param-value>
</context-param>
<servlet>
<servlet-name>DisplayServlet</servlet-name>
<servlet-class>[Link]</servlet-class>
<init-param>
<param-name>c</param-name>
<param-value>500</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DisplayServlet</servlet-name>
<url-pattern>/dis</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
===========================================================================
====
Note:
(i)Only one ServletContext object is created for WebApplication and the information
in ServletContext object can be used by all the Servlet-programs and JSP-Programs
of Web Application.
(ii)Every Servlet-program and JSP-program in applications will have its own
ServletConfig objects.
(iii)when we want to send data to WebApplication then we send data to ServletContext
object.
(iv)when we want to send data to individual Servlet-program then we send data to
ServletConfig object
===========================================================================
====
Note:
=>To execute Servlet-program we need servlet-url-pattern and this Servlet-url-pattern
is holded by any one of the following:
[Link]
@WebServlet("/url")
[Link]
<servlet></servlet>
<servlet-mapping></servlet-mapping)
===========================================================================
=========
Dt : 18/12/2023
*imp
Filters in Servlet Programming:
=>Filter is a pre-processing component which is executed before Servlet Program.
=>Filter is executed with same url-pattern of Servlet-program,which means Filter
and Servlet will have same url-pattern.
=>Filter-program will have highest priority in execution than Servlet-program.
=>In realtime Filter-program will hold security related code,which means Filter is
a Security layer of Servlet-program.
=>we use the following components to construct Filters:
[Link]
[Link]
[Link]

[Link]:
=>'Filter' is an interface from [Link] package and which is implemented to
construct Filter-programs.
=>The following are some important methods from Filter:
public void init([Link])
throws [Link];
public abstract void doFilter([Link],
[Link], [Link])
throws [Link], [Link];
public void destroy();

[Link]:
=>FilterChain is an interface from [Link] package and which is instantiated
automatically while doFilter()-method execution.
=>This FilterChain will provide the following method to interlink Servlet-program
having same url-pattern:
public abstract void doFilter([Link],
[Link]) throws [Link],
[Link];

Ex-application:
Layout:

[Link]
<!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">
</form>
</body>
</html>
[Link]
package test;
import [Link].*;
@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) {
[Link] = uName;
}
public String getpWord() {
return pWord;
}
public void setpWord(String pWord) {
[Link] = pWord;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
[Link] = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
[Link] = lName;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
[Link] = addr;
}
public String getmId() {
return mId;
}
public void setmId(String mId) {
[Link] = mId;
}
public long getPhNo() {
return phNo;
}
public void setPhNo(long phNo) {
[Link] = phNo;
}

[Link]
package test;
public interface DBInfo
{
public static final String
dbUrl="jdbc:oracle:thin:@localhost:1521:xe";
public static final String uName="system";
public static final String pWord="manager";

[Link]
package test;
import [Link].*;
import static [Link].*;
public class DBConnection
{
private static Connection con=null;
private DBConnection() {}
static
{
try {
[Link]("[Link]");
con = [Link](dbUrl,uName,pWord);
}catch(Exception e) {[Link]();}
}
public static Connection getCon()
{
return con;
}
}
[Link]
package test;
import [Link].*;
public class LoginDAO {
public UserBean ub = null;
public UserBean login(String uName,String pWord) {
try {
Connection con = [Link]();
PreparedStatement ps = [Link]
("select * from UserReg57 where uname=? and
pword=?");
[Link](1, uName);
[Link](2, pWord);
ResultSet rs = [Link]();
if([Link]()) {
ub = new UserBean();
[Link]([Link](1));
[Link]([Link](2));
[Link]([Link](3));
[Link]([Link](4));
[Link]([Link](5));
[Link]([Link](6));
[Link]([Link](7));
}
}catch(Exception e) {[Link]();}
return ub;
}
}

[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
@WebFilter("/log")
public class LoginFilter implements Filter{
@Override
public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain)
throws ServletException,IOException{
UserBean ub = new LoginDAO().login([Link]("uname"),
[Link]("pword"));
if(ub==null) {
[Link]("msg","Invalid Login process...<br>");
[Link]("[Link]").forward(req, res);
}else {
[Link]("ubean", ub);
[Link](req, res);//linking Servlet_program
}
}
}
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/log")
public class WelcomeServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException{
[Link]("[Link]").forward(req, res);
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="test.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
UserBean ub = (UserBean)[Link]("ubean");
[Link]("Welcome User : "+[Link]()+"<br>");
[Link]([Link]()+"&nbsp&nbsp"+[Link]()+"&nbsp&nb
sp"+[Link]()+

"&nbsp&nbsp"+[Link]()+"&nbsp&nbsp"+[Link]()+"<br>")
;
%>
<jsp:include page="[Link]"/>
</body>
</html>
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String msg = (String)[Link]("msg");
[Link](msg);
%>
<jsp:include page="[Link]"/>
</body>
</html>
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
===========================================================================
=
Dt : 19/12/2023
[Link]:
=>FilterConfig is an interface from [Link] package and which is instantiated
automatically when filter-program is loaded for execution.
=>This FilterConfig Object is loaded with Filter_name.
=>To access FilterConfig object reference we must use init()-method
=>we use <init-param> subtag part of <filter> tag to initialize parameter-values
to FilterConfig Object.
syntax:
<web-app>
...
<filter>
<filter-name> name </filter-name>
<filter-class> class </filter-class>
<init-param>
<param-name> name </param-name>
<param-value> value </param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name> name </filter-name>
<url-pattern> /url </url-pattern>
</filter-mapping>
...
</web-app>
---------------------------------------------------------------------------
Ex-Application:(Demonstrating FilterConfig)
Layout:

[Link]
<!DOCTYPE html>
<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>
<input type="submit" value="Display">
</form>
</body>
</html>
[Link]
package test;
import [Link].*;
import [Link].*;
public class DisplayFilter implements Filter{
public FilterConfig fcf=null;
@Override
public void init(FilterConfig fcf)throws ServletException{
[Link]=fcf;
}
@Override
public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain)throws
ServletException,IOException{
[Link]("fn",[Link]());
[Link]("a", [Link]("a"));
[Link]("[Link]").forward(req, res);
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String uName = [Link]("uname");
String fn = (String)[Link]("fn");
[Link]("Welcome UserName : "+uName+"<br>");
[Link]("=====FilterConfig=====");
[Link]("<br>FilterName:"+fn);
[Link]("<br>FilterConfig
Val:"+[Link]("a"));
%>
</body>
</html>
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<filter>
<filter-name>DisplayFilter</filter-name>
<filter-class>[Link]</filter-class>
<init-param>
<param-name>a</param-name>
<param-value>1000</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>DisplayFilter</filter-name>
<url-pattern>/dis</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
===========================================================================
faq:
wt is the diff b/w
(i)ServletConfig
(ii)FilterConfig
(iii)JSP-Config

(i)ServletConfig:
=>ServletConfig is instantiated automatically when Servlet-program loaded for
execution and which holds Servlet_name.

(ii)FilterConfig:
=>FilterConfig is instantiated automatically when Filter-program is loaded for
execution and which holds Filter_name

(iii)JSP-Config:
=>JSP-Config means ServletConfig and which is instantiated automatically when
JSP-program loaded for execution.
=>This JSP-Config is accessed with implicit name "config"
===========================================================================
===
*imp
Events and Listeners in Servlet Programming:

define Events?
=>The actions which are performed are known as Events.

define Listeners?
=>Listeners are executed background to Servlet-Objects and record the actions
performed on Servlet-Objects.
=>The Listeners in Servlet programming can be added to the following Servlet-Objects
[Link]
[Link]
[Link]

[Link]:
=>we add 'ServletContextListener' to ServletContext Object

Listener_name : ServletContextListener
public void contextInitialized([Link]);
public void contextDestroyed([Link]);

Event_name : ServletContextEvent
public [Link] getServletContext();
Attribute_Lisnter_name : ServletContextAttributeListener
public void attributeAdded([Link]);
public void attributeRemoved([Link]);
public void attributeReplaced([Link]);

Attribute_Event_name : ServletContextAttributeEvent
public [Link] getName();
public [Link] getValue();
--------------------------------------------------------------------------------
[Link]:
=>we add 'ServletRequestListener" to ServletRequest Object

Listener_name : ServletRequestListener
public void requestInitialized([Link]);
public void requestDestroyed([Link]);

Event_name : ServletRequestEvent
public [Link] getServletRequest();
public [Link] getServletContext();

Attribute_Listener_name : ServletRequestAttributeListener
public void attributeAdded([Link]);
public void attributeRemoved([Link]);
public void attributeReplaced([Link]);

Attribute_Event_name : ServletRequestAttributeEvent
public [Link] getName();
public [Link] getValue();
----------------------------------------------------------------------------
[Link]:
=>we add 'HttpSessionListenter' to HttpSession object
Listener_name : HttpSessionListener
public void sessionCreated([Link]);
public void sessionDestroyed([Link]);

Event_name : HttpSessionEvent
public [Link] getSession();

Attribute_Listener_name : HttpSessionAttributeListener
public void attributeAdded([Link]);
public void attributeRemoved([Link]);
public void attributeReplaced([Link]);

Attribute_Event_name : HttpSessionBindingEvent
public [Link] getName();
public [Link] getValue();
===========================================================================
=
Dt : 20/12/2023
[Link]
package test;
import [Link].*;
import [Link].*;
@WebListener
public class ContextListener implements ServletContextListener,
ServletContextAttributeListener{
@Override
public void contextInitialized(ServletContextEvent sce) {
[Link]("Context Object initialized....");
ServletContext sct = [Link]();//Accessing Context Objec_ref
[Link]("Application deployed into : "+[Link]());
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
[Link]("Context Object destroyed...");
}
@Override
public void attributeAdded(ServletContextAttributeEvent scae) {
[Link]("Attribute added to Context Object");
String aName = [Link]();
[Link]("Attribute Name : "+aName);
}
@Override
public void attributeRemoved(ServletContextAttributeEvent scae) {
[Link]("Attribute removed from Context Object");
}
}
Note:
=>Add [Link] program into Cookie Session tracking Application.
===========================================================================
=====
[Link]
package test;
import [Link].*;
import [Link].*;
@WebListener
public class RequestListener implements ServletRequestListener,
ServletRequestAttributeListener{
@Override
public void requestInitialized(ServletRequestEvent sre) {
[Link]("Request Object initialized....");
}
@Override
public void requestDestroyed(ServletRequestEvent sre) {
[Link]("Request Object destroyed...");
}
@Override
public void attributeAdded(ServletRequestAttributeEvent srae) {
[Link]("Attribute added to Request Object...");
String aName = [Link]();
[Link]("Attribute Name:"+aName);
}
@Override
public void attributeRemoved(ServletRequestAttributeEvent srae) {
[Link]("Attribute removed from Request Object...");
}
}
[Link]
package test;
import [Link].*;
import [Link].*;
@WebListener
public class SessionListener implements HttpSessionListener,
HttpSessionAttributeListener{
@Override
public void sessionCreated(HttpSessionEvent hse) {
[Link]("Session Created...");
}
@Override
public void sessionDestroyed(HttpSessionEvent hse) {
[Link]("Session destroyed...");
}
@Override
public void attributeAdded(HttpSessionBindingEvent hsbe) {
[Link]("Attribute added to Session...");
String aName = [Link]();
[Link]("Attribute Name:"+aName);
}
@Override
public void attributeRemoved(HttpSessionBindingEvent hsbe) {
[Link]("Attribute removed from Session...");
}
}
Note:
=>Add [Link] and [Link] to HttpSession tracking
application.
===========================================================================
Dt : 21/12/2023
faq:
define Annotattion?
=>The tag-based-information which is added to the programming components like
Variable or method or Class or Interface is known as Annotation.
=>we use '@' symbol to represent annotations.
=>These annotations will give information to Compiler at compilation stage or
will give information to execution-control while execution process.
CoreJava Annotations:
@Override - will give information to compiler to check the method is
Overriding method or not
@SuppressWarnings - will give information to compiler to close the raised
warnings
@FunctionalInterface - will give information to check the interface is
Functional Interface or not

AdvJava Annotations:
@WebServlet - will hold Servlet-url-pattern to identify Servlet-program
for execution.
@WebFilter - will hold Servlet-url-pattern to identify Filter-program for
execution.
@WebListener - is used to identify Listener-program for execution.
===========================================================================
==
*imp
Servlet Life-Cycle:
=>Servlet Life-Cycle demonstrates different states of Servlet-program from
Starting of program to ending of program.
=>The following are the stages of Servlet Life-Cycle:
[Link] process
[Link] process
[Link] process
[Link] Handling Process
[Link] Process

[Link] process:
=>The process of identifying the servlet-program using url-pattern and loading
for execution is known as Loading Process.

[Link] process:
=>When Servlet-program loaded,it is instantiated automatically known as
Instantiation process.(Object creation process)
=>After Instantiation process,the execution-controls will identify the following
life-cycle methods:
GenericServlet
init()
service()
destroy()
HttpServlet
init()
service()/doPost()/doGet()
destroy()
Filter
init()
doFilter()
destroy()

[Link] process:
=>The process of making the programming components ready for service()-method
is known as Initialization process.
=>we use init()-method for initialization process.
Note:
=>init()-method is executed only once for Servlet-program,which means
Initialization process is performed only once.

[Link] Handling Process:


=>The process of accepting request from user and providing the response is
known as Request Handling process.
=>we use service()/doPost()/doGet() method to perform Request handling process.
Note:
=>This service()-method is executed for all multiple requests generated from
multiple users.

[Link] Process:
=>The process of closing the resources which are opened part of Request Handling
process is known as destroying process.
=>we use destroy()-method to perform destroying process.

Note:
=>The destroy()-method is executed after service()-method execution completed.
==========================================================================
=
Ex-application:
[Link]
<!DOCTYPE html>
<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>
<input type="submit" value="Display">
</form>
</body>
</html>
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/dis")
public class DisplayServlet extends HttpServlet
{
public DisplayServlet()
{
[Link]("Instantiation process...");
}
@Override
public void init()throws ServletException
{
[Link]("Initialization process...");
}
@Override
protected void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException{
PrintWriter pw = [Link]();
[Link]("text/html");
[Link]("Welcome : "+[Link]("uname"));
[Link]("Request handling process...");
}
@Override
public void destroy()
{
[Link]("Destroying process....");
}
}
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
======================================================================
Dt : 22/12/2023
faq:
wt it the diff b/w
(i)JAR
(ii)WAR
(iii)EAR

(i)JAR:
=>JAR means 'Java Archeive' and which is compressed format of
class files.

(ii)WAR:
=>WAR means 'Web Archeive' and which is compressed format of
HTML files,XML file,UI-Files,Servlets,JSP and Jars.
=>WebApplications are converted into WAR files.

(iii)EAR:
=>EAR means 'Enterprise Archeive' and which is compressed format
of Enterprise Java Beans,WARs and JARs.
=>Enterprise Applications are converted into EAR files.
================================================================
Summary:

Level-1 : CoreJava - Stand Alone Application - JAR file


Level-2 : AdvJava - Web Application(JSP-MVC) - WAR file
Level-3 : Framework - Enterprise Applications - EAR file
(Spring,WebServices)
=================================================================
*imp
Generating WAR file and executing from Tomcat Server:
step-1 : Generate WAR file using IDE Eclipse
RightClick on WebApplication->Export->WAR file->Browse the
destination folder to store WAR file->name the file and
click 'save'->click 'finish'
step-2 : start the Tomcat server
step-3 : Open WebBrowser and access the Server(Tomcat)
step-4 : Deploy the WAR file into Tomcat Server
Click on Manager App->perform login process->
From 'WAR file to deploy' click 'choose file'->
browse and select the file->click 'deploy'
Use the following Web_App_URL:
[Link]
Use the following Web_App_URL from Mobile(Remote):
[Link]
---------------------------------------------------------------------------
*imp
Deployment Directory Structure of Tomcat Server:
Dt : 23/12/2023
JSP Conclusion:
=>JSP uses the followimg tags to write Java-code in JSP programs:
[Link] tags
[Link] tags
[Link] tags

[Link] tags:
=>The Scripting tags are used to write JavaCode in JSP programs.
=>These Scripting tags are categorized into the following:
(a)Scriptlet tag
(b)Expression tag
(c)Declarative tag

(a)Scriptlet tag:
=>Scriptlet tag is used to write Normal JavaCode or ServletCode in JSP
programs.
syntax:
<% code %>

(b)Expression tag:
=>Expression tag is used to assign the value to variable or used to
display the data to WebBrowser directly.
syntax:
<%= value/Expression %>

(c)Declarative tag:
=>Declarative tag is used to declare variables and methods in JSP
Programs.
syntax:
<%! Variables;Methods %>
---------------------------------------------------------------
[Link] tags:
=>The tags which are used to specify the directions in translation
process of JSP Programs.
=>Directive tags are categorized into the following:
(a)@page
(b)@include
(c)@taglib

(a)@page:
=>'@page' will specify Langauge used in JSP,contextType,pageEncoding,
importing and so on...
(Specifications about the JSP page)
syntax:
<%@page ... %>

(b)@include:
=>'@include' will specify which page must be included to current running
JSP program
syntax:
<%@include file="File_name"/%>

(c)@taglib:
=>'@taglib' is used to link external libraries to current JSP program.
syntax:
<%@tablib ....%>
---------------------------------------------------------------------
[Link] tags:
=>Action tage used to perform some actions related to JSP programs while
execution process.
=>These Action tage are categorized into the following:
(a)<jsp:include>
(b)<jsp:forward>
(c)<jsp:param>
(d)<jsp:useBean>
(e)<jsp:setProperty>
(f)<jsp:getProperty>
======================================================================
Ex-program:(Demonstrating JSP-Application)
Layout:

[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="[Link]" method="post">
Enter the Value:<input type="text" name="v"><br>
<input type="submit" value="Factorial">
</form>
</body>
</html>
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
errorPage="[Link]"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%!
int fact;
int factorial(int n)
{
fact=1;
for(int i=n;i>=1;i--)
{
fact=fact*i;
}
return fact;
}
%>
<%
int v = [Link]([Link]("v"));
int res = factorial(v);
[Link]("factorial="+res+"<br>");
%>
<%@include file="[Link]"%>
</body>
</html>

[Link]
<%@ 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>
<%
[Link]("Invalid input...<br>");
%>
<%= exception %>
<br>
<%@include file="[Link]" %>
</body>
</html>

[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
======================================================================
*imp
Implicit Objects of JSP:
[Link] - [Link]
[Link] - [Link]
[Link] - [Link]
[Link] - [Link]
[Link] - [Link]
[Link] - [Link]
[Link] - [Link]
[Link] - [Link]
[Link] - [Link]
=====================================================================
Ex-program:(Demonstrating <jsp:include>,<jsp:forwrad> and <jsp:param>)
Layout:
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="[Link]" method="post">
Enter the Value-1:<input type="text" name="v1"><br>
Enter the Value-2:<input type="text" name="v2"><br>
<input type="submit" value="Add" name="s1">
<input type="submit" value="Sub" name="s1">
</form>
</body>
</html>
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String s1 = [Link]("s1");
if([Link]("Add")){
%>
<jsp:forward page="[Link]">
<jsp:param value="<%= 200%>" name="nm"/>
</jsp:forward>
<%
}else{
%>
<jsp:forward page="[Link]">
<jsp:param value="<%= 300 %>" name="nm"/>
</jsp:forward>
<%
}
%>
</body>
</html>

[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
errorPage="[Link]"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
int v1 = [Link]([Link]("v1"));
int v2 = [Link]([Link]("v2"));
int v3 = v1+v2;
[Link]("Name:"+[Link]("nm")+"<br>");
[Link]("Addition:"+v3+"<br>");
%>
<jsp:include page="[Link]"/>
</body>
</html>
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
errorPage="[Link]"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
int v1 = [Link]([Link]("v1"));
int v2 = [Link]([Link]("v2"));
int v3 = v1-v2;
[Link]("Name:"+[Link]("nm")+"<br>");
[Link]("Subtraction:"+v3+"<br>");
%>
<jsp:include page="[Link]"/>
</body>
</html>
[Link]
<%@ 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>
<%
[Link]("Invalid input...<br>");
%>
<%= exception %>
<br>
<jsp:include page="[Link]"/>
</body>
</html>
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list> </web-app>
Dt : 26/12/2023
Ex-program(Demonstrating <jsp:useBean>,<jsp:setProperty> and <jsp:getProperty>)
Layout:
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="[Link]" method="post">
UserName:<input type="text" name="uname"><br>
MailId:<input type="text" name="mid"><br>
PhoneNo:<input type="text" name="phno"><br>
<input type="submit" value="LoadToBean">
</form>
</body>
</html>
[Link]
package test;
import [Link].*;
@SuppressWarnings("serial")
public class UserBean implements Serializable{
private String uName,mId;
private long phNo;
public UserBean() {}
public String getuName() {
return uName;
}
public void setuName(String uName) {
[Link] = uName;
}
public String getmId() {
return mId;
}
public void setmId(String mId) {
[Link] = mId;
}
public long getPhNo() {
return phNo;
}
public void setPhNo(long phNo) {
[Link] = phNo;
}

[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="[Link]"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<jsp:useBean id="ub" class="[Link]" scope="session"/>
<jsp:setProperty property="uName" param="uname" name="ub"/>
<jsp:setProperty property="mId" param="mid" name="ub"/>
<jsp:setProperty property="phNo" param="phno" name="ub"/>
<h1>Details Added to Bean Successfully...</h1><br>
<a href="[Link]">ViewDetails</a>
</body>
</html>
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="[Link]"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<jsp:useBean id="ub" type="[Link]" scope="session"/>
UserName:<jsp:getProperty property="uName" name="ub"/><br>
MailID:<jsp:getProperty property="mId" name="ub"/><br>
PhoneNo:<jsp:getProperty property="phNo" name="ub"/><br>

</body>
</html>
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
======================================================================
(a)<jsp:include>:
=><jsp:include> tag is used to include the specified files into current running
JSP-page
syntax:
<jsp:include page="file"/>

(b)<jsp:forward>:
=><jsp:forward> tag is used to forward the request from one JSP-page to
another JSP-page.
syntax:
<jsp:forward page="file"/>

(c)<jsp:param>:
=><jsp:param> tag is a SubTag of <jsp:forward> and which is used to send
parameter from one JSP-page to another JSP-page.
syntax:
<jsp:forward page="file">
<jsp:param value="value" name="name"/>
</jsp:forward>

(d)<jsp:useBean>:
=><jsp:useBean> tag is used to instatiate bean-object or identify the existing
bean-object.
syntax-1:(Instantiating Bean-Object)
<jsp:useBean id="bean_name" class="Class_name" scope="scope"/>

syntax-2:(Identifying the Bean-Object)


<jsp:useBean id="bean_name" type="Class_name" scope="scope"/>

Type of scope:
(i)application - Used in total Web Application
(ii)page - Used only in JSP-page
(iii)request - Used within the request
(iv)session - Used within the session

(e)<jsp:setProperty>:
=>jsp:setProperty> tag is used to set the data to Bean object.
=>This <jsp:setProperty> internally uses Setter-method based on property-name
syntax:
<jsp:setProperty property="" param="" name="bean_name"/>

(f)<jsp:getProperty>:
=><jsp:getProperty> tag is used to get the data from the Bean Objects.
=>This <jsp:getProperty> internally uses Getter-method based on Property-name
display the data directly through JspWriter.
syntax:
<jsp:getProperty property="" name="bean_name"/>

Dt : 27/12/2023
Expression Language(EL):
=>Expression Language will provide more flexibility to access the objects of
JSP like request,response,out,...
=>Expression Language is a newly added feature to JSP-Programming and which is
known as "JSP-EL".
syntax:
$(Expression)
=>The following are implicit objects of Expression Language(EL):
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]

[Link]:
=>'appliactionScope' is used to access attribute from ServletContext Object.

[Link]:
=>'sessionScope' is used to access attribute from HttpSession Object.

[Link]:
=>'requestScope' is used to access attribute from jsp-request-Object.

[Link]:
=>'pageScope' is used to access attribute from jsp-pageContext-Object.

[Link]:
=>'param' is used to access single para-value from jsp-request-Object.

[Link]:
=>'paramValue' is used to multiple para-values from jsp-request-Object in the
form of String-Array
[Link]:
=>'header' is used to access single header value from jsp-request-Object.

[Link]:
=>'headerValues' is used to access multiple header values from jsp-request-Object
in the form of String-Array
[Link]:
=>'cookie' is used to access cookie from jsp-request-Object

[Link]:
=>'initParam' is used to access initialization para-value from jsp-config-Object

[Link]:
=>'pageContext' is an implicit object refering jsp-pageContext-Object

==========================================================================
==
*imp
Complete Summary of Objects Generated from CoreJava and AdvJava:

CoreJava Objects:(Container Objects:


[Link] defined Class Objects
[Link]-Objects
(a)String-Class-Object
(b)StringBuffer-Class-Object
(c)StringBuilder-Class-Object
[Link] Objects
(a)Byte Object
(b)Short Object
(c)Integer Object
(d)Long Object
(e)Float Object
(f)Double Object
(g)Character Object
(h)Boolean Object
[Link] Objects
(a)Array holding User defined Class Objects
(b)Array holding WrapperClass Objects
(c)Array holding String Objects
(d)Array holding Array-Objects(Jagged Array)
(e)Array holding Dis-Similer Objects(Object Array
[Link]<E> Objects
(a)Set<E> Objects
(i)HashSet<E> Object
(ii)LinkedHashSet<E> Object
(iii)TreeSet<E> Object
(b)List<E> Objects
(i)ArrayList<E> Object
(ii)LinkedList<E> Object
(iii)Vector<E> Object
=>Stack<E> Object
(c)Queue<E> Objects
(i)PriorityQueue<E> Object
=>Deque<E> Objects
(ii)ArrayDeque<E> Object
(iii)LinkedList<E> Object
[Link]<K,V> Objects
(a)HashMap<K,V> Object
(b)LinkedHashMap<K,V> Object
(c)TreeMap<K,V> Object
(d)Hashtable<K,V> Object
[Link]<E> Objects
------------------------
Total : 31 Objects
----------------------------------------
JDBC Objects:
[Link] Object
[Link] Object
[Link] Object
[Link] Object
[Link] Object
(i)Scrollable ResultSet Object
(ii)NonScrollable ResultSet Objects
[Link] Objects
(a)JdbcRowSet Object
(b)CachedRowSet Objects
=>WebRowSet Objects
(i)FilterRowSet Object
(ii)JoinRowSet Object
[Link] Object
[Link] Object
[Link] Object
[Link] Object
---------------------------------
Total : 10 Objects
-----------------------------------------------------------------
Servlet Objects:
[Link] Object
[Link] Object
[Link]/HttpServletRequest Object
[Link]/HttpServletResponse Object
[Link] Object
[Link] Object
[Link] Object
[Link] Objects
[Link] Objects
[Link] Objects
----------------------------
Total : 10 Objects
------------------------------------------------------------------
JSP Implicit Objects:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
---------------------
Total : 9 Objects
------------------------------------------------------------------
EL Implicit Objects:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
----------------------------
Total : 11 Objects
-----------------------------------------------------------------------
*imp
JSTL(JSP Standard Tag Lib):
=>This JSTL represents a set of tags to simplify the JSP
development.

Advantages of JSTL:
(i)Fast Development
(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

Note:
=>To work with EL-JSTL,download the following Jar-file:
External JAR : [Link](Download from Internet)

=>This JSTL-Jar must be copied into "lib" folder of WEB-INF


=>we use "@taglib" directive tag to declare JSTL Tags.
---------------------------------------------
(1)Core Tags:
=>These JSTL core tags provides variable support,URL management,
flow control etc. (Basic code writing)

syntax:
<%@ taglib uri="[Link]
prefix="c" %>

The following are the List of JSTL Core Tags:

c:out ->It displays the result of an expression, similar to


<%=...%> tag.

c:import->It Retrives relative or an absolute URL.

c:set-> It sets the value to variable.

c:remove->It is used for removing the variable .

c:catch-> It is used for Catching any Throwable exception that occurs


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.

c:forTokens-> It iterates over tokens which is separated by the


supplied delimeters.

c:param-> It adds a parameter in a containing 'import' tag's URL.

c:redirect-> It redirects the browser to a new URL and supports the


context-relative URLs.

c:url-> It creates a URL with optional query parameters.


======================================================
(2)Function Tags:
=>These JSTL function tags provides a number of
standard functions, most of these functions are common
string manipulation functions.

syntax:

<%@taglib uri= "[Link]


prefix="fn" %>
List of Some Function tags:

fn:contains :It is used to test if an input string containing the


specified substring or not.

fn:containsIgnoreCase(): It is used to test if an input string


contains the specified substring as a case insensitive way.
fn:endsWith() : It is used to test if an input string ends with the
specified suffix.

fn:indexOf(): It returns an index within a string of first occurrence


of a specified substring.

fn:trim(): It removes the blank spaces from both the ends of a string.

fn:startsWith(): It is used for checking whether the given string is


started with a particular string value or not.

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.

fn:length(): It returns the number of characters inside a string, or


the number of items in a collection.

fn:replace(): It replaces all the occurrence of a string with


another string sequence.
============================================================
(3)Formatting Tags:
=>These formatting tags provide support for message
formatting,number formating and date formatting etc.
=>These formatting tags are also used for
internationalized web sites to display and format text,
time,date and numbers.

syntax:

<%@ taglib uri="[Link]


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 specific format or precision.

fmt:parseDate : It parses the string representation of a time


and date.

fmt:setTimeZone : It stores the time zone inside a time


zone configuration variable.

*imp
fmt:formatDate : It formats the time and date using the
supplied pattern and styles.
===========================================================
(4)XML Tags:
=>The JSTL XML tags are used for providing a JSP-centric way of
manipulating and creating XML documents.

syntax:
<%@ taglib uri="[Link] 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.

syntax:
<%@ taglib uri="[Link] prefix="sql" %>

Note:
=>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 compared to other tags.
================================================================
Dt : 28/12/2023
Ex-application:(Demonstrating EL-JSTL)
Layout:

[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title> </head>
<body>
<form action="dis" method="post">
Enter the name:<input type="text" name="name"><br>
<input type="submit" value="Display">
</form>
</body>
</html>

[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/dis")
public class ControllerServlet extends HttpServlet{
@ Override
public void doPost(HttpServletRequest req,
HttpServletResponse res)
throws ServletException,IOException{
ServletContext sct = [Link]();
HttpSession hs = [Link]();
[Link]("a",100);
[Link]("b",200);
[Link]("c", 300);
RequestDispatcher rd = [Link]("[Link]");
[Link](req,res);
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO- 8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib prefix="c"
uri="[Link] %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body> <% [Link]("fName","Raju"); %>
<c:set var="name" value="${[Link]} "/>
WELCOME : <c:out value="${name}"/><br>
<c:set var="a" value="${applicationScope.a}" />
<c:set var="b" value="${sessionScope.b}" />
<c:set var="c" value="${requestScope.c}" />
<c:set var="d" value="${[Link]}" />
ContextVal:<c:out value="${a}"/><br>
SessionVal:<c:out value="${b}"/><br>
RequestVal:<c:out value="${c}"/><br>
PageVal:<c:out value="${d}"/><br> </body>
</html>

[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
===========================================================================
faq:
define pageContext?
=>pageContext is an implicit object generated for
[Link] AbstractClass and which is extended
from [Link] AbstractClass.
=>using pageContext object we can access remaining implicit
objects of JSP.
The following are some important methods:

public abstract [Link] getOut();


public abstract [Link] getSession();
public abstract [Link] getRequest();
public abstract [Link] getResponse();
public abstract [Link] getPage();
public abstract [Link] getException();
public abstract [Link] getServletConfig();
public abstract [Link]
getServletContext();
============================================================
faq:
define "page"?
=>"page" is an implicit object of [Link]
class,this "page" object is used when we want the methods of
[Link] class.

Note:
=>page implicit object is used part of JSP,when we want to
perform Cloning process or Thread communication process.
=========================================================

Some Example Programs on JSP EL-JSTL:


Exp_Program:(CoreTags)
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="[Link]">
Enter the String:<input type="text" name="str"><br>
<input type="submit" value="Display">
</form>
</body>
</html>
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib prefix="c" uri="[Link] %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<c:set var="n" value="${[Link]}" />
<c:forEach var="j" begin="1" end="5">
<c:out value="${n}"/>
<p> </c:forEach> <c:forTokens items="${[Link]}" delims=" " var="name">
<c:out value="${name}"/><p>
</c:forTokens>
</body>
</html>
-------------------------------------------------------------------------------------------------------------
Ex_Program:(Function Tags)
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="[Link]">
Enter the String:<input type="text" name="str"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="[Link] prefix="c" %>
<%@ taglib uri="[Link] prefix="fn" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<c:set var="s1" value="${[Link]}"/> <c:choose> <c:when test="${fn:contains(s1,
'java')}">
<p>String Founded<p>
</c:when> <c:otherwise>
<p>String Not Founded<p>
</c:otherwise> </c:choose> <c:if test="${fn:containsIgnoreCase(s1, 'JAVA')}">
<p>String Founded<p> </c:if>
</body>
</html>
-------------------------------------------------------------------------------------------------------------
Ex_Program:(formatting Tags)
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="[Link]
<%@ taglib prefix="fmt" uri="[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>Different Formats of the Date</h2>
<c:set var="Date" value="<%=new [Link]()%>" />
<p> Formatted Time : <fmt:formatDate type="time" value="${Date}" /> </p>
<p> Formatted Date : <fmt:formatDate type="date" value="${Date}" /> </p>
<p> Formatted Date and Time : <fmt:formatDate type="both" value="${Date}" /> </p>
<p> Formatted Date and Time in short style : <fmt:formatDate type="both"
dateStyle="short" timeStyle="short" value="${Date}" /> </p>
<p> Formatted Date and Time in medium style :
<fmt:formatDate type="both" dateStyle="medium"
timeStyle="medium" value="${Date}" /> </p>
<p> Formatted Date and Time in long style : <fmt:formatDate
type="both" dateStyle="long" timeStyle="long" value="${Date}" /> </p>
</body>
</html>
==================================================================
Dt : 29/12/2023
*imp
Web Architecture Models:(Web Application Architectures)

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

These models are:

1. Model-1 Architecture
2. Model-2 Architecture

1. Model-1 Architecture:

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

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)Involves the developer at both the page development and the


business logic implementation stages.

(iii)Increases the complexity of a program with the increase in


the size of the JSP page.

Exp:
JSP_App1
JSP_App2
JSP_App3

===========================================================
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 and this Model-2 architecture is based
on the MVC design model.

Diagram:

=>MVC Stands for Model View Controller.

Model: Represents enterprise data and business rules that specify


how data is accessed and updated,and which is generally
implemented by using JavaBeans.

View: Shows the contents of a [Link] View component accesses


enterprise data through the Model component and specifies how
that data should be presented and this View Component is
designed by JSP.
Controller: Receives HTTP requests. The Controller component
receives 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
business logic of other applications.

(ii)Offers great flexibility to the presentation logic, which


can be modified without effecting the business logic.
=======================================================================
faq:
define Error Code?
=>The numeric number which defines the type of error occured in the application
is known as Error Code
=>when we want to terminate the web application,then we generate Error_code with
msg and terminate the application.
=>HttpServletResponse will provide fields to represent Error_codes
Ex:
public static final int SC_CONTINUE;
public static final int SC_SWITCHING_PROTOCOLS;
public static final int SC_OK;
public static final int SC_CREATED;
public static final int SC_ACCEPTED;
...
=>we use sendError() method from HttpServletResponse to send Error_code with msg
Methods Signatures:
public abstract void sendError
(int, [Link]) throws [Link];
public abstract void sendError(int) throws [Link];
-----------------------------------------------------------------------
faq:
define sendRedirect() method?
=>sendRedirect() method is from HttpServletResponse and which is used to send
response to another WebApplication executing on same server or different
server.
Method Signature:
public abstract void sendRedirect([Link])
throws [Link];
===================================================================
Code Message Description
Only a part of the request has been
received by the server, but as long as it
100 Continue
has not been rejected, the client should
continue with the request
101 Switching Protocols The server switches protocol.
200 OK The request is OK
The request is complete, and a new
201 Created
resource is created
The request is accepted for processing,
202 Accepted
but the processing is not complete.
Non-authoritative
203
Information
204 No Content
205 Reset Content
206 Partial Content
A link list. The user can select a link and
300 Multiple Choices go to that location. Maximum five
addresses
The requested page has moved to a
301 Moved Permanently
new url
The requested page has moved
302 Found
temporarily to a new url
The requested page can be found under
303 See Other
a different url
304 Not Modified
305 Use Proxy
This code was used in a previous
306 Unused version. It is no longer used, but the
code is reserved
The requested page has moved
307 Temporary Redirect
temporarily to a new url.
400 Bad Request The server did not understand the
request
The requested page needs a username
401 Unauthorized
and a password
402 Payment Required You cannot use this code yet
403 Forbidden Access is forbidden to the requested
page
The server cannot find the requested
404 Not Found page.

The method specified in the request is


405 Method Not Allowed
not allowed.
The server can only generate a
406 Not Acceptable response that is not accepted by the
client.
Proxy Authentication You must authenticate with a proxy
407 Required server before this request can be
served.
The request took longer than the server
408 Request Timeout
was prepared to wait.
The request could not be completed
409 Conflict
because of a conflict.
410 Gone The requested page is no longer
available.
The "Content-Length" is not defined. The
411 Length Required server will not accept the request without
it.
The precondition given in the request
412 Precondition Failed
evaluated to false by the server.
Request Entity Too The server will not accept the request,
413
Large because the request entity is too large.
The server will not accept the request,
because the url is too long. Occurs when
414 Request-url Too Long
you convert a "post" request to a "get"
request with a long query information.
The server will not accept the request,
Unsupported Media
415 because the media type is not
Type
supported.
417 Expectation Failed
The request was not completed. The
500 Internal Server Error
server met an unexpected condition.
The request was not completed. The
501 Not Implemented server did not support the functionality
required.
The request was not completed. The
502 Bad Gateway server received an invalid response from
the upstream server.
The request was not completed. The
503 Service Unavailable server is temporarily overloading or
down.
504 Gateway Timeout The gateway has timed out.
HTTP Version Not The server does not support the "http
505
Supported protocol" version.

THE END```

You might also like