0% found this document useful (0 votes)
6 views256 pages

Adv Java

The document provides a comprehensive overview of JDBC (Java Database Connectivity) API, detailing the 'java.sql' package, the 'Connection' interface, and its methods for establishing a connection with a database. It explains the creation and execution of JDBC applications, including the use of Statement, PreparedStatement, and CallableStatement for executing queries. Additionally, it includes sample Java programs demonstrating how to connect to a database, execute queries, and handle user input for database operations.

Uploaded by

bsrassignment
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)
6 views256 pages

Adv Java

The document provides a comprehensive overview of JDBC (Java Database Connectivity) API, detailing the 'java.sql' package, the 'Connection' interface, and its methods for establishing a connection with a database. It explains the creation and execution of JDBC applications, including the use of Statement, PreparedStatement, and CallableStatement for executing queries. Additionally, it includes sample Java programs demonstrating how to connect to a database, execute queries, and handle user input for database operations.

Uploaded by

bsrassignment
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

Dt : 8/5/2023

*imp

JDBC API:

=>"[Link]" package is known as JDBC-API.

=>"[Link]" interface is the root of JDBC-API.

=>The following are some important methods of "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 the implementation object for "Connection"

interface.
Method Signature of getConnection():

public static [Link] getConnection([Link],

[Link], [Link]) throws [Link];

syntax:

Connection con = [Link]

("db-url","username","password");

db-url => jdbc:oracle:thin:@localhost:1521:xe

username => system

password => manager

Diagrams:

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

*imp

=>We use the following steps to establish commincation b/w

JavaProgram and DB Product:


step-1 : Loading driver

step-2 : Creating Connection

step-3 : preparing statements

step-4 : executing queries

step-5 : closing connection

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

*imp

JDBC statements:

=>JDBC statements will specify the type of action to be performed

on DB-Product.

=>These JDBC statements are categorized into three types:

[Link]

[Link]

[Link]

Dt : 9/5/2023

*imp

JDBC statements:

=>JDBC statements will specify the type of action to be performed

on DB-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 on DB-product without IN-parameters.

=>we use "createStatement()" method from "Connection" interface

to create the implementation object for "Statement" interface.

syntax:
Statement stm = [Link]();

=>The following are some important methods of "Statement":

(i)executeQuery()

(ii)executeUpdate()

(i)executeQuery():

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

syntax:

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

(ii)executeUpdate():

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

like Create,Insert,Update and delete.

syntax:

int k = [Link]("NonSelect-query");

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

*imp

Creating and executing JDBC Application using IDE Eclipse:

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

Click "Launch"

step-2 : Create Java Project

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

"Next"->name the project and click "Finish"

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

RightClick on Java Project->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

step-6 : Type the JDBC code to retrieve data from the table:EMP52

Program : [Link]
package test;
import [Link].*;
public class DBCon1 {
public static void main(String[] args) {
try
{
[Link]("[Link]");
//Loading driver

Connection con = [Link]


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

Statement stm = [Link]();


//Preparing statement

ResultSet rs = [Link]("select * from Emp52");


//Executing query

while([Link]())
{
[Link]([Link](1)+"\t"+
[Link](2)+"\t"+[Link](3)+"\t"+
[Link](4));
}//end of loop

[Link]();
//closing connection
}//end of try
catch(Exception e)
{
[Link]();
}
}
}

o/p:

A111 Alex SE 19000

A121 Raj TE 18000

A120 Ram ME 17000

========================================================
Assignment:

Step-1 : Create table with name Product52

(pcode,pname,pprice,pqty)

Step-2 : Insert min 5 records into Product52

step-3 : Construct JDBC Application to display the Product-details

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

Dt : 10/5/2023

Execution flow of above program:([Link])

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

*imp

Construct JDBC Application to read date from Console and insert

into DB-table(Emp52):

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 empId:");
String id = [Link]();
[Link]("Enter the empName:");
String name = [Link]();
[Link]("Enter the empDesg:");
String desg = [Link]();
[Link]("Enter the empSal:");
int sal = [Link]();

Connection con = [Link]


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

Statement stm = [Link]();


//Preparing statement

int k = [Link]
("insert into Emp52
values('"+id+"','"+name+"','"+desg+"',"+sal+")");
if(k>0)
{
[Link]("Record inserted
Successfully..");
}
[Link]();
}//end of try
catch(InputMismatchException ime)
{
[Link]("Invalid input...");
}
catch(SQLIntegrityConstraintViolationException sicve)
{
[Link]("Employee details already
available...");
}
catch(SQLException cnfe)
{
[Link]();
}
}//end of try with resource
}
}

o/p:

Enter the empId:

B130
Enter the empName:

Ram

Enter the empDesg:

SE

Enter the empSal:

16000

Record inserted Successfully..

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

Assignment:

Construct JDBC Application to read Product details from Console and

insert into DB-table(Product52)

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

*imp

[Link]:

=>PreparedStatement is an interface from [Link] package and

which is used to execute normal-queries on DB-product with

IN-parameters

=>we use parepareStatement() method from Connection interface

to create implementation object for "PreparedStatement" interface.

syntax:

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

=>The following are some important methods of PreparedStatement:

(i)executeQuery() - used for select-queries

(ii)executeUpdate() - used for NonSelect-queries

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

Dt : 11/5/2023
Table : BookDetails52

(bcode,bname,bauthor,bprice,bqty)

Create table BookDetails52(bcode varchar2(10),bname varchar2(15),


bauthor varchar2(15),bprice number(10,2),bqty number(10),

primary key(bcode));

Construct JDBC Application to perform the following operations

based on User-Choice:

[Link]

[Link]

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 {
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
//Creating Connection
PreparedStatement ps1 = [Link]
("insert into BookDetails52 values(?,?,?,?,?)");
//Compilation
PreparedStatement ps2 = [Link]
("select * from BookDetails52");
//Compilation
while(true) {
[Link]("****Choice****");
[Link]("\[Link]"
+ "\n\[Link]"
+ "\n\[Link]");
[Link]("Enter the Choice:");
int choice = [Link]([Link]());
switch(choice) {
case 1:
[Link]("Enter the BookCode:");
String bC = [Link]();
[Link]("Enter the BookName:");
String bN = [Link]();
[Link]("Enter the
BookAuthor:");
String bA = [Link]();
[Link]("Enter the
BookPrice:");
float bP = [Link]([Link]());
[Link]("Enter the BookQty:");
int bQ = [Link]([Link]());

//Setting data to ps1-Object


[Link](1, bC);
[Link](2, bN);
[Link](3, bA);
[Link](4, bP);
[Link](5, bQ);

int k = [Link]();//Execution
if(k>0) {
[Link]
("BookDetails inserted
Successfully...");
}
break;
case 2:
ResultSet rs = [Link]();
//Execution
[Link]("****Book-
Details****");
while([Link]()) {

[Link]([Link](1)+"\t"
+[Link](2)+"\t"+
[Link](3)+"\t"+
[Link](4)+"\t"
+[Link](5));
}//end of loop
break;
case 3:
[Link]("Operation on DB
Stopped...");
[Link](0);
default:
[Link]("Invalid Choice..");
}//end of switch
}//end of loop
}catch(Exception e) {
[Link]();
}
}//end of try with resource
}
}

o/p:

****Choice****

[Link]

[Link]

[Link]

Enter the Choice:


1

Enter the BookCode:

A101

Enter the BookName:

Enter the BookAuthor:

B-Swamy

Enter the BookPrice:

1200

Enter the BookQty:

12

BookDetails inserted Successfully...

****Choice****

[Link]

[Link]

[Link]

Enter the Choice:

Enter the BookCode:

A123

Enter the BookName:

CoreJ

Enter the BookAuthor:

XYZ

Enter the BookPrice:

1700

Enter the BookQty:

17

BookDetails inserted Successfully...

****Choice****

[Link]
[Link]

[Link]

Enter the Choice:

****Book-Details****

A101 null B-Swamy 1200.0 12

A123 CoreJ XYZ 1700.0 17

****Choice****

[Link]

[Link]

[Link]

Enter the Choice:

Enter the BookCode:

A345

Enter the BookName:

AdvJ

Enter the BookAuthor:

PQR

Enter the BookPrice:

1900

Enter the BookQty:

19

BookDetails inserted Successfully...

****Choice****

[Link]

[Link]

[Link]

Enter the Choice:

2
****Book-Details****

A101 null B-Swamy 1200.0 12

A123 CoreJ XYZ 1700.0 17

A345 AdvJ PQR 1900.0 19

****Choice****

[Link]

[Link]

[Link]

Enter the Choice:

Operation on DB Stopped...

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

Assignment:

DB table : BankCustomer52

(accno,custname,balance,acctype)

Costruct JDBC application to perform the following operations:

(PreparedStatement)

[Link]

[Link]

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

Dt : 12/5/2023

Program : [Link](Updated Program)

package test;

import [Link].*;

import [Link].*;

public class DBCon3 {

public static void main(String[] args) {

Scanner s = new Scanner([Link]);


try(s;){

try {

Connection con = [Link]

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

//Creating Connection

PreparedStatement ps1 = [Link]

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

//Compilation

PreparedStatement ps2 = [Link]

("select * from BookDetails52");

//Compilation

PreparedStatement ps3 = [Link]

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

PreparedStatement ps4 = [Link]

("update BookDetails52 set bprice=?,bqty=bqty+? where


bcode=?");

PreparedStatement ps5 = [Link]

("delete from BookDetails52 where bcode=?");

while(true) {

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

[Link]("\[Link]"

+ "\n\[Link]"

+ "\n\[Link]"

+ "\n\[Link](Price/Qty)"

+ "\n\[Link]"

+ "\n\[Link]");

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

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

switch(choice) {

case 1:

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


String bC = [Link]();

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

String bN = [Link]();

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

String bA = [Link]();

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

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

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

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

//Setting data to ps1-Object

[Link](1, bC);

[Link](2, bN);

[Link](3, bA);

[Link](4, bP);

[Link](5, bQ);

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

if(k>0) {

[Link]

("BookDetails inserted Successfully...");

break;

case 2:

ResultSet rs = [Link]();

//Execution

[Link]("****Book-Details****");

while([Link]()) {

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

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

[Link](4)+"\t"

+[Link](5));

}//end of loop

break;

case 3:

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

String code = [Link]();

//setting data to ps3-Object

[Link](1, code);

ResultSet rs2 = [Link]();

if([Link]()) {

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

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

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

[Link](4)+"\t"

+[Link](5));

}else {

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

break;

case 4:

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

String code2 = [Link]();

[Link](1, code2);

ResultSet rs3 = [Link]();

if([Link]()) {

[Link]("Old Book price : "+[Link](4));


[Link]("Enter new BookPrice : ");

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

[Link]("Old Book Qty:"+[Link](5));

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

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

[Link](1, nPrice);

[Link](2, nQty);

[Link](3, code2);

int k2 = [Link]();

if(k2>0) {

[Link]("Book price and qty


Updated...");

}else {

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

break;

case 5:

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

String code3 = [Link]();

[Link](1, code3);

ResultSet rs4 = [Link]();

if([Link]()) {

[Link](1, code3);

int k3 = [Link]();

if(k3>0) {

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

}else {
[Link]("Invalid BookCode...");

break;

case 6:

[Link]("Operation on DB Stopped...");

[Link](0);

default:

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

}//end of switch

}//end of loop

}catch(Exception e) {

[Link]();

}//end of try with resource

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

Diagram:
========================================================
Dt : 13/5/2023

faq:

wt is the diff b/w

(i)Statement

(ii)PreparedStatement

=>When we perform multiple insert-operations,

=>If we use "Statement" then query is compiled and executed

Multiple times.

=>If we use "PreparedStatement" then query is compiled only

once,but executed multiple times.

Note:

=>PreparedStatement will have highperformance than Statement.

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

Assignment-1:

Step-1 : Create table with name UserReg52

(uname,pword,fname,lname,addr,mid,phno)

Primary Key : uname,pword

step-2 : Construct JDBC Application to perform the following

Operations:

[Link]

[Link]

[Link]

[Link]:

=>Perform User registration process.

=>After User registration process is successfull,then repeat the

choice

[Link]

[Link]
[Link]

[Link]:

=>read uname and pword,then perform login-process

=>If login process is failed the repeat the choice

=>If the login process is successfull then show the followig

choice:

[Link] Profile

[Link] Profile(addr,mailid,phno)

[Link](Exit)

=>repeat the choice

[Link]

[Link]

[Link]

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

Assignment-1:

step-1 : Create tables,

Student52(rollNo,name,branch,totmarks,per,grade)

StuMarks52(rollNo,sub1,sub2,sub3,sub4,sub5,sub6)

step-2 : Construct JDBC Application to perform the following

Operations

[Link]

[Link]

[Link]

[Link]

[Link]:

=>read rollNo,name,branch,6 submarks

=>Calculate totM,per,grade

[Link]
[Link]

[Link]

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

Note:

=>The following some important DB-Jar files related SB-Products:

Oracle - [Link],[Link], [Link], [Link],

[Link]

Oracle10 - [Link]

Oracle11 - [Link]

oracle12 - [Link],[Link]

other - [Link](Universal Connection pool)

([Link])

MySQL - [Link]

SQL Server - [Link], [Link]

PostgreSQL - [Link]

Apache Derby - [Link], [Link]

SQLite - [Link]

Microsoft Access - [Link]

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

Dt : 15/5/2023

faq:

define ResultSet?

=>"ResultSet" is an interface from [Link] package and which

is used to hold result generated from select-queries.

=>The following syntax is used to create implementation object

for ResultSet interface:

(i)Using Statement:
ResultSet rs = [Link]("select-query");

(ii)Using PreparedStatemnent:

ResultSet rs = [Link]();

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

Types of ResultSet objects:

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

categorized into two types:

[Link]-Scrollable ResultSet object

[Link] ResultSet object

[Link]-Scrollable ResultSet object:

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

in one direction,which means the cursor moves from

top-of-the-table-data to Bottom-of-table-data.

Ex:

above programs related to ResultSet

*imp

[Link] ResultSet object:

=>In Scrollable ResultSet objects the cursor can be moved in

two directions,which means down the table data and upward the

table data.

syntax for Creating Scrollable ResultSet object:

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

PreparedStatement ps = [Link]("query-S",type,mode);

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

Mode:

public static final int CONCUR_READ_ONLY=1007

public static final int CONCUR_UPDATABLE=1008

Note:

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

the action to be performed(read or update).

The following are some Methods used to control cursor on

Scrollable ResultSet object:

afterLast() =>Moves the cursor after the Last row

beforeFirst() =>Moves the cursor before the First row

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

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

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

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

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

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

in forward or backward direction by increment or

decrement.

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

Ex-program :

[Link](MainClass)
package test;
import [Link].*;
public class DBCon4 {
public static void main(String[] args) {
try {
Connection con = [Link]

("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
//Creating Connection
Statement stm = [Link]
(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = [Link]
("select * from BookDetails52");
[Link]("****Table data in reverse*****");
[Link]();//Cursor pointing after last row
while([Link]()) {
[Link]([Link](1)+"\t"
+[Link](2)+"\t"
+[Link](3)+"\t"
+[Link](4)+"\t"
+[Link](5));
}//end of loop
PreparedStatement ps = [Link]
("select * from BookDetails52",1004,1007);
ResultSet rs2 = [Link]();
[Link]("****Row-3****");
[Link](3);
[Link]([Link](1)+"\t"
+[Link](2)+"\t"
+[Link](3)+"\t"
+[Link](4)+"\t"
+[Link](5));
[Link]("****relative(-2)****");
[Link](-2);
[Link]([Link](1)+"\t"
+[Link](2)+"\t"
+[Link](3)+"\t"
+[Link](4)+"\t"
+[Link](5));
[Link]("****relative(+1)****");
[Link](+1);
[Link]([Link](1)+"\t"
+[Link](2)+"\t"
+[Link](3)+"\t"
+[Link](4)+"\t"
+[Link](5));
}catch(Exception e) {
[Link]();
}
}
}

o/p:

****Table data in reverse*****

A212 AdvJ XYZ 1900.0 19

A234 CoreJ PQR 1700.0 17

A123 CoreJ XYZ 1700.0 17

A101 null B-Swamy 1200.0 12


****Row-3****

A234 CoreJ PQR 1700.0 17

****relative(-2)****

A101 null B-Swamy 1200.0 12

****relative(+1)****

A123 CoreJ XYZ 1700.0 17

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

Assignment:

Construct JDBC Application to peform the following operations on

Product52 - table based on User-Choice:

[Link] Normal

[Link] Reverse

[Link] Last Row

[Link] First Row

[Link] Specified row(absolute())

[Link]

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

Dt : 16/5/2023

*imp

Batch Processing in JDBC:

=>The process of collecting multiple queries as batch and

executing at-a-time is known as Batch Processing.

=>The following methods are used in Batch Processing:

(a)addBatch()

(b)executeBatch()

(c)clearBatch()

(a)addBatch():

=>This addBatch() method is used to add query to the batch.

Method Signature:
public abstract void addBatch([Link])

throws [Link];

(b)executeBatch():

=>This executeBatch() method will execute all the queries from

the batch on Database product.

Method Signature:

public abstract int[] executeBatch() throws [Link];

(c)clearBatch():

=>This clearBatch() method will delete the queries from the

batch and destroys the batch.

Method Signature:

public abstract void clearBatch() throws [Link];

Note:

=>These methods are available from Statement and PreparedStatement

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

Case-1 : Batch Processing using "Statement"

Program : [Link]

package test;

import [Link].*;

import [Link].*;

public class DBCon5 {

public static void main(String[] args) {

Scanner s = new Scanner([Link]);

try(s){

try {

Connection con = [Link]

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

Statement stm = [Link]();


[Link]("****Enter BookDetails****");

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

String code = [Link]();

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

String name = [Link]();

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

String author = [Link]();

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

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

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

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

[Link]("====Delete employee====");

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

String id = [Link]();

[Link]

("insert into BookDetails52


values('"+code+"','"+name+"','"+author+"',"+price+","+qty+")");

[Link]("delete from Emp52 where id='"+id+"'");

int k[] = [Link]();

for(int i=0;i<[Link];i++) {

[Link]("Executed Successfully...");

[Link]();

[Link]();

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

}//end of try

}
}

o/p:

****Enter BookDetails****

Enter the code:

A312

Enter the name:

HB-JPA

Enter the author:

PQR

Enter the price:

1800

Enter the qty:

18

====Delete employee====

Enter the empId:

A111

Executed Successfully...

Executed Successfully...

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

Case-2 : Batch Processing using "PreparedStatement"

Table : Product52

package test;

import [Link].*;

import [Link].*;

public class DBCon6 {

public static void main(String[] args) {

Scanner s = new Scanner([Link]);

try(s;){

try {

Connection con = [Link]


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

//Creating Connection

PreparedStatement ps = [Link]

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

[Link]("Enter the number of Products:");

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

[Link]("Enter "+n+" Product details...");

for(int i=1;i<=n;i++) {

[Link]("****Details of Product-"+i+"****");

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

String code = [Link]();

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

String name = [Link]();

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

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

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

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

[Link](1, code);

[Link](2, name);

[Link](3, price);

[Link](4, qty);

[Link]();//Query will values added to batch

}//end of loop

int k[] = [Link]();

for(int i=0;i<[Link];i++) {

[Link]("Executed Successfully...");

[Link]();
[Link]();

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

}//end of try with resource

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

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

Program : [Link](MainClass)

o/p:

Enter the number of Products:

Enter 3 Product details...

****Details of Product-1****

Enter the ProdCode:

A102

Enter the ProdName:

Mou

Enter the ProdPrice:

1200

Enter the ProdQty::

12

****Details of Product-2****

Enter the ProdCode:

A204

Enter the ProdName:

CDR

Enter the ProdPrice:

1200

Enter the ProdQty::


12

****Details of Product-3****

Enter the ProdCode:

A312

Enter the ProdName:

KB

Enter the ProdPrice:

1400

Enter the ProdQty::

14

Executed Successfully...

Executed Successfully...

Executed Successfully...

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

Note:

(i)Batch Processing using "Statement",we can update multiple

DB tables at-a-time.

(ii)Batch Processing using "PreparedStatement",we can update

Same DB table by executing same query multiple times by changing

the values.

(iii)"Statement" is more efficient than PreparedStatement in

Batch Processing.

(iv)Using Batch processing we can execute only NonSelect queries

because of this reason Batch Processing is also known as "Batch

update processing"

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

faq:

wt is the advantage of Batch Processing?

=>Using Batch Processing we can execute multiple queries at-a-time

and which saves the execution time and generate highperformance


of an application.

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

Dt : 17/5/2023

*imp

Transaction Management in JDBC:

define Transaction?

=> The 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:

=>The process of moving the transaction to completed state is

known as Atomicity.

C - Consistency:

=>The process of making the state of resources selected by the

user,same until the transaction is completed is known as

Consistency

I - Isolation:

=>The process of running multiple users independently is known

as Isolation.

D - Durability:

=>The process of storing transation details and making it available

for user is known as Durability.

--------------------------------------------------------
define Transaction Management?

=>The process of controlling the transaction from starting to

ending of transaction is known as Transaction Management.

=>To perform Transaction Management in JDBC,we have to make

auto-commit operation "false"

=>The folowing are some important methods used in Transaction

Management:

(a)setAutoCommit()

(b)getAutoCommit()

(c)commit()

(d)rollback()

(e)setSavepoint()

(f)releaseSavepoint()

(a)setAutoCommit():

=>setAutoCommit() method is used to set auto-commit operation

to "false" or "true"

syntax:

[Link](false);

(b)getAutoCommit():

=>getAutoCommit() method is used to get the status of auto-commit

operation.

syntax:

boolean k = [Link]();

(c)commit():

=>commit() method is used to store the data from buffer to

database permanently.

syntax:

[Link]();
(d)rollback():

=>rollback() method is used to change modified state to original

state.

=>This rollback() method is used when transaction failed.

syntax:

[Link](sp);

(e)setSavepoint():

=>setSavepoint() method will specify the check-point to perform

rollback-operation.

syntax:

Savepoint sp = [Link]();

(f)releaseSavepoint():

=>releaseSavepoint() method is used to delete the save points.

syntax:

[Link](sp);

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

Ex-program:

Table : Bank52

(accno,name,bal,acctype)

create table Bank52(accno number(15),name varchar2(15),

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

insert into Bank52 values(6123456,'Raj',12000,'savings');

insert into Bank52 values(313131,'Alex',500,'savings');

Transaction : Transfer amt:3000/- from

accNo:6123456 to accNo:313131
SubT1 : Subtract 3000/- from accNo : 6123456

SubT2 : Add 3000/- to accNo : 313131

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 {
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
[Link]("Status of AutoCommit :
"+[Link]());
[Link](false);
[Link]("Status of AutoCommit :
"+[Link]());
PreparedStatement ps1 = [Link]
("select * from Bank52 where
accNo=?");
PreparedStatement ps2 = [Link]
("update Bank52 set bal=bal+? where
accNo=?");
Savepoint sp = [Link]();
[Link]("Enter the Home AccNo:");
long hAccNo = [Link]();
[Link](1, hAccNo);
ResultSet rs1 = [Link]();
if([Link]()) {
float bl = [Link](3);
[Link]("Enter beneficiery
AccNo:");
long bAccNo = [Link]();
[Link](1, bAccNo);
ResultSet rs2 = [Link]();
if([Link]()) {
[Link]("Enter the amt to be
Transferred:");
float amt = [Link]();
if(amt<=bl) {
[Link](1,-amt);
[Link](2, hAccNo);
int i = [Link]();//Updated
in buffer

[Link](1, amt);
[Link](2, bAccNo);
int j = [Link]();//Updated
in buffer
if(i==1 && j==1) {
[Link]("Transaction
Successfull...");
[Link]();//Update the database
}else {
[Link]("Transaction
Failed...");
[Link](sp);
}
}else {
[Link]("Insufficient
fund...");
}
}else {
[Link]("Invalid
bAccNo...");
}
}else {
[Link]("Invalid
homeAccNo...");
}
}catch(Exception e) {[Link]();}
}//end of try with resource
}
}

o/p:

Status of AutoCommit : true

Status of AutoCommit : false

Enter the Home AccNo:

6123456

Enter beneficiery AccNo:

313131

Enter the amt to be Transferred:

3000

Transaction Successfull...

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

ACCNO NAME BAL ACCTYPE

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

6123456 Raj 12000 savings

313131 Alex 500 savings


SQL> select * from Bank52;

ACCNO NAME BAL ACCTYPE

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

6123456 Raj 9000 savings

313131 Alex 3500 savings

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

Dt : 18/5/2023

Diagram:(Demonstrating Transaction Management)

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

Assignment:

DBtable : TransLogTab52

(haccno,baccno,amt,dateTime)

Update above Application to recored transaction details into

TransLogTab52 when Transaction is Successfull.

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

Assignmet:
Construct JDBC Application to display transsaction details based

on hAccNo.

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

*imp

Connection Pooling in JDBC:

=>The process of organizing multiple pre-initialized database

connections among multiple users is known as Connection Pooling

process.

Diagram:

Ex-Application:

[Link]
package test;
import [Link].*;
import [Link].*;
public class ConnectionPooling {
public String dbUrl,uName,pWord;
public ConnectionPooling(String dbUrl,String uName,
String pWord) {
[Link]=dbUrl;
[Link]=uName;
[Link]=pWord;
}
public Vector<Connection> v = new Vector<Connection>();
public void createConnections() {
try {
while([Link]()<5) {
[Link]("Pool is not full....");
Connection con = [Link]
(dbUrl,uName,pWord);
[Link](con);
[Link](con);
}//end of loop
if([Link]()==5) {
[Link]("Pool is full....");
}
}catch(Exception e) {[Link]();}
}//end of method

[Link](MainClass)
package test;
public class DBCon8 {
public static void main(String[] args) {
ConnectionPooling cp = new ConnectionPooling
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
[Link]();
}
}

o/p:

Pool is not full....

[Link].T4CConnection@3159c4b8

Pool is not full....

[Link].T4CConnection@6328d34a

Pool is not full....

[Link].T4CConnection@145eaa29

Pool is not full....

[Link].T4CConnection@2d2e5f00

Pool is not full....

[Link].T4CConnection@4c40b76e

Pool is full....

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

Dt : 19/5/2023
Note:

=>In Connection-Pooling process we use Vector<E> to hold multiple

pre-initialized database connections

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

Hierarchy of Vector<E>:

Diagram:
Program:

[Link](Modified)

package test;

import [Link].*;

import [Link].*;

public class ConnectionPooling {

public String dbUrl,uName,pWord;//Instance Variables

//Initialized using Constructor

public ConnectionPooling(String dbUrl,String uName,

String pWord) {

[Link]=dbUrl;

[Link]=uName;

[Link]=pWord;

}
//Instance reference variable(Tightly Coupled reference)

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

//Instance method

public void createConnections() {

try {

while([Link]()<5) {

[Link]("Pool is not full....");

Connection con = [Link]

(dbUrl,uName,pWord);

[Link](con);//Adding to Vector Object

[Link](con);

}//end of loop

if([Link]()==5) {

[Link]("Pool is full....");

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

}//end of method

public synchronized Connection useConnection() {

Connection con = [Link](0);

//Taking the element from index 0

[Link](0);//Element deleted from Vector

return con;

}//end of method

public synchronized void returnConnection(Connection con) {

[Link](con);//Adding the Connection back to Vector

[Link]("Connection added back to pool...");

}//end of method

[Link](MainClass)(Modified)
package test;
import [Link].*;
public class DBCon8 {
public static void main(String[] args) {
ConnectionPooling cp = new ConnectionPooling
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
[Link]();//method call
[Link]("*****User-1*****");
Connection cn1 = [Link]();
[Link]("Con at user-1 : "+cn1);
[Link]("Size of pool : "+[Link]());
try {
PreparedStatement ps1 = [Link]("Select *
from Product52");
ResultSet rs1 = [Link]();
while([Link]()) {
[Link]([Link](1)+"\t"+
[Link](2)+"\t"+[Link](3)+
"\t"+[Link](4));
}//end of loop
}catch(Exception e) {[Link]();}
[Link]("****User-2****");
Connection cn2 = [Link]();
[Link]("Con at user-2 : "+cn2);
[Link]("Size of pool : "+[Link]());
try {
PreparedStatement ps2 = [Link]
("Select * from Emp52");
ResultSet rs2 = [Link]();
while([Link]()) {
[Link]([Link](1)+
"\t"+[Link](2)+
"\t"+[Link](3)+
"\t"+[Link](4));
}//end of loop
}catch(Exception e) {[Link]();}
[Link]("*****User-1****");
[Link](cn1);
[Link]("Size of pool : "+[Link]());
[Link]("*****User-2****");
[Link](cn2);
[Link]("Size of pool : "+[Link]());
[Link]("-----Display Connections----");
[Link]((k)->
{
[Link](k);
});
}
}

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

*****User-1*****

Con at user-1 : [Link].T4CConnection@3159c4b8

Size of pool : 4

A102 Mou 1200.0 12

A204 CDR 1200.0 12

A312 KB 1400.0 14

****User-2****

Con at user-2 : [Link].T4CConnection@525f1e4e

Size of pool : 3

A121 Raj TE 18000

A120 Ram ME 17000

B130 Ram SE 16000

B123 RTY TE 15000

*****User-1****

Connection added back to pool...

Size of pool : 4

*****User-2****

Connection added back to pool...

Size of pool : 5

-----Display Connections----
[Link].T4CConnection@75f9eccc

[Link].T4CConnection@67e2d983

[Link].T4CConnection@5d47c63f

[Link].T4CConnection@3159c4b8

[Link].T4CConnection@525f1e4e

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

Dt : 20/5/2023

*imp

[Link]:

=>CallableStatement is an interface from [Link] package and

which is used to execute "Procedures" and "Functions" on Database

product.

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

create implementation object for "CallableStatement".

syntax:

CallableStatement cs = [Link]("{call proc/func}");

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

Diagram:
faq:

define Procedure?

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

and after execution it will not return any value.

(Procedure means Non-return_type)

structure of procedure:

create or replace procedure Proc_name

(para_list) is

begin

query1;

query2;

...

end;

define Function?

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

after execution it will return the value.


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

value after execution.

structure of Function:

create or replace function Func_name

(para_list)return data_type as var data_type;

begin

query1;

query2;

....

return var;

end;

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

*imp

Constructing and executing Procedure:

step-1 : Create the following tables related to Customer

CustDetails52(CustId,fname,lname)

CustAddress52(CustId,hno,sname,city,pincode)

CustContact52(CustId,mid,phno)

create table CustDetails52(CustId varchar2(10),fname varchar2(15),

lname varchar2(15),primary key(custId));

create table CustAddress52(CustId varchar2(10),hno varchar2(15),

sname varchar2(15),city varchar2(15),pincode number(10),

primary key(CustId));

create table CustContact52(CustId varchar2(10),mid varchar2(25),

phno number(15),primary key(CustId));

step-2 : Construct Procedure to insert Cust-data


create or replace procedure CustInsert52

(cid varchar2,fn varchar2,ln varchar2,hn varchar2,sn varchar2,

cty varchar2,pcode number,md varchar2,pno number) is

begin

insert into CustDetails52 values(cid,fn,ln);

insert into CustAddress52 values(cid,hn,sn,cty,pcode);

insert into CustContact52 values(cid,md,pno);

end;

Step-3 : Construct JDBC Application to execute procedure to insert

Customer-data

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]("Enter the CustId:");
String cId = [Link]();
[Link]("Enter the CustFirstName:");
String fName = [Link]();
[Link]("Enter the CustLastName:");
String lName = [Link]();
[Link]("Enter the hNo:");
String hNo = [Link]();
[Link]("Enter the StreetName:");
String sName = [Link]();
[Link]("Enter the City:");
String city = [Link]();
[Link]("Enter the PinCode:");
int pinCode = [Link]([Link]());
[Link]("Enter the MailId:");
String mId = [Link]();
[Link]("Enter the PhoneNo:");
long phNo = [Link]([Link]());

Connection con = [Link]


("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
CallableStatement cs = [Link]
("{call
CustInsert52(?,?,?,?,?,?,?,?,?)}");
[Link](1,cId);
[Link](2,fName);
[Link](3, lName);
[Link](4, hNo);
[Link](5, sName);
[Link](6, city);
[Link](7, pinCode);
[Link](8, mId);
[Link](9, phNo);

[Link]();
[Link]("Procedure executed
Successfully...");
[Link]("CustData updated....");
}catch(Exception e) {[Link]();}
}//end of try
}
}

o/p:

Enter the CustId:

E102

Enter the CustFirstName:

Raj

Enter the CustLastName:

Kumar

Enter the hNo:

12-34/h

Enter the StreetName:

SR Nagar

Enter the City:

Hyd

Enter the PinCode:

612345

Enter the MailId:

r@[Link]

Enter the PhoneNo:


9898981234

Procedure executed Successfully...

CustData updated....

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

Assignment:

Step-1 : Create the following tables related to Employee

EmpDetails52(eid,ename,edesg)

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

EmpContact52(eid,mid,phno)

EmpSalary52(eid,bsal,hra,da,totSal)

step-2 : Construct Procedure to insert employee details

step-3 : Construct JDBC application to execute Procedure

============================================================
Dt : 23/5/2023

Execution flow of program : [Link]

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

*imp

Types of Precedures:

=>Procedures are categorized into the following:

[Link]-Parameter Procedures

[Link]-Parameter Procedures

[Link]-Parameter Procedures:

=>The Procedures which take the data from JavaPrograms and

update database tables are known as IN-Parameter Procedures.

Ex:

above programs

[Link]-Parameter Procedures:

=>The procedures which take the data from database tables and

sent to the Program are known as OUT-Parameter Procedures

Ex-program:(Demonstrating OUT-parameter Procedure)

Step-1 : Construct Procedure to retrieve Customer-data based on

custId.

create or replace procedure CustRetrieve52


(cid varchar2,fn OUT varchar2,ln OUT varchar2,hn OUT varchar2,

sn OUT varchar2,cty OUT varchar2,pcode OUT number,md OUT varchar2,

pno OUT number) is

begin

select fname,lname into fn,ln from CustDetails52 where custid=cid;

select hno,sname,city,pincode into hn,sn,cty,pcode from

CustAddress52 where custid=cid;

select mid,phno into md,pno from CustContact52 where custid=cid;

end;

step-2 : Construct JDBC Application to execute OUT-parameter

Procedure.

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]("Enter the CustId:");
String cId = [Link]();
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
CallableStatement cs = [Link]
("{call CustRetrieve52(?,?,?,?,?,?,?,?,?)}");
[Link](1, cId);
[Link](2, [Link]);
[Link](3, [Link]);
[Link](4, [Link]);
[Link](5, [Link]);
[Link](6, [Link]);
[Link](7, [Link]);
[Link](8, [Link]);
[Link](9, [Link]);

[Link]();

[Link]("CId:"+cId);
[Link]("FName:"+[Link](2));
[Link]("LName:"+[Link](3));
[Link]("HNo:"+[Link](4));
[Link]("SName:"+[Link](5));
[Link]("City:"+[Link](6));
[Link]("PinCode:"+[Link](7));
[Link]("MID:"+[Link](8));
[Link]("PhNo:"+[Link](9));

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

o/p:

Enter the CustId:

E102

CId:E102

FName:Raj

LName:Kumar

HNo:12-34/h

SName:SR Nagar

City:Hyd

PinCode:612345

MID:r@[Link]

PhNo:9898981234

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

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

faq:

define registerOutParameter() method?

=>registerOutParameter() method is used to specify the type data

to be recorded from OUT-Parameter procedure.

Ex:

[Link](2, [Link]);

[Link](3, [Link]);

Note:

=>"Types" is a class from [Link] package and which specify

sql-types

Ex:

public static final int INTEGER;

public static final int BIGINT;

public static final int FLOAT;

public static final int VARCHAR;

....
===========================================================

Assignment:

step-1 : Construct OUT-parameter procedure to retrieve emp-data

based on empId

step-2 : Construct JDBC Application to execute OUT-Parameter

Procedure

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

Dt : 24/5/2023

*imp

Creating and Executing Functions:

step-1 : Construct function to retrieve phno of an Customer based

on custId.

create or replace function Retrievephno52

(cid varchar2)return number as pno number;

begin

select phno into pno from CustContact52 where custid=cid;

return pno;

end;

step-2 : Construct JDBC Application to execute Function

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]("Enter the CustId:");

String cId = [Link]();

Connection con = [Link]

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

CallableStatement cs = [Link]

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

[Link](1, [Link]);

[Link](2, cId);

[Link]();

[Link]("CustId:"+cId);

[Link]("PhNO:"+[Link](1));

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

}//end of try with resource

o/P:

Enter the CustId:

E102

CustId:E102

PhNO:9898981234

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

Assignment:

Construct and execute Function to retriev Emp-totSal based on empId.

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

*imp

Streams with Database:

define stream?(Normal definition)

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

Types of Streams:

=>Streams in Java are categorized into two types:

[Link] Stream

[Link] Stream

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

Audio,Video,Image and Animation

[Link] 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 Animation data.

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

=>The following are the sql-types support streams:

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

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

Ex-program:

Construct JDBC Application to store Image onto DB product.

DB Table : StreamTab52(id,mfile)
create table StreamTab52(id varchar2(10),mfile BLOB,

primary key(id));

Program : [Link]

package test;

import [Link].*;

import [Link].*;

import [Link].*;

public class DBCon12 {

public static void main(String[] args) {

Scanner s = new Scanner([Link]);

try(s;){

try {

Connection con = [Link]

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

PreparedStatement ps = [Link]

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

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

String id = [Link]();

[Link](1, id);

[Link]("Enter fPath&fName(Source):");

File f = new File([Link]());

FileInputStream fis = new FileInputStream(f);

[Link](2, fis, [Link]());

int k = [Link]();

if(k>0) {

[Link]("Image inserted to database Successfully");

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

}//end of try with resource

o/p:

Enter the id:

M101

Enter fPath&fName(Source):

C:\Images\IMG_4917.JPG

Image inserted to database Successfully

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

Ex-program:

Construct JDBC Application to retrieve Image from DB product based

on id.

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 {

Connection con = [Link]

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

PreparedStatement ps = [Link]

("select * from StreamTab52 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 fPath&fName(destination):");

File f = new File([Link]());

FileOutputStream fos = new FileOutputStream(f);

[Link](by);

[Link]("Image retrieved Successfully..");

[Link]();

}else {

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

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

}//end of try with resource

o/p:

Enter the Id:

M101

Enter fPath&fName(destination):

D:\Images\[Link]

Image retrieved Successfully..

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

Dt : 25/5/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 binary stream

data.

syntax:

FileInputStream fis = new FileInputStream("fpath&fname");

faq:

define FileOutputStream?

=>FileOutputStream is a class from [Link] package and which is

used to create a new file and opens the file to write binary stream

data.

syntax:

FileOutputStream fos = new FileOutputStream("fpath&fName");

faq:

define "File"?

=>"File" is a class from [Link] package and which is used to

fild the properties of file like file-lenth,file-path,file-exits

or not,...

syntax:

File f = new File("fPath&fName");

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

Diagram:

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

*imp

define 'RowSet'?

=>RowSet object will encapsulate the rows generated from

ResultSets or any other data sources.

=>RowSet is an interface from [Link] package and which is

extended from '[Link]' interface.

=>The following are the interfaces extended from RowSet:

(a)JDBCRowSet
(b)CachedRowSet

=>WebRowSet

(i)FilteredRowSet

(ii)JoinRowSet

Hierarchy of RowSet:

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

faq:

wt is the diff b/w

(i)JdbcRowSet

(ii)CachedRowSet

(i)JdbcRowSet:

=>JdbcRowSet will hold ResultSet and connection to DataBase

is active.
(ii)CachedRowSet:

=>cachedRowSet will hold ResultSet,but connection to DataBase

is Dis-Connected automatically.

--------------------------------------------------------------
Dt : 26/5/2023

Note:

=>WebRowSet is used to transfer the data from one layer to

another layer in Application architectures.

=>FilteredRowSet will hold the data retrieved based on

condition.

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

ResultSet

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

*imp

define RowSetFactory?

=>RowSetFactory is an interface from '[Link]' package

and which provide the following methods to create the

implementations of RowSet:

(a)createJdbcRowSet()

(b)createCachedRowSet()

(c)createWebRowSet()

(d)createFilteredRowSet()

(e)createJoinRowSet()

(a)createJdbcRowSet():
=>This method is used to create the implementation object of

'JdbcRowSet'.

Method Signature:

public abstract [Link] createJdbcRowSet()

throws [Link];

(b)createCachedRowSet():

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

'CachedRowSet'.

Method Signature:

public abstract [Link] createCachedRowSet()

throws [Link];

(c)createWebRowSet():

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

'WebRowSet'.

Method Signature:

public abstract [Link] createWebRowSet()

throws [Link];

(d)createFilteredRowSet():

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

'FilteredRowSet'.

Method Signature:

public abstract [Link]

createFilteredRowSet() throws [Link];

(e)createJoinRowSet():

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

'JoinRowSet'.

Method Signature:

public abstract [Link] createJoinRowSet()


throws [Link];

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

Note:

=>we use the following methods from

'[Link]' class to create the

implementation object of 'RowSetFactory' interface.

public static [Link] newFactory()

throws [Link];

public static [Link] newFactory

([Link], [Link])

throws [Link];

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

Ex-program : [Link]
package test;
import [Link].*;
import [Link].*;
public class DBCon14 {
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
try(s;){
try {
RowSetFactory rsf = [Link]();
[Link]("****Choice****");
[Link]("\[Link]"
+ "\n\[Link]");
[Link]("Enter the Choice:");
switch([Link]()) {
case 1:
JdbcRowSet jrs = [Link]();
[Link]("jdbc:oracle:thin:@localhost:1521:xe");
[Link]("system");
[Link]("manager");
[Link]("select * from BookDetails");
[Link]();
[Link]("====BookDetails=====");
while([Link]()) {
[Link]([Link](1)+
"\t"+[Link](2)+
"\t"+[Link](3)+
"\t"+[Link](4)+
"\t"+[Link](5));
}//end of loop
break;
case 2:
CachedRowSet crs = [Link]();
[Link]("jdbc:oracle:thin:@localhost:1521:xe");
[Link]("system");
[Link]("manager");
[Link]("select * from BookDetails");
[Link]();
[Link]("=====Display in reverse====");
[Link]();
while([Link]()) {
[Link]([Link](1)+
"\t"+[Link](2)+
"\t"+[Link](3)+
"\t"+[Link](4)+
"\t"+[Link](5));
}//end of loop
break;
default:
[Link]("Invalid Choice...");
}//end of switch
}catch(Exception e) {[Link]();}
}//End of try with resource
}
}

o/p:

****Choice****

[Link]

[Link]

Enter the Choice:

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

A101 AWS PQR 800.0 8

A107 HB Xyx 700.0 3

A104 CLang BS 500.0 7

B009 C++ B-Swamy 1800.0 18

A005 Spng ABC 900.0 9

A001 AdvJ PQR 1100.0 10

A111 CoreJ XYZ 1200.0 12

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

Note:

=>RowSet Objects are automatically Scrollable-Objects.


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

faq:

define Meta data?

=>The data which is holding information about other data is known

as "Meta data".

=>According to JDBC,Meta data means one object holding information

about other Object.

=>The following are some important meta data components in JDBC:

[Link]

[Link]

[Link]

[Link]

[Link]:

=>DatabaseMetaData is an interface from [Link] package and

which hold the information about Connection-Object.

syntax:

DatabaseMetaData dmd = [Link]();

[Link]:
=>ParameterMetaData is an interface from [Link] package and

which hold the information about PreparedStatement-Object.

syntax:

ParameterMetaData pmd = [Link]();

[Link]:

=>ResultSetMetaData is an interface from [Link] package and

which hold the information about ResultSet-Object.

syntax:

ResultSetMetaData rsmd = [Link]();

[Link]:

=>RowSetMetaData is an interface from [Link] package and

which hold the information about RowSet-Objects

syntax:

RowSetMetaData rsmd = (RowSetMetaData)[Link]();

==============================================================
Dt : 27/5/2023

Program : [Link]

package test;

import [Link].*;

import [Link].*;

public class DBCon15 {

public static void main(String[] args) {

Scanner s = new Scanner([Link]);

try(s;)

try

Connection con = [Link]

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

DatabaseMetaData dmd = [Link]();

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

[Link]("URL = "+[Link]());

[Link]("driver version = "+[Link]());

[Link]("driver name = "+[Link]());

PreparedStatement ps = [Link]

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

ParameterMetaData pmd = [Link]();

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

[Link]("parameter count = "+[Link]());

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

String id = [Link]();

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

String name = [Link]();

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


float price = Float .parseFloat([Link]());

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

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

[Link](1, id);

[Link](2, name);

[Link](3, price);

[Link](4, qty);

int k = [Link]();

if(k>0) {

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

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

PreparedStatement ps2 = [Link]

("select code,name,price from BookDetails");

ResultSet rs = [Link]();

while([Link]()) {

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

+[Link](2)+

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

}//end of loop

ResultSetMetaData rsmd = [Link]();

[Link]("Col Count = "+[Link]());

for(int i=1;i<=[Link]();i++) {

[Link]("Col-"+i+" : "

+[Link](i)+" - "

+[Link](i));

}//end of loop
[Link]();

catch(SQLIntegrityConstraintViolationException sicve)

[Link]("Product already available...");

catch(NumberFormatException nfe)

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

catch(Exception e)

[Link]();

}//end of try with resource

o/p:

*****DatabaseMetadata****

URL = jdbc:oracle:thin:@localhost:1521:xe

driver version = 11

driver name = Oracle JDBC driver

*****ParameterMetaData*****

parameter count = 4

****ResuleStMetaData****

A111 CoreJ 1200.0

A001 AdvJ 1100.0

A005 Spng 900.0

B009 C++ 1800.0


A104 CLang 500.0

A107 HB 700.0

A101 AWS 800.0

Col Count = 3

Col-1 : CODE - VARCHAR2

Col-2 : NAME - VARCHAR2

Col-3 : PRICE - NUMBER

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

faq:

define forName() method?

=>forName() method is from "[Link]" and which is used to

load the class at runtime or execution time.

syntax:

Class c = [Link]("Class_name");

(or)

[Link]("Class_name");

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

faq:

Hierarchy of JDBC-statements:
===========================================================

faq:

define "Wrapper" in JDBC?

=>Wrapper is an interface from [Link] package and which parent

interface of "Connection" and "Statement" interfaces.

=>Wrapper will support to make data or content available in the

form of objects.

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

faq:

define AutoCloseable?

=>AutoCloseable is an interface from from [Link] package and

which supports Auto-Closing operation part of try-with-resource

statement.

Rule : The class which is implemented from [Link]

interface must be used in try-with-resource satatement.

==============================================================
Dt : 29/5/2023

Summary of Objects created in CoreJava and JDBC:

CoreJava Objects:

[Link] defined Class Object

[Link]-Objects

[Link] Objects

[Link] Objects

[Link]<E> Objects

[Link]<K,V> Objects

[Link]<E> Objects

JDBC Objects:

[Link] Object

[Link] Object

[Link] Object

[Link] Object

[Link] Object

(i)Scrollable ResultSet Object

(ii)NonScrollable ResultSet Object

[Link] Object

(a)JdbcRowSet Object

(b)CachedRowSet Object

=>WebRowSet

(i)FilteredRowSet Object

(ii)JoinRowSet Object

[Link] Objects

(i)DatabaseMetaData Object

(ii)ParameterMetaData Object

(iii)ResultSetMetaData Object

(iv)RowSetMetaData Object

============================================================
*imp

Servlet Programming:

faq:

define Servlet?

=>The program which is executing in Server environment and which

interacts with user or client through WebBrowser is known as

Servlet Program or Server Program

Diagram:

faq:

define Server?

=>Server means service provider,which means accepting the request

from the user and providing the response.

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

faq:

define Application?

=>The set-of-programs collected together to perform defined action

is known as Application.

Types of Applications:

=>Applications are categorized into the following:

[Link] Applications

[Link] Applications

[Link] Applications

[Link] Applications
[Link] Applications:

=>The applications which are installed in one computer and performs

actions in the same computer are known as StandAlone Applications

or DeskTop Applications or Windows Applications.

=>Based on User interaction StandAlone applications are categorized

into two types:

(i)CUI Applications

(ii)GUI Applications

(i)CUI Applications:

=>The applications in which the user interacts through Console

are known as CUI Applications.

(CUI means Console User Interface)

(ii)GUI Applications:

=>The applications in which the user interacts through GUI

components are known as GUI Applications.

(GUI means Graphical User Interface)

=>We use the following to design GUI Components:

(a)AWT - Abstract Window Toolkit

(b)Swing

Diagram:
Note:

=>In CUI and GUI Applications,

Starting point : main()

Execution environmnet : JVM

Execuion Command : java

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

*imp

[Link] Applications:

=>The applications which are execued in Web Environment or

Internet Environmnet are known as WebApplications or Internet

Applications.

=>we use the following three technologies to construct Web

Applications:

(i)JDBC

(ii)Servlet

(iii)JSP
Note:

=>In WebApplications,

Starting point : init()

Execution Environment : WebContainer

Execution URL : url-pattern

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

*imp

[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

Distributed Applications.

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

*imp

[Link] Applications:

=>The applications which are executing in mobile environment are

known as Mobile Applications.

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

Dt : 30/5/2023

Note:

=>Java is both PlatForm and Language.

=>Java is PlatForm because Java having its own Execution

environmnet.

=>Java is Language becuase Java having its own Syntax to contruct

program.

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

=>According to Vendor(Oracle Corporation) java PlatForms are

categorized into three types:

[Link] SE
[Link] EE

[Link] ME

[Link] SE:

=>Java SE means Java to Standard Edition,which provides PlatForm

to develop StandAlone applications.

=>Standard Edition means CoreJava+JDBC

*imp

[Link] EE:

=>Java EE means Java Enterprise Edition,which provide PlatForm

to develop Server based applications.

=>Enterprise Edition will support WebApplications and Enterprise

Applications.

[Link] ME:

=>Java ME means Java Micro Edition,which provide PlatForm to

develop Mobile Applications,Machine Applications and Embeded

Applications

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

faq:

define WebContainer?

=>The Component of Server where WebApplications are deployed for

execution is known as WebContainer,which means WebContainer is an

execution environment for WebApplications.

=>This WebContainer internally categorized into two SubContainers:

(i)Servlet Container

(ii)JSP Container

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

*imp

Types of Servers:

=>Servers are categorized into two types:

(a)WebServers

(b)Application Servers

(a)WebServer:

=>Web Server contains only Web container .

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

html pages.

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

compared to application server.

=>Web Server provides the runtime environment for web

applications.

=>Web Server supports HTTP Protocol

=>Apache Web Server.(Tomcat)

(b)Application Server:

=>Application Server contains both Web Container and EJB

Container.(EJB - Enterprise Java Bean)


=>Applcation server is relevant in case of dynamic contents

like bank websites.

=>Application server utilizes more resources

=>Application server provides the runtime environment for

enterprise applications.

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

(RPC - Remote Procedure call)

(RMI - Remote Method Invocation)

=>Weblogic, JBoss.

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

Dt : 2/6/2023

*imp

Installing Tomcat Server:

step1 : Download Tomcat9.x WebServer

webserver - Tomcat 9.x

(Compatable with JDK1.8 and Above )

vendor - Apache org

default port no - 8080

download - [Link](Open source)

Note:

=>WebContainer internally has two SubContainers

(i)Servlet container

(ii)JSP Container

Servlet container : Catelina

Jsp Container : Jasper

Link : [Link]

[Link]
[Link]

step-2 : Install the Tomcat Server

while installation process,

Select the type of Install : Full

(click Next)

Server shutdown port : 8089

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

User Name : Venkatesh

Password : nit

(click Next)

step-3 : start the Tomcat Server

=>click "startup" or "Tomcat9w" from "bin" folder of Tomcat to

start the server

C:\Tomcat 9.0\bin

step-4 : Open WebBrower and use the following server-url to

connect Tomcat server

[Link]

step-5 : stop the Tomcat Server

=>click "shutdown" or "Tomcat9w" from "bin" folder of Tomcat to

stop the server

C:\Tomcat 9.0\bin

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

*imp

Servlet API:

=>"[Link]" package is known as Servlet-API and which


provide "classes and Interfaces" used in servlet-application

development

=>"[Link]" interface is root of Servlet-API

=>The following are some important methods of "Servlet" interface:

[Link]()

[Link]()

[Link]()

[Link]()

[Link]()

[Link]():

=>The process of making the programming components ready for

service is known as initialization process,this initialization

process can be performed using init()-method

Method Signature:

public abstract void init([Link])

throws [Link];

[Link]():

=>The process of accepting the request and providing the response

is known as service and which can be performed using service()

method.

=>service() method will hold major servlet-logic.

Method Signature:

public abstract void service([Link],

[Link]) throws

[Link], [Link];

[Link]():

=>The process of closing the opened resources part of service

is known as destroying process and which can be performed using

destroy() method.
Method Signature:

public abstract void destroy();

[Link]():

=>getServletConfig() method is used to get servlet-configuration

details.

Method Signature:

public abstract [Link] getServletConfig();

[Link]():

=>getServletInfo() method is used to get servlet information.

Method Signature:

public abstract [Link] getServletInfo();

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

Dt : 3/6/2023

Note:

=>In the process of constructing Servlet-programs,the user defined

classes must be implemented from "[Link]" interface.

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

*imp

Construct Servlet Application(WebApp) to read data from HTML form

using IDE Eclipse:

step-1 : Open IDE Eclispe,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 "Next"->name the project and click "Finish"

step-3 : Add "[Link]" file to Dynamic Web Project

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

select "classpath" and click "Add External Jars"->Browse and select

"[Link]" from "lib" folder of Tomcat->Open->Apply->


Apply and Close

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

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

slect Tomcat Server and click "Next"->Browse "Tomcat Installation

directory"->Click "Finish".

step-5 : Create Package(Java Resources->src/main/java)

step-6 : Create Servlet-class(Servlet-program) in package

Program : [Link]

package test;

import [Link].*;

import [Link].*;

import [Link].*;

@WebServlet("/first")

public class FirstServlet implements Servlet{

public void init(ServletConfig sc)throws ServletException{

//NoCode

public void service(ServletRequest req,ServletResponse res)

throws ServletException,IOException{

PrintWriter pw = [Link]();

[Link]("text/html");

String name = [Link]("uname");

String mailId = [Link]("mid");

[Link]("****Display from Servlet****");

[Link]("<br>UserName : "+name);

[Link]("<br>MailID : "+mailId);

public void destroy() {


//NoCode

public ServletConfig getServletConfig() {

return [Link]();//Demo Code

public String getServletInfo() {

return "FirstServlet reading data from HTMl";//Demo code

step-7 : Create HTML file in webapp

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

"Finish"

File Name : [Link]


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

step-8 : Construct [Link] file in "WEB-INF"

RightClick on WEB-INF->new->Other->XML->select XML file and click

"Next"->name the file and click "Finish"

File Name : [Link]


<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>

step-9 : Execute the Application

RightClick on Project->Run AS->Run On Server->select the Server

and Click "Finish"

[Link]

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

Dt : 5/6/2023

Execution flow of above application:

[Link]

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

*imp

ServletContext:

=>ServletContext is an interface from [Link] package and

which is instantiated automatically when WebApp is deployed onto

Server.
=>This ServletContext Object is loaded with server information.

*imp

ServletConfig:

=>ServletConfig is an interface from [Link] package and

which is instantiated automatically when servlet-program loaded for

execution.

=>This ServletConfig Object will hold the name of Servlet.

*imp

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 form

*imp

ServletResponse:

=>ServletResponse is an interface from [Link] package and

which is instantiated automatically while service() method

execution.

=>This ServletResponse object will hold the data which we are

sending as response.

faq:

define getWriter() method?

=>getWriter() method is from "ServletResponse" and which is used

to create object for "[Link]" class.

syntax:

PrintWriter pw = [Link]();

=>This PrintWriter object will hold the reference of


ServletResponse,which means the two objects are interlinked.

faq:

define setContentType() method?

=>setContentType() method is from "ServletResponse" and specify

the type of data which we are going to send through response.

syntax:

[Link]("text/htmm");

faq:

define getParameter() method?

=>getParameter() method is from "ServletRequest" and which is

used to get the para-value from ServletRequest object.

syntax:

String var = [Link]("para_name");

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

Assignment-1:

Construct Servlet-Applications to read and display Product Details.

(code,name,price,qty)

Assignment-2:

Construct Servlet-Application to read and display Book Details.

(code,name,author,price,qty)

Note:

=>Use HTML and CSS to design input forms

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

Dt : 6/6/2023

Assignment-1:

Construct Servlet-Applications to read and display Product Details.

(code,name,price,qty)
Layout:

[Link]

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="dis">
<table>
<tr>
<td>ProdCode</td>
<td><input type="text"
name="code"><br></td>
</tr>
<tr>
<td>ProdName</td>
<td><input type="text"
name="name"><br></td>
</tr>
<tr>
<td>ProdPrice</td>
<td><input type="text"
name="price"><br></td>
</tr>
<tr>
<td>ProdQty</td>
<td><input type="text"
name="qty"><br></td>
</tr>
<tr>
<td><input type="submit"
value="Display"></td>
<td></td>
</tr>
</table>
</form>
</body>
</html>
[Link]

package test;

import [Link].*;

import [Link].*;

import [Link].*;

@WebServlet("/dis")

public class DisplayServlet implements Servlet{

public void init(ServletConfig sc)throws ServletException{

//NoCode

public void service(ServletRequest req,ServletResponse res)

throws ServletException,IOException{

PrintWriter pw = [Link]();

[Link]("text/html");

String cd = [Link]("code");

String nm = [Link]("name");

float pr = [Link]([Link]("price"));

int qt = [Link]([Link]("qty"));

[Link]("====ProductDeatils====");
[Link]("<br>Code:"+cd);

[Link]("<br>Name:"+nm);

[Link]("<br>Price:"+pr);

[Link]("<br>Qty:"+qt);

public void destroy() {

//NoCode

public ServletConfig getServletConfig() {

return [Link]();

public String getServletInfo() {

return "DisplayServlet";

[Link]

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


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

*imp

Hierarchy of Servlet-API:
================================================================

Note:

=>when we construct servlet-program using "Servlet" interface,

then we have to construct body for all 5-methods of "Servlet"

interface.

=>when we construct servlet-program using "GenericServlet"

then we have to construct body for service() method and init() and

destroy() are optional methods.

=>If the servlet-program constructed using "GenericServlet" then

the Servlet-program will accept request from any type of protocol.

=>when we Construct servlet-program using "HttpServlet" then

the methods are optional methods

initialization - init()

get request - doGet()

post request - doPost()

any request - service()


destroying - destroy()

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

*imp

RequestDispatcher in Servlet programming:

=>"RequestDispatcher" is an interface from [Link] package

and which is used to perform servlet communications.

=>Servlet communications can be the following:

(i)servlet to servlet

(ii)servlet to HTML

(iii)servlet to JSP

=>RequestDispatcher will provide the following methods to perform

communications:

(a)forward()

(b)include()

(a)forward():

=>forward() method will perform forward communication process,

which means ServletProgram1 will take the request and forwards the

request to ServletProgram2,in this process ServletProgram2 will

provide the response.

(This ServletProgram2 can be replaced with HTML/JSP)

Method signature of forward():

public abstract void forward([Link],

[Link])

throws [Link], [Link];

Diagram:
(b)include():

=>include() method will perform include communication process,

which means ServletProgram1 will take the request and provide the

response,but the response is included with the response of

ServletProgram2.

(This ServletProgram2 can be replaced with HTML/JSP)

Method Signature of include():

public abstract void include([Link],

[Link])

throws [Link], [Link];

Diagram:
========================================================
Dt : 7/6/2023

Note:

=>we use getRequestDispatcher() method from "ServletRequest" to

create implementation object for "RequestDispatcher" interface.

syntax:

RequestDispatcher rd =

[Link]("url-patter/HTML/JSP");

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

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 Value1:<input type="text" name="v1"><br>
Enter the Value2:<input type="text" name="v2"><br>
<input type="submit" value="Add" name="s1">
<input type="submit" value="Sub" name="s1">
</form>
</body>
</html>

[Link]

package test;

import [Link].*;

import [Link].*;

import [Link].*;

@SuppressWarnings("serial")

@WebServlet("/choice")

public class ChoiceServlet extends GenericServlet{

public void service(ServletRequest req,ServletResponse res)

throws ServletException,IOException{

String s1 = [Link]("s1");

if([Link]("Add")) {

RequestDispatcher rd =

[Link]("ad");

[Link](req, res);

}else {

RequestDispatcher rd =

[Link]("sb");

[Link](req, res);

[Link]

package test;

import [Link].*;
import [Link].*;

import [Link].*;

@SuppressWarnings("serial")

@WebServlet("/ad")

public class AdditionServlet extends GenericServlet{

public void service(ServletRequest req,ServletResponse res)

throws ServletException,IOException{

PrintWriter pw = [Link]();

[Link]("text/html");

try

int v1 = [Link]([Link]("v1"));

int v2 = [Link]([Link]("v2"));

int v3 = v1+v2;

[Link]("Sum : "+v3+"<br>");

catch(Exception e)

[Link]("Enter only Integer values...<br>");

RequestDispatcher rd =

[Link]("[Link]");

[Link](req, res);

[Link]

package test;

import [Link].*;

import [Link].*;

import [Link].*;
@SuppressWarnings("serial")

@WebServlet("/sb")

public class SubtractionServlet extends GenericServlet{

public void service(ServletRequest req,ServletResponse res)

throws ServletException,IOException{

PrintWriter pw = [Link]();

[Link]("text/html");

try

int v1 = [Link]([Link]("v1"));

int v2 = [Link]([Link]("v2"));

int v3 = v1-v2;

[Link]("Sub : "+v3+"<br>");

catch(Exception e)

[Link]("Enter only Integer values...<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>

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

Note:
=>Only one "ServletContext" object is created for WebApplication,

but every ServletProgram in WebApp will have its own ServletConfig

object,ServletRequest Object and ServletResponse object.

=>PrintWriter object is an optional object and which is created

when we want to provide response.

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

Assignment:

Update above application by adding the folling options:

=>Mul

=>Div

=>ModDiv

=>Greater

=>Smaller

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

Dt : 8/6/2023

*imp

define Bean Classes?

=>The classes which are declared with the following rules are

known as Bean Classes.

Rule-1 : The classes 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 classes must be declared with "Getter" and "Setter"

methods.

-------------------------------------------------------
Note:

=>These Bean classes will generate Bean-Objects

=>These Bean-Objects will hold data which is going onto DB product

and which is also used to hold data coming from DB 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 to the Objects are

known as Setter-methods.

Coding rule:

=>Every variable in class will have its own Setter and Getter

methods.

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

faq:

define DAO Layer?

=>DAO stands for "Data Access Object" and which is separate layer

in MVC(Model View Controller) to hold Persistent logics or DB

ralated logics.

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

Note:

=>In the process of establishing communication b/w Servlet-program

and DB Product,the "DB Jar file" must be copied into "lib" folder

of WEB-INF

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

Ex-Application:

Construct Servlet Application to demonstrate Employee related

Operations.

DB Table : Employee52(id,name,desg,bsal,totsal)

Primary Key : id

Create table Employee52(id varchar2(10),name varchar2(15),

desg varchar2(10),bsal number(10),totsal number(10,2),

primary key(id));
Layout:

[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="[Link]">AddEmployee</a>
<a href="view">ViewAllEmployees</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">
Employee Id:<input type="text" name="id"><br>
Employee Name:<input type="text" name="name"><br>
Employee Desg:<input type="text" name="desg"><br>
Employee BSal:<input type="text" name="bsal"><br>
<input type="submit" value="AddEmployee">
</form>
</body>
</html>

[Link]
package test;
import [Link].*;
@SuppressWarnings("serial")
public class EmployeeBean implements Serializable{
private String id,name,desg;
private int bSal;
private float totSal;
public EmployeeBean() {}
public String getId() {
return id;
}
public void setId(String id) {
[Link] = id;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public String getDesg() {
return desg;
}
public void setDesg(String desg) {
[Link] = desg;
}
public int getbSal() {
return bSal;
}
public void setbSal(int bSal) {
[Link] = bSal;
}
public float getTotSal() {
return totSal;
}
public void setTotSal(float totSal) {
[Link] = totSal;
}

[Link]
package test;
import [Link].*;
public class DBConnection {
private static Connection con = null;
private DBConnection() {}
static
{
try {
[Link]("[Link]");
con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
}catch(Exception e) {[Link]();}
}//end of block
public static Connection getCon() {
return con;
}
}

[Link]
package test;
import [Link].*;
public class InsertEmployeeDAO {
public int k=0;
public int insert(EmployeeBean eb) {
try {
Connection con = [Link]();
PreparedStatement ps = [Link]
("insert into Employee52
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].*;

@SuppressWarnings("serial")

@WebServlet("/add")

public class AddEmployeeServlet extends GenericServlet{

public void service(ServletRequest req,ServletResponse res)

throws ServletException,IOException{

PrintWriter pw = [Link]();

[Link]("text/html");

EmployeeBean eb = new EmployeeBean();

[Link]([Link]("id"));

[Link]([Link]("name"));
[Link]([Link]("desg"));

int bSal = [Link]([Link]("bsal"));

[Link](bSal);

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

[Link](totSal);

int k = new InsertEmployeeDAO().insert(eb);

if(k>0) {

[Link]("Employee Added Successfully...<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>

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

Dt : 9/6/2023

[Link]

package test;

import [Link].*;

import [Link].*;

public class ViewEmployeesDAO {

public ArrayList<EmployeeBean> al =

new ArrayList<EmployeeBean>();

public ArrayList<EmployeeBean> retrieve()

{
try

Connection con = [Link]();

PreparedStatement ps = [Link]

("select * from Employee52");

ResultSet rs = [Link]();

while([Link]())

EmployeeBean eb = new EmployeeBean();

[Link]([Link](1));

[Link]([Link](2));

[Link]([Link](3));

[Link]([Link](4));

[Link]([Link](5));

[Link](eb);//Add bean object to ArrayList

}//end of loop

catch(Exception e)

[Link]();

return al;

[Link]

package test;

import [Link].*;

import [Link].*;

import [Link].*;

import [Link].*;
@SuppressWarnings("serial")

@WebServlet("/view")

public class ViewEmployeesServlet extends GenericServlet{

public void service(ServletRequest req,ServletResponse res)

throws ServletException,IOException{

PrintWriter pw = [Link]();

[Link]("text/html");

ArrayList<EmployeeBean> al =

new ViewEmployeesDAO().retrieve();

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

[Link]("No employees available...");

RequestDispatcher rd =

[Link]("[Link]");

[Link](req, res);

}else {

[Link]((k)->

EmployeeBean eb = (EmployeeBean)k;

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

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

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

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

[Link]()+

"<a href='edit'>Edit</a><a
href='delete'>Delete</a><br>");

});

[Link]("<a href='[Link]'>Back</a>");

}//end of else

}
Layout:

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

Assignment-1:

Construct Servlet Application to perform operations on Products.

=>AddProduct

=>ViewAllProducts

DB Table : Product52

Assignment-2 :

Construct Servlet Application to perform operations on BookDetails.

=>AddBookDetails

=>ViewAllBookDetails

DB Table : BookDetails52

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

*imp

ServletContext:

=>ServletContext is an interface from [Link] package and

which is instantiated automatically when WebApp is deployed into

Server.
=>This ServletContext object is loaded with Server-information.

=>we use getServletContext() method to access the reference of

ServletContext object.

=>This getServletContext() method is available from GenericServlet,

ServletRequest,ServletConfig and HttpSession.

syntax:

ServletContext sct = [Link]();

=>we use <context-param> tag in [Link] to initialize parameters

in ServletContext object.

syntax:

<web-app>

<context-param>

<param-name>name</param-name>

<param-value>name</param-value>

</context-param>

</web-app>

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

Dt : 10/6/2023

Ex-Application:(Demonstrating ServletContext)

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].*;

import [Link].*;

@SuppressWarnings("serial")

@WebServlet("/dis")

public class DisplayServlet extends GenericServlet{

public void service(ServletRequest req,ServletResponse res)

throws ServletException,IOException{

PrintWriter pw = [Link]();
[Link]("text/html");

String uName = [Link]("uname");

[Link]("Welcome : "+uName);

ServletContext sct = [Link]();

[Link]("<br>****ServletContext****");

[Link]("<br>ServerInfo:"+[Link]());

Enumeration<String> e = [Link]();

while([Link]())

String str = [Link]();

[Link]("<br>"+str+":"+[Link](str));

}//end of loop

[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<context-param>
<param-name>x</param-name>
<param-value>1000</param-value>
</context-param>
<context-param>
<param-name>y</param-name>
<param-value>2000</param-value>
</context-param>
<context-param>
<param-name>z</param-name>
<param-value>3000</param-value>
</context-param>

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

o/p:

Welcome : Alex

****ServletContext****

ServerInfo:Apache Tomcat/9.0.67
x:1000

y:2000

z:3000

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

define getInitParameter() method?

=>getInitParameter() method is used to get initialized para-value

from ServletContext and ServletConfig Objects.

syntax:

String val = [Link]("para_name");

define getInitParameterNames() method?

=>This getInitParameterNames() method is used to get all parameter

names from ServletContext and ServletConfig Objects.

syntax:

Enumeration<String> e = [Link]();

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

Note:

=>Only one ServletContext object is created for WebApplication

and the content available in ServletContext object can be used by

all the Servlet-programs of WebApp.

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

Dt : 13/6/2023

*imp

"attribute" in ServletProgramming:

=>"attribute" is a variable in Servlet programming which can be

added to "ServletContext" object,"ServletRequest" object and

"HttpSession" object.

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

(a)setAttribute()

(b)getAttribute()
(c)getAttributeNames()

(d)removeAttribute()

(a)setAttribute():

=>setAttribute() method is used to add attribute to Objects.

Method Signature:

public abstract void setAttribute

([Link],[Link]);

(b)getAttribute():

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

Method Signature:

public abstract [Link] getAttribute([Link]);

(c)getAttributeNames():

=>getAttributeNames() method is used to get all attributes names

from the objects.

Method Signature:

public abstract [Link]<[Link]>

getAttributeNames();

(d)removeAttribute():

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

Objects.

Method Signature:

public abstract void removeAttribute([Link]);

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

*imp

Scope of "attribues":

(i)"attribute" in ServletContext Object will have Application

Scope,which means all the Servlet-programs of WebApp can use

"attributes".
(ii)"attributes" in ServletRequest Object will have Request Scope

which means the "attributes" in SservletRequest can also be

used by next servlet-program in forward-communication process

(iii)"attributes" in HttpSession object will have Session Scope

which means "attributes" in HttpSession object is available

from user-login to user-logout

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

faq:

define request?

=>The query which is generated by the client to Server-program

or Servlet-program is known as request.

Types of requests:

=>Requests are categorized into two types:

[Link] request

[Link] request

[Link] request:

=>The request which is generated to send the data to server is

known as POST request.

=>Through POST request we can send any type of data,which means

we can send all file formats like Text,Audio,Video,Image and

Animation

=>Through POST request we can send UnLimited data.

=>The data in POST request is secure,because the data is

encapsulated to body of HTTP protocol.

=>use the following syntax to generate POST request:

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

...

</form>

=>we use doPost() method from "HttpServlet" to accept POST


request

Method Signature:

protected void doPost([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 limited data,which means 2kb or

4kb or 8kb

=>The data in GET request is not secure,because it is displayed

in address-bar of WebBrowser

=>We use the following four syntaxes to generate GET request:

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

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

...

</form>

(ii)Using <form> tag without "method" attribute.

<form action="url">

...

</form>

(iii)Using Hyper Links(href)

<a href="view">ViewAllEmployee</a>

(iV)Using servlet-url-pattern in AddressBar

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

protected void doGet([Link],

[Link])throws
[Link],[Link];

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

*imp

define Session?

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

define Session Tracking?

=>The process of tracking the state of user in session,is known

as Session Tracking.

=>The following are some important Session Tracking techniques

in Servlet Programming:

[Link]

[Link]

[Link] re-write

[Link] Form fields

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

Dt : 14/6/2023

[Link]:

=>The small piece of information which is persisted b/w multiple

client requests is known as cookie.

=>cookie generated by server-program,but stored in WebBrowser to

track the user.

Types of Cookies:

=>Cookies are categorized into two types:

(i)Persistent Cookie

(ii)NonPersistent Cookie

(i)Persistent Cookie:

=>The cookie which is stored and available in WebBrowser until

user-logout,is known as Persistent Cookie.


(ii)NonPersistent Cookie:

=>The cookie which becomes invalidated automatically when the

WebBrowser is closed is known as NonPersistent Cookie

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

Note:

=>To construct cookie in Session Tracking process we use

"[Link]" class.

=>The following are some important methods of Cookie:

public [Link]

([Link], [Link]);

public void setMaxAge(int);

public int getMaxAge();

public void setValue([Link]);

public [Link] getValue();

public [Link] getName();

Hierarchy of Cookie:

=============================================================
Ex-Application:

User Registration and Login process using Cookie Session Tracking

process.

DBTable : UserReg52(uname,pword,fname,lname,addr,mid,phno)

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

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

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

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;
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 DBConnection {
private static Connection con = null;
private DBConnection() {}
static
{
try {
[Link]("[Link]");
con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
}catch(Exception e) {[Link]();}
}//end of block
public static Connection getCon() {
return con;
}
}

[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 UserReg52
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 RegisterServlet extends HttpServlet{

protected void doPost(HttpServletRequest req,

HttpServletResponse res)throws ServletException,

IOException{

PrintWriter pw = [Link]();

[Link]("text/html");

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]("User registered Successfully...<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>

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

[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="view">ViewProfile</a>
<a href="logout">Logout</a>
</body>
</html>

[Link]

package test;

import [Link].*;

import [Link].*;

public class LoginDAO {

public UserBean ub = null;

public UserBean login(HttpServletRequest req) {

try {
Connection con = [Link]();

PreparedStatement ps = [Link]

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

[Link](1, [Link]("uname"));

[Link](2, [Link]("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{

protected void doPost(HttpServletRequest req,


HttpServletResponse res)throws ServletException,

IOException{

PrintWriter pw = [Link]();

[Link]("text/html");

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

if(ub==null) {

[Link]("Invalid Login process...<br>");

RequestDispatcher rd =

[Link]("[Link]");

[Link](req, res);

}else {

ServletContext sct = [Link]();

[Link]("ub", ub);

Cookie ck = new Cookie("fname",[Link]());

[Link](ck);

//Serialization process

[Link]("Welcome User : "+[Link]()+"<br>");

RequestDispatcher rd =

[Link]("[Link]");

[Link](req, res);

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

Dt : 15/6/2023

[Link]

package test;

import [Link].*;

import [Link].*;

import [Link].*;
import [Link].*;

@SuppressWarnings("serial")

@WebServlet("/view")

public class ViewProfileServlet extends HttpServlet{

protected void doGet(HttpServletRequest req,

HttpServletResponse res)throws ServletException,

IOException{

PrintWriter pw = [Link]();

[Link]("text/html");

Cookie c[] = [Link]();

//Internally perform DeSerialization

if(c==null) {

[Link]("Session expired..<br>");

RequestDispatcher rd =

[Link]("[Link]");

[Link](req, res);

}else {

String fName = c[0].getValue();

[Link]("Page belongs to User : "+fName+"<br>");

ServletContext sct = [Link]();

UserBean ub = (UserBean)[Link]("ub");

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

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

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

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

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

+"<a href='edit'>EditProfile</a>"

+"&nbsp&nbsp&nbsp"

+"<a href='logout'>Logout</a>");
}

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

PrintWriter pw = [Link]();

[Link]("text/html");

Cookie c[] = [Link]();

if(c==null) {

[Link]("Session Expired...<br>");

}else {

ServletContext sct = [Link]();

[Link]("ub");

c[0].setMaxAge(0);

[Link](c[0]);

[Link]("User logged out Successfully..<br>");

}//end of else

RequestDispatcher rd =

[Link]("[Link]");

[Link](req, res);
}

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

Dt : 16/6/2023

[Link]

package test;

import [Link].*;

import [Link].*;

import [Link].*;

import [Link].*;

@SuppressWarnings("serial")

@WebServlet("/edit")

public class EditProfileServlet extends HttpServlet{

protected void doGet(HttpServletRequest req,

HttpServletResponse res)throws ServletException,


IOException{

PrintWriter pw = [Link]();

[Link]("text/html");

Cookie c[] = [Link]();

if(c==null) {

[Link]("Session Expired...<br>");

RequestDispatcher rd =

[Link]("[Link]");

[Link](req, res);

}else {

ServletContext sct = [Link]();

UserBean ub = (UserBean)[Link]("ub");

[Link]("<form action='update' method='post'>");

[Link]("Address:<input type='text' name='addr'


value='"+[Link]()+"'><br>");

[Link]("MailId:<input type='text' name='mid'


value='"+[Link]()+"'><br>");

[Link]("PhoneNo:<input type='text' name='phno'


value='"+[Link]()+"'><br>");

[Link]("<input type='submit' value='Update'>");

[Link]("</form>");

[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 UserReg52 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{

protected void doPost(HttpServletRequest req,

HttpServletResponse res)throws ServletException,

IOException{

PrintWriter pw = [Link]();

[Link]("text/html");

Cookie c[] = [Link]();

if(c==null) {

[Link]("Session expired...<br>");

RequestDispatcher rd =

[Link]("[Link]");

[Link](req, res);

}else {

String fName = c[0].getValue();

ServletContext sct = [Link]();

UserBean ub = (UserBean)[Link]("ub");

[Link]([Link]("addr"));
[Link]([Link]("mid"));

[Link]([Link]([Link]("phno")));

int k = new UpdateProfileDAO().update(ub);

[Link]("page belongs to User : "+fName+"<br>");

if(k>0) {

[Link]("Profile Updated Successfully...<br>");

RequestDispatcher rd =

[Link]("[Link]");

[Link](req, res);

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

Summary:
=======================================================
Dt : 17/6/2023

*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 boolean isNew();

public abstract [Link]

getServletContext();

public abstract [Link]

getSessionContext();

----------------------------------------------------
=>we use getSession() method from "HttpServletRequest"

to create implementation object for "HttpSession" interface.

Method Signatures of getSession():

public abstract [Link] getSession();

public abstract [Link]

getSession(boolean);

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

Ex-Application:(Demonstrating HttpSession in Session Tracking)

DBTables :

Table : UserTab52

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

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

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

Table : AdminTab52

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

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

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

Layout:
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="[Link]">UserLogin</a>
<a href="[Link]">AdminLogin</a>
</body>
</html>

[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="admin" 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]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="user" 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>
<a href="[Link]">AddProduct</a>
<a href="view">ViewAllProducts</a>
<a href="logout">Logout</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].*;
public class DBConnection {
private static Connection con = null;
private DBConnection() {}
static
{
try {
[Link]("[Link]");
con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
}catch(Exception e) {[Link]();}
}//end of block
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].*;
@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]

package test;

import [Link].*;

import [Link].*;
public class AdminLoginDAO {

public AdminBean ab = null;

public AdminBean login(HttpServletRequest req) {

try {

Connection con = [Link]();

PreparedStatement ps = [Link]

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

[Link](1, [Link]("uname"));

[Link](2, [Link]("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("/admin")

public class AdminLoginServlet extends HttpServlet{

@Override

protected void doPost(HttpServletRequest req,

HttpServletResponse res)throws ServletException,

IOException{

PrintWriter pw = [Link]();

[Link]("text/html");

AdminBean ab = new AdminLoginDAO().login(req);

if(ab==null) {

[Link]("Invalid Login process...<br>");

RequestDispatcher rd =

[Link]("[Link]");

[Link](req, res);

}else {

HttpSession hs = [Link]();//Session created

[Link]("ab", ab);

[Link]("Welcome Admin : "+[Link]()+"<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>
[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{

PrintWriter pw = [Link]();

[Link]("text/html");

HttpSession hs = [Link](false);

if(hs==null) {

[Link]("Session expired...<br>");

}else {

[Link]("ab");

[Link]();//session destroyed

[Link]("logged out Successfully...<br>");

RequestDispatcher rd =

[Link]("[Link]");

[Link](req, res);

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

Dt : 22/6/2023
[Link]
package test;
import [Link].*;
public class AddProductDAO {
public int k=0;
public int add(ProductBean pb) {
try {
Connection con = [Link]();
PreparedStatement ps = [Link]
("insert into Product52
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{

PrintWriter pw = [Link]();

[Link]("text/html");

HttpSession hs = [Link](false);

if(hs==null) {

[Link]("Session expired...<br>");

RequestDispatcher rd =

[Link]("[Link]");

[Link](req, res);

}else {

AdminBean ab = (AdminBean)[Link]("ab");

ProductBean pb = new ProductBean();

[Link]([Link]("code"));

[Link]([Link]("name"));

[Link]([Link]([Link]("price")));

[Link]([Link]([Link]("qty")));

int k = new AddProductDAO().add(pb);

[Link]("Page belongs to "+[Link]()+"<br>");

RequestDispatcher rd =

[Link]("[Link]");

[Link](req, res);

if(k>0) {

[Link]("<br>Product added Successfully...");

}
[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 Product52");

ResultSet rs = [Link]();

while([Link]()) {

ProductBean pb = new ProductBean();

[Link]([Link](1));

[Link]([Link](2));

[Link]([Link](3));

[Link]([Link](4));

[Link](pb);//Adding ProductBean 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{

PrintWriter pw = [Link]();

[Link]("text/html");

HttpSession hs = [Link](false);

if(hs==null) {

[Link]("Session expired...<br>");

RequestDispatcher rd =

[Link]("[Link]");

[Link](req, res);

}else {

AdminBean ab = (AdminBean)[Link]("ab");

[Link]("Page belongs to "+[Link]()+"<br>");

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

[Link]("al", al);

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

[Link]("No product Available...<br>");

}else {

[Link]((k)->

ProductBean pb = (ProductBean)k;

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

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

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

+"<a
href='edit?pcode="+[Link]()+"'>Edit</a>"

+"&nbsp&nbsp&nbsp"

+"<a
href='delete?pcode="+[Link]()+"'>Delete</a><br>");

});

[Link]("<a href='[Link]'>Back</a>"

+"&nbsp&nbsp&nbsp"

+"<a href='logout'>Logout</a>");

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

Dt : 23/6/2023

[Link]

package test;

import [Link].*;

import [Link].*;

import [Link].*;

import [Link].*;

import [Link].*;

@SuppressWarnings("serial")

@WebServlet("/edit")

public class EditProductServlet extends HttpServlet{

@SuppressWarnings("unchecked")

@Override

protected void doGet(HttpServletRequest req,

HttpServletResponse res)throws ServletException,

IOException{
PrintWriter pw = [Link]();

[Link]("text/html");

HttpSession hs = [Link](false);

if(hs==null) {

[Link]("Session Expired...<br>");

RequestDispatcher rd =

[Link]("[Link]");

[Link](req, res);

}else {

String code = [Link]("pcode");

ArrayList<ProductBean> al =

(ArrayList<ProductBean>)[Link]("al");

[Link]((k)->

if([Link]([Link]())) {

[Link]("<form action='update' method='POST'>");

[Link]("<input type='hidden' name='pcode'


value='"+code+"'>");

[Link]("ProdPrice:<input type='text' name='pprice'


value='"+[Link]()+"'><br>");

[Link]("ProdQty:<input type='text' name='pqty'


value='"+[Link]()+"'><br>");

[Link]("<input type='submit' value='UpdateProduct'>");

[Link]("</form>");

});

[Link]

package test;

import [Link].*;
import [Link].*;

import [Link].*;

import [Link].*;

import [Link].*;

@SuppressWarnings("serial")

@WebServlet("/update")

public class UpdateProductServlet extends HttpServlet{

@SuppressWarnings("unchecked")

protected void doPost(HttpServletRequest req,

HttpServletResponse res)throws ServletException,

IOException{

PrintWriter pw = [Link]();

[Link]("text/html");

HttpSession hs = [Link](false);

if(hs==null) {

[Link]("Session Expired...<br>");

RequestDispatcher rd =

[Link]("[Link]");

[Link](req, res);

}else {

AdminBean ab = (AdminBean)[Link]("ab");

[Link]("Page belongs to "+[Link]()+"<br>");

ArrayList<ProductBean> al =

(ArrayList<ProductBean>)[Link]("al");

String code = [Link]("pcode");

[Link]((k)->{

if([Link]([Link]())) {

[Link]([Link]([Link]("pprice")));

[Link]([Link]([Link]("pqty")));

int z = new UpdateProductDAO().update(k);


if(z>0) {

[Link]("Product Updated Successfully..<br>");

});

RequestDispatcher rd =

[Link]("[Link]");

[Link](req, res);

[Link]
package test;
import [Link].*;
public class UpdateProductDAO {
public int z=0;
public int update(ProductBean pb) {
try {
Connection con = [Link]();
PreparedStatement ps = [Link]
("update Product52 set price=?,qty=? where code=?");
[Link](1, [Link]());
[Link](2, [Link]());
[Link](3, [Link]());
z = [Link]();
}catch(Exception e) {[Link]();}
return z;
}
}

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

[Link] re-write:

=>The process of adding para-values to servlet-url-pattern is

known as "URL re-writing"

=>Through URL re-writing process we can pass para-values from

one Servlet-program to another Servlet-program in Session Tracking

syntax:

url-pattern?para1=value&para2=value&para3=value&...
? - This symbol is separator b/w url-pattern and para-values

& - This symbol is separator b/w parameters.

[Link]

q=gmail

&rlz=1C1YTUH_enIN1024IN1024

&oq=

&aqs=chrome.0.35i39i362j46i39i199i362i465j35i39i362l2j46i39i199i362i465j35i39i362j46i39i
199i362i465j35i39i362.2392573929j0j15

&sourceid=chrome

&ie=UTF-8

[Link]

pcode=A001

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

[Link] Form fields:

=>The process of declaring <input type="hidden" ...> in <form>

tag of HTML is known as Hidden form field.

=>The values in Hidden form fields are not visible to the

end-users.

=>Through Hidden form fields we can pass information from one

Servlet-program to another Servlet-program in Session Tracking.

syntax:

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

<input type="hidden" name="name" value="value">

....

</form>

================================================================
Dt : 24/6/2023

Summary of Session Tracking in Servlet Programming:

(i)Cookie in Session Tracking:

=>Cookie generated by Server-program,but stored in WebBrowser

and tracks the user.

=>Cookie in Session Tracking is a Client dependent or WebBrowser

dependent.

(ii)HttpSession in Session Tracking:

=>HttpSession is created by Server-program,and which is stored

and available in Server.

=>HttpSession will track the user from the Server and which is

Server dependent.

faq:

wt is the diff b/w

(i)getSession()

(ii)getSession(false)

(iii)getSession(true)

(i)getSession():

=>getSession() method is used to access the existing session if


available,if not available then new session is created.

(ii)getSession(false):

=>getSession(false) is used to access the existing session if

available,if not available then new Session is not created.

(iii)getSession(true):

=>getSession() method is used to access the existing session if

available,if not available then new session is created.

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

Note:

=>"URL re-writing" and "Hidden form fields" are used as

Sub-Tracking techniques.

=>These Tracking Techniques are used part of Cookie or HttpSession

in Session Tracking process.

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

Summary of Objects:

CoreJava:

[Link] defined Class Objects

[Link]-Objects

[Link] Objects

[Link]-Objects

[Link]<E> Objects

[Link]<K,V> Objects

[Link]<E> Objects

JDBC Objects:

[Link] Object

[Link] Object

[Link] Object

[Link] Object

[Link] Object
[Link] Object

[Link] Object

[Link] Object

[Link] Object

[Link] Object

Servlet Objects:

[Link] Object

[Link] Object

[Link] Object / HttpServletRequest Object

[Link] Object / HttpServletResponse Object

[Link] Object

[Link] Object

[Link] Object

[Link] Object

[Link](Data Access Object)

[Link] Object

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

faq:

define Serialization?

=>The process of converting Object-state into binary Stream is

known as Serialization process.

faq:

wt is the advantage of Serialization process?

=>Through Serialization process we can make Object available in

the form of binary Stream and we can move on the N/W from one

location to another location.

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

=>Based on Serialization process the Objects are categorized into

two types:
(a)Serializable Objects

(b)NonSerializable Objects

(a)Serializable Objects:

=>The objects which are generated from the classes and the

classes are implementation of "[Link]" interface are

known as Serializable Objects.

=>Serializable Objects means can travel on Network.

Ex:

All CoreJava Objects are Serializable Objects

Cookie Object

Bean Object

JCF Objects

(b)NonSerializable Objects:

=>The Object which are generated from the classes and the classes

are not implementation of "[Link]" interface are

known as NonSerializable objects.

=>NonSerializable Objects means cannot travel on Network

Ex:

JDBC Objects

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

faq:

why we use Java-Beans in Servlet-Programming?

=>JDBC Objects are NonSerializable Objects,because of this

reason we use Java-Beans to hold data retrieved from DB Product.

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

Dt : 27/6/2023

*imp

Filters in Servlet Programming:


=>The pre-processing component which is executed before Servlet

Program is known as "Filter"

Advantage of Filters:

(i)Converion process

(ii)Logging process

(iii)Compression process

(iv)Encryption process

(v)DeCryption Process

(vi)Input Validations

Diagram:

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

=>The following components are used to construct filters:

[Link]

[Link]

[Link]

[Link]:

=>"Filter" is an interface from [Link] package and which

is used to construct filter-programs.

=>In the process of constructing filter-programs,the user defined

classes must be implemented from "Filter" interface.


=>The following are some important methods of 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.

=>FilterChain object is used to link Servlet program to pass the

request.

=>The following is one important method of FilterChain:

public abstract void doFilter([Link],

[Link]) throws [Link],

[Link];

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

Ex-Aplication:

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]
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 DBConnection {
private static Connection con = null;
private DBConnection() {}
static
{
try {
[Link]("[Link]");
con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
}catch(Exception e) {[Link]();}
}//end of block
public static Connection getCon() {
return con;
}
}

[Link]

package test;

import [Link].*;

import [Link].*;

public class LoginDAO {

public UserBean ub = null;

public UserBean login(ServletRequest req) {

try {

Connection con = [Link]();

PreparedStatement ps = [Link]

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

[Link](1, [Link]("uname"));

[Link](2, [Link]("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{

PrintWriter pw = [Link]();

[Link]("text/html");

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

if(ub==null) {

[Link]("Invalid Login Process...<br>");

RequestDispatcher rd =

[Link]("[Link]");

[Link](req, res);

}else {

[Link]("fName", [Link]());

[Link]("lName", [Link]());

[Link]("addr", [Link]());

[Link]("mid", [Link]());

[Link]("phno",[Link]([Link]()));

[Link](req, res);//Linking Servlet

}
}

[Link]

package test;

import [Link].*;

import [Link].*;

import [Link].*;

import [Link].*;

@SuppressWarnings("serial")

@WebServlet("/log")

public class WelcomeServlet extends HttpServlet{

protected void doPost(HttpServletRequest req,

HttpServletResponse res)throws ServletException,

IOException{

PrintWriter pw = [Link]();

[Link]("text/html");

String fName = (String)[Link]("fName");

String lName = (String)[Link]("lName");

String addr = (String)[Link]("addr");

String mId = (String)[Link]("mid");

String phNo = (String)[Link]("phno");

[Link]("Welcome User : "+fName+"<br>");

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

+lName+"&nbsp&nbsp&nbsp"

+addr+"&nbsp&nbsp&nbsp"

+mId+"&nbsp&nbsp&nbsp"

+phNo+"<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>

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

Dt : 28/6/2023

[Link]:

=>FilterConfig is an interface from [Link] package and

which is instantiated automatically when filter-program loaded for

execution and this FilterConfig object is loaded with filter-name

=>we use init() method to access FilterConfig Object reference.

=>we use <init-param> subtag part of <filter> tag to initialize

parameters in 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:

Layout:

[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>100</param-value>
</init-param>
<init-param>
<param-name>b</param-name>
<param-value>200</param-value>
</init-param>
<init-param>
<param-name>c</param-name>
<param-value>300</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>

[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].*;

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{

PrintWriter pw = [Link]();

[Link]("text/html");

String uName = [Link]("uname");

[Link]("Welcome UserName:"+uName+"<br>");

[Link]("****FilterConfig****<br>");

[Link]("FilterName:"+[Link]()+"<br>");

Enumeration<String> e = [Link]();

while([Link]()) {

String el = [Link]();

[Link]("value of "+el+" is "+[Link](el)+"<br>");

}//end of loop

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

Note:

=>In realtime Filters are used in Security layer of applications,

which means used in WebServices-security

========================================================
*imp

Events and Listeners in Servlet Programming:

define Event?
=>The action which is performed on Servlet-Objects is known as

"event in Servlet programming".

define Listener?

=>The program which is executed background to servlet-objects

when event is performed is known "Listener".

Diagram:

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

=>The following are the source-objects in Servlet Programming:

[Link]

[Link]

[Link]

[Link]:

=>The following is the Listener of ServletContext:

Listener : ServletContextListener

Methods :
public void contextInitialized([Link]);

public void contextDestroyed([Link]);

Attribute Listener : ServletContextAttributeListener

Methods :

public void attributeAdded

([Link]);

public void attributeRemoved

([Link]);

public void attributeReplaced

([Link]);

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

[Link]:

=>The following is the Listener of ServletRequest

Listener : ServletRequestListerner

Methods :

public void requestDestroyed([Link]);

public void requestInitialized([Link]);

Attribute Listener :ServletRequestAttributeListener

Methods :

public void attributeAdded

([Link]);

public void attributeRemoved

([Link]);

public void attributeReplaced

([Link]);

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

[Link]:

=>The following is the Listener of HttpSession:


Listener : HttpSessionListener

Methods :

public void sessionCreated([Link]);

public void sessionDestroyed([Link]);

Attribute Listener : HttpSessionAttributeListener

Methods :

public void attributeAdded

([Link]);

public void attributeRemoved

([Link]);

public void attributeReplaced

([Link]);

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

Dt : 29/6/2023

Note:

=>when we want to add listeners for ServletContext then the

User defined class must be implemented from ServletCotextListener

and ServletContextAttributeListener.

=>Use the folowing listener-program in UserApp Application

[Link]

package test;

import [Link].*;

import [Link].*;

@WebListener

public class ContextListener implements ServletContextListener,

ServletContextAttributeListener{

@Override

public void contextInitialized(ServletContextEvent sce) {


[Link]("Context Initialized..");

@Override

public void contextDestroyed(ServletContextEvent sce) {

[Link]("Context destroyed...");

@Override

public void attributeAdded

(ServletContextAttributeEvent scae) {

[Link]("Attribute added to Context...");

@Override

public void attributeRemoved

(ServletContextAttributeEvent scae) {

[Link]("Attribute removed from Context..");

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

Note:

=>When we want to add listeners for ServletRequest then the user

defined class must be implemented from ServletRequestListener and

ServletRequestAttributeListener

=>Use the following listener-program in FilterApp1

[Link]

package test;

import [Link].*;

import [Link].*;

@WebListener

public class RequestListener implements ServletRequestListener,

ServletRequestAttributeListener{
@Override

public void requestInitialized(ServletRequestEvent sre) {

[Link]("request initialized...");

@Override

public void requestDestroyed(ServletRequestEvent sre) {

[Link]("request destroyed...");

public void attributeAdded

(ServletRequestAttributeEvent srae) {

[Link]("request added with attribute...");

public void attributeRemoved

(ServletRequestAttributeEvent srae) {

[Link]("Attribute removed from request...");

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

Note:

=>when we want to add listener for HttpSession then the user

defined class must be implemented from HttpSessionListener and

HttpSessionAttributeListener

=>Use the folowin listener-program in HttpSession App

[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...");

@Override

public void attributeRemoved

(HttpSessionBindingEvent hsbe) {

[Link]("Attribute removed from Session..");

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

Note:

=>In realtime Listeners are used in Security-layer of WebServices

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

Note:

=>The following are the classes related to events:

[Link]

[Link]

[Link]

[Link]

[Link]
[Link]

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

dt : 30/6/2023

*imp

Structure of [Link] in ServletProgramming:

<web-app>

<context-param>

<param-name>name</param-name>

<param-value>value</param-value>

</context-param>

<listener>

<listener-class>class</listener-class>

</listener>

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

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

<welcome-file-list>

<welcome-file>file_name</welcome-file>

</welcome-file-list>

</web-app>

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

faq:

Types of Listeners:
=>Listeners in Servlet-programming are categorized into three

types:

[Link] Listener

[Link] Listener

[Link] Listener

[Link] Listener:

=>The Listener which is added to ServletContext object is known

as Application Listener.

[Link] Listener:

=>The Listener which is added to ServletRequset Object is known

as Request Listerner.

[Link] Listener:

=>The Listener which is added to HttpSession is known as Session

Listener.

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

*imp

Annotations in Servlet Programming:

=>The tag based information which is added to programming

component(Variable,Method,Class and Interface) is known as

Annotation.

=>we use "@" symbol to represent annotations

=>These annotations will specify the information to Compiler at

compilation stage or to execution control at execution stage.

=>The following are some important annotations in CoreJava:

(i)@Override

(ii)@SuppressWarnings

(i)@Override:

=>@Override annotation will specify the compiler to check the


method is Overriding method or not

(ii)@SuppressWarnings

=>@SuppressWarnings annotation will specify the compiler to

close the raised warnings.

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

=>The following are some important annotations in

ServletProgramming:

(i)@WebServlet

(ii)@WebFilter

(iii)@WebListener

(i)@WebServlet:

=>@WebServlet will hold "url-pattern" and used to identify the

Servlt-program for execution

(ii)@WebFilter:

=>@WebFilter will also hold "url-pattern" and used to identify

the Filter-program for execution

(iii)@WebListener :

=>@WebListener is used to identify Listener-program for execution

when event occured on Servlet-objects.

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

*imp(faq)

Servlet Collaboration:

=>The process of interchanging information among servlet-programs

is known as Servlet Collaboration.

(Servlet Communications is also known as Servlet Collaboration)

=>Servlet Collaboration can be peformed in two ways:

(i)RequestDispatcher

(ii)sendRedirect()
(i)RequestDispatcher:

=>RequestDispatcher is used for Servlet-Communications using

the following methods:

(a)forward() - forward Communication

(b)include() - include Communication

=>RequestDispatcher is used to establish communications b/w

Servlet-programs available in same WebApplication.

(ii)sendRedirect():

=>sendRedirect() method is used to establish communication b/w

Servlet-programs available in two different WebApplications.

=>These two different WebApps can be executed on Same Server

or different Servers.

Application : WebApp1

[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="first" method="post">
UserName:<input type="text" name="uname"><br>
MailId:<input type="text" name="mid"><br>
<input type="submit" value="Dispaly">
</form>
</body>
</html>

[Link]

package test;

import [Link].*;

import [Link].*;

import [Link].*;

import [Link].*;

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

public class FirstServlet extends HttpServlet{

@Override

protected void doPost(HttpServletRequest req,

HttpServletResponse res)throws ServletException,

IOException{

String uName = [Link]("uname");

String mId = [Link]("mid");

[Link]

("[Link]

+"&mid="+mId);

[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>

Application : WebApp2

[Link]

package test;

import [Link].*;

import [Link].*;

import [Link].*;

import [Link].*;

@SuppressWarnings("serial")

@WebServlet("/second")

public class SecondServlet extends HttpServlet{

@Override

protected void doGet(HttpServletRequest req,

HttpServletResponse res)throws ServletException,


IOException{

PrintWriter pw = [Link]();

[Link]("text/html");

String uName = [Link]("uname");

String mId = [Link]("mid");

[Link]("****SecondServlet****<br>");

[Link]("UserName:"+uName+"<br>");

[Link]("MailId:"+mId);

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

[Link]

==========================================================
Dt : 1/7/2023

*imp

Servlet-Life-Cycle:

=>Servlet-Life-Cycle demonstrates different states of

Servlet-program from starting to ending.

=>The following are the states of Servlet-program in Life-Cycle:

[Link] process

[Link] process

[Link] process

[Link] handling process

[Link] process

[Link] process:

=>The process of identifying the servlet-program based on

url-pattern and loading for execution is known as Loading process.

[Link] process:

=>when Servlet-program loaded for execution then it is

automatically instantiated known as Instantiation process

Note:

After Instantiation process we can find 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 programming components ready for service()

method is known as Initialization process.

=>This initialization process is performed using init() method.

Note:

=>Loading,Instantiation and Initialization process is perform

only once.

[Link] handling process:

=>The process of accepting the request and providing the response

to the EndUser,is known as Request handling process.

=>we use service()/doPost()/doGet() method to perform Request

handling process.

Note:

=>service() method is executed for all multiple requests from

multiple users.

[Link] process:

=>The process of making programming components eligible for

destroying is known as destroying process.

=>we use destroy() method to perform destroying process.

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

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]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>

[Link]

package test;

import [Link].*;

import [Link].*;

import [Link].*;

import [Link].*;

@SuppressWarnings("serial")

@WebServlet("/dis")

public class Display extends HttpServlet

public int x;

public int y;

public Display()

x++;

y++;

@Override

public void init()throws ServletException

x++;
y++;

@Override

protected void doPost(HttpServletRequest req,

HttpServletResponse res)throws ServletException,

IOException{

PrintWriter pw = [Link]();

[Link]("text/html");

String uName = [Link]("uname");

[Link]("Welcome User : "+uName+"<br>");

[Link]("The value of x : "+x+"<br>");

[Link]("The value of y : "+y+"<br>");

@Override

public void destroy()

x=100;

y=200;

}
===========================================================

*imp

Generating WAR file and executing from Tomcat Server:

step-1 : Generating 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

Click on Manager App->perform login process->

From 'WAR file to deploy' click 'choose file'->

browse and select the file->click 'deploy'

Execution URL:

[Link] (Same Computer)

[Link] (Romote Computer)

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

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)

=================================================================
Dt : 3/7/2023

*imp

JSP Programming:(Unit-3)

=>JSP Stands for 'Java Server Page' and which is response from

WebApplication.

=>JSP is tag based programming language and which is more easy

when compared to Servlet programming.

=>Programs in JSP are saved with (.jsp) as an extention.

=>JSP programs are combination of both HTML code and Java Code.

=>JSP provides the following tags to write JavaCode part of JSP

programs:

[Link] tags

=>Scriptlet tag

=>Expression tag

=>Declarative tag

[Link] tags

=>page

=>include

=>taglib

[Link] tags

=>jsp:include

=>jsp:forward

=>jsp:param

=>jsp:useBean

=>jsp:setProperty

=>jsp:getProperty

[Link] tags:

=>Scripting tags are used to write JavaCode part of JSP programs.

=>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(Servlet Code)

part of JSP programs

syntax:

<% ---JavaCode--- %>

(b)Expression tag:

=>Expression tag is used to assign the value to variable or

which is used to display the data to the WebBrowser.

syntax:

<%= expression %>

(c)Declarative tag:

=>Declarative tag is used to declare variables and methods in JSP

programs.

syntax:

<%! variables;methods %>

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

[Link] tags:

=>The tags which are used to specify the directions in

translation process are known as Directive Tags.

The following are the types of Directive tags:

(a)page

(b)include

(c)taglib

(a)page:
=>'page' directive tag specifies the translator to add the related

attribute to current JSP page.

syntax:

<%@ page attribute="value" %>

exp:

<%@ page import="[Link].*"%>

List of attributes:

[Link]

[Link]

[Link]

[Link]

[Link]

[Link]

[Link]

[Link]

[Link]

[Link]

[Link]

[Link]

[Link]

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

(b)include:

=>'include' directive tag specifies the file to be included to

current JSP page.

syntax:

<%@ include file="file-name"%>

Exp:

<%@ include file="[Link]" %>


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

(c)taglib:

=>'taglib' directive tag specifies to add specified url to current

JSP page and which is used part of EL(Expression Lang) and JSTL

(JSP Standard Tag Lib).

syntax:

<%@ taglib url="urloftaglib" prefix="prefixoftaglib"%>

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

Ex : 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 n = [Link]([Link]("v"));
int res = factorial(n);
[Link]("Factorial:"+res+"<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>

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

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

=>The following are the implicit objects of JSP:

application - [Link]

config - [Link]

request - [Link]

response - [Link]

out - [Link]

session - [Link]

exception - [Link]

page - [Link]

pageContext - [Link]

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

[Link] tags:

=>Action Tags are used to include some basic actions like

inserting some other page resources ,forwarding the request

to another page,creating or locating the JavaBean instances

and,setting and retrieving the bean properties in JSP pages.

Note:

=>These action tags are used in Execution process at runtime.

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

=>The following are some Important action tags available in

JSP:

1.<jsp:include>

2.<jsp:forward>

3.<jsp:param>

4.<jsp:useBean>
5.<jsp:setProperty>

6.<jsp:getProperty>

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

1.<jsp:include> :

=>This action tag allows to include a static or dynamic

resource such as HTML or JSP specified by an URL to be

included in the current JSP while processing request.

=>If the resource is static then its content is included

in the JSP page.

=>If the resource is dynamic then its result is included in

the JSP page.

syntax:

<jsp:include attributes>

<---Zero or more jsp:param tags--->

</jsp:include>

attributes of include tag:

*imp

page : Takes a relative URL,which locates the resource

to be included in the JSP page.

<jsp:include page="/[Link]"/>

<jsp:include page="<%=mypath%>"/>

flush : Takes true or false,which indicates whether or not

the buffer needs to be flushed before including resource.

2.<jsp:forward>:

=> This action tag forwards a JSP request to another

resource and which can be either static or dynamic.

=>If the resource is dynamic then we can use a jsp:param


tag to pass name and value of the parameter to the resource.

sntax:

<jsp:forward attributes>

<-- Zero or more jsp:param tags-->

</jsp:forward>

Exp:

<jsp:forward page="/[Link]"/>

<jsp:forward page="<%=mypath%>"/>

3.<jsp:param>:

This action tag is used to hold the parameter with value

and which is to be forwarded to the next resource.

syntax:

<jsp:param name="paramName" value="paramValue"/>

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

4.<jsp:useBean>:

=>This tag is used to instantiate a JavaBean,or locate an

existing bean instance and assign it to a variable name(id).

syntax:

<jsp:useBean attributes>

<!-optional body content--->

</jsp:useBean>

Attributes of <jsp:useBean> tag:

(a)id

(b)scope

(c)class

(d)beanName

(e)type
(a)id:

=>which represents the variable name assigned to id attribute of

<jsp:useBean> tag and which holds the reference of JavaBean instance.

(b)scope:

=>which specifies the scope in which the bean instance has to be

created or located.

scope can be the following:

(i)page scope : within the JSP page,until the page sends response.

(ii)request scope : JSP page processing the same request until a JSP sends response.

(iii)session scope - Used with in the Session.

(iv)application scope - Used within entire web application.

*imp

(c)class :

=>The class attribute takes the qualified class name to create a

bean instance.

(d)beanName :

=>The beanName attribute takes a qualified class name.

(e)type :

=>The "type" attribute takes a qualified className or

interfaceName,which can be the classname given in the class or

beanName attribute or its super type.

5.<jsp:setProperty>:

=>This action tag sets the value of a property in a bean,

using the bean's setter methods.

Types of attributes:

(a)name
(b)property

(c)value

(d)param

(a)name:

=>The name attribute takes the name of already existing bean as

a reference variable to invoke the setter method.

(b)property:

=>which specifies the property name that has to be set,and

specifies the setter method that has to be invoked.

(c)value:

=>The value attribute takes the value that has to be set to the

specified bean property.

(d)param:

=>which specify the name of the request parameter whose value to

be assigned to bean property.

6.<jsp:getProperty>:

=>This action tag gets the value of a property in a bean

by using the bean's getter method and writes the value to the

current JspWriter.

Types of attributes:

(a)name

(b)property

(a)name:

=>The name attribute takes the reference variable name on which we

want to invoke the getter method.

(b)property:
=>which gets the value of a bean property and invokes the getter

method of the bean property.

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

The following are some rare used Actions tags:

7.< jsp:plugIn >:

The <jsp:plugin> action tag provide easy support for

including a java applet in the client Web browser, using a

built-in or downloaded java plug-in.

Syntax:

<jsp:plugin attributes>

<!-optionally one jsp:params or jsp:fallback tag-

</jsp:plugin>

8. < jsp:fallBack >

The <jsp:fallback> action tag allows us to specify a text

message to be displayed if the required plug-in cannot run

and this action tag must be used as a child tag with the

<jsp:plugin> action tag.

Syntax:

<jsp:fallback>

Test message that has to be displayed if the plugin cannot be started

</jsp:fallback>

9. < jsp:params >

The <jsp:params> action tag sends the parameters that we

want to pass to an applet.

Syntax:

<jsp:params>

<!-one or more jsp:param tags---


</jsp:params>

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

Dt : 4/7/2023

Ex-Application:(Demonstrating forward,include and 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 Value1:<input type="text" name="v1"><br>
Enter the Value2:<input type="text" name="v2"><br>
<input type="submit" value="Add" name="s1">
<input type="submit" value="Sub" name="s1">
</form>
</body>
</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="500" 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"));
String nm = [Link]("nm");
int v3 = v1+v2;
[Link]("Param-Value:"+nm+"<br>");
[Link]("Sum:"+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"));
String nm = [Link]("nm");
int v3 = v1-v2;
[Link]("Param-Value:"+nm+"<br>");
[Link]("Sub:"+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]("Enter only Integer values..<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>

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

Ex-Application :(Demonstrating useBean,setProperty and

getProperty)

Layout:
[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]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="[Link]" method="post">
ProdCode:<input type="text" name="code"><br>
ProdName:<input type="text" name="name"><br>
ProdPrice:<input type="text" name="price"><br>
ProdQty:<input type="text" name="qty"><br>
<input type="submit" value="LoadProduct">
</form>
</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="ob" class="[Link]" scope="session"/>
<jsp:setProperty property="code" param="code" name="ob"/>
<jsp:setProperty property="name" param="name" name="ob"/>
<jsp:setProperty property="price" param="price" name="ob"/>
<jsp:setProperty property="qty" param="qty" name="ob"/>
<%
[Link]("Producr details loaded to Bean-Object..<br>");
%>
<a href="[Link]">ViewDetailsFromBean</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="ob" type="[Link]" scope="session"/>
ProductCode:<jsp:getProperty property="code" name="ob"/><br>
ProductName:<jsp:getProperty property="name" name="ob"/><br>
ProductPrice:<jsp:getProperty property="price" name="ob"/><br>
ProductQty:<jsp:getProperty property="qty" name="ob"/><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>

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

Dt : 5/7/2023

faq:

JSP Life-Cycle:

=>JSP Life-Cycle demonstrates different states of Jsp-program

from starting to ending of program.

=>The following are the stages of JSP program:

[Link] process

[Link] process

[Link] process

[Link] process

[Link] process

[Link] handling process

[Link] process

Diagram:
[Link] process:

=>The process of separating JavaCode from Jsp-program is known

as Translation process.

[Link] process:

=>The process of compiling the JavaCode and generating ByteCode

is known as Compilation process.

[Link] process:

=>The process of loading JSP-program for execution is known as

Loading process.

[Link] process:

=>The process of generating object for JSP-program automatically

by WebContainer is known as Instantiation process.

=>After instatiation process we can find the following

Life-Cycle methods:

(i)_jspInit()

(ii)_jspService()

(iii)_jspDestroy()

[Link] process:

=>The process of making the programming components ready for


execution is known as Initialization process.

[Link] handling process:

=>The process of accepting the request and providing the response

is known as Request handling process.

[Link] process:

=>The process of making the programming components eligible for

destroying is known as Destroying process.

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

*imp

MVC Architecture:

=>MVC stands for 'Model View Controller' and which is architectural

design pattern used in realtime to develop applications.

Diagram:

Controller(C):

=>Controller will accept the request from the end-user and controls

View(Presentation) and Model layers of application.


Model(M):

=>Model layer in application will have Business logics,DAO and

external services.

View(V):

=>View means presentation from the WebApplications

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

*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

Dt : 6/7/2023

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.

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

Summary of Objects in Servlet and JSP:

CoreJava:

[Link] defined Class Objects

[Link]-Objects

[Link] Objects

[Link]-Objects

[Link]<E> Objects

[Link]<K,V> Objects

[Link]<E> Objects

JDBC Objects:
[Link] Object

[Link] Object

[Link] Object

[Link] Object

[Link] Object

[Link] Object

[Link] Object

[Link] Object

[Link] Object

[Link] Object

Servlet Objects:

[Link] Object

[Link] Object

[Link] Object / HttpServletRequest Object

[Link] Object / HttpServletResponse Object

[Link] Object

[Link] Object

[Link] Object

[Link] Object

[Link](Data Access Object)

[Link] Object

JSP Objects:

[Link]

[Link]

[Link]

[Link]

[Link]

[Link]

[Link]
[Link]

[Link]

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

Project_Name : JSP_MVC

DBTables :

Table : UserTab52

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

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

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

insert into UserTab52 values('nit.v','mzu672','Venkat','M','SRN',

'v@[Link]',9898981234);

Table : AdminTab52

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

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

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

Layout:

[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="[Link]">UserLogin</a>
<a href="[Link]">AdminLogin</a>
</body>
</html>

[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="user" 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]
package test;
import [Link].*;
public class DBConnection {
private static Connection con = null;
private DBConnection() {}
static
{
try {
[Link]("[Link]");
con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
}catch(Exception e) {[Link]();}
}//end of block
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].*;

import [Link].*;
public class UserLoginDAO {

public UserBean ub=null;

public UserBean login(HttpServletRequest req) {

try {

Connection con = [Link]();

PreparedStatement ps = [Link]

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

[Link](1, [Link]("uname"));

[Link](2, [Link]("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("/user")

public class UserLoginServlet extends HttpServlet{

protected void doPost(HttpServletRequest req,

HttpServletResponse res)throws ServletException,

IOException{

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

if(ub==null) {

[Link]("msg","Invalid Login Process..<br>");

[Link]("[Link]").forward(req, res);

}else {

HttpSession hs = [Link]();

[Link]("ub", ub);

[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>
<%
UserBean ub = (UserBean)[Link]("ub");
[Link]("Welcome User "+[Link]()+"<br>");
%>
<a href="view">ViewProducts</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+"<br>");
%>
<a href="[Link]">UserLogin</a>
<a href="[Link]">AdminLogin</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>

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

Dt : 7/7/2023

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

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 Product52");

ResultSet rs = [Link]();

while([Link]()) {

ProductBean pb = new ProductBean();

[Link]([Link](1));

[Link]([Link](2));

[Link]([Link](3));

[Link]([Link](4));

[Link](pb);//Adding ProductBean 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{

HttpSession hs = [Link](false);

if(hs==null) {

[Link]("msg", "Session expired...<br>");

[Link]("[Link]").forward(req, res);

}else {

ArrayList<ProductBean> al =

new ViewProductsDAO().retrieve();

[Link]("al", al);

[Link]("[Link]").forward(req, res);

[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="[Link].*,test.*"%>
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
UserBean ub = (UserBean)[Link]("ub");
ArrayList<ProductBean> al =
(ArrayList<ProductBean>)[Link]("al");
[Link]("page of "+[Link]()+"<br>");
if([Link]()==0){
[Link]("Products not available...<br>");
}else{
Iterator<ProductBean> it = [Link]();

%>
<table>
<tr>
<th>CODE</th>
<th>NAME</th>
<th>PRICE</th>
<th>QTY</th>

</tr>
<%
while([Link]()){
ProductBean pb = (ProductBean)[Link]();
%>
<tr>
<td><%=[Link]() %></td>
<td><%=[Link]() %></td>
<td><%=[Link]() %></td>
<td><%=[Link]() %></td>
<td><a href="buy?code=<%=[Link]()%>">Buy</a></td>
</tr>
<%
}
%>
</table>
<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{

HttpSession hs = [Link](false);

if(hs==null) {

[Link]("msg","Session expired...<br>");

}else {

[Link]("ub");

[Link]("al");

[Link]();//session destroyed

[Link]("msg","logged out Successfully...<br>");

[Link]("[Link]").forward(req, res);

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

*imp

Expression Language(EL) in JSP:

=>EL(Expression Language) simplifies the accessibility of

data stored in java Bean component and other objects like

request,session,application,etc..
Note:

It is newly added feature in JSP technology,known as JSP-EL.

syntax of EL:

$(expression)

The following are the implicit objects of EL:

[Link]

[Link]

[Link]

[Link]

[Link]

[Link]

[Link]

[Link]

[Link]

[Link]

[Link]

[Link] : It maps the given attribute name with the value,

set in the page scope

[Link] : It maps the given attribute name with the value

set in the request scope

[Link] : It maps the given attribute name with the value

set in the session scope

[Link] : It maps the given attribute name with the

value set inthe application scope

[Link] : It maps the request parameter to the single value


[Link] :

It maps the request parameters to the array of

values

[Link] : It maps the request header name to the single value

[Link] : It maps the request header names to the array

of values

[Link] :It maps the cookie name to the cookie value

[Link] : It maps the Initialization parameter

[Link] : It provides access to many objects request,

session,...

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

Summery of Objects Generated:

CoreJava Objects:

[Link] Class objects

[Link] objects

(i)Byte Object

(ii)Short Object

(iii)Integer object

(iv)Long Object

(v)Float Object

(vi)Double Object

(vii)Character object

(viii)Boolean Object

[Link] Objects

(i)String Object

(ii)StringBuffer object

(iii)StringBuilder object
[Link] Objects

(i)User defined Class Array

(ii)String Array

(iii)WrapperClass Array

(iv)Object Array

(v)Jagged Array

[Link]<E> Objects

(a)Set<E>

(i)HashSet<E> object

(ii)LinkedHashSet<E> Object

(iii)TreeSet<E> Object

(b)List<E>

(i)ArrayList<E> Object

(ii)Vector<E> Object

|->Stack<E> Object

(iii)LinkedList<E> Object

(c)Queue<E>

(i)PriorityQueue<E> Object

|->Deque<E>

(ii)ArrayDeque<E> Object

(iii)LinkedList<E> Object

[Link]<K,V> Objects

(i)HashMap<K,V> Object

(ii)LinkedHashMap<K,V> Object

(iii)TreeMap<K,V> Object

(iv)Hashtable<K,V> Object

[Link]<E> objects

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

Utility Classes:

(i)[Link]
(ii)[Link]

(iii)[Link]

(iV)[Link]

(v)[Link]

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

Cursor Objects:

(i)Iterator<E>

(ii)ListIterator<E>

(iii)Enumeration<E>

(iV)Spliterator<T>

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

JDBC Objects:

[Link] Object

[Link] Object

[Link] Object

[Link] object

[Link] ResultSet Object

[Link]-Scrollable ResultSet Object

[Link] object

[Link] object

[Link] object

[Link] Object

(i)JdbcRowSet

(ii)CachedRowSet

=>WebRowSet

=>FilteredRowSet

=>JoinRowSer

[Link]

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

[Link] pooling object(Vector<E> object)


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

Servlet Objects:

[Link] object

[Link] Object

[Link] object/HttpServletRequest object

[Link] object/HttpServletResponse object

[Link] object

[Link] object

[Link] object

[Link] Layer object

[Link] object

[Link] Object

JSP objects:

[Link]

[Link]

[Link]

[Link]

[Link]

[Link]

[Link]

[Link]

[Link]

----------

JSP EL objects:

[Link]

[Link]

[Link]

[Link]

[Link]

[Link]
[Link]

[Link]

[Link]

[Link]

[Link]

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

Note:

=>In realtime JSPEL replaces with SpEL.

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

Objects Layout diagram:

==============================================================
Dt : 10/7/2023

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.

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

Ex-1:

Layout:
[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>

[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>

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

Ex-2:

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]
<%@ 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]

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]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>

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

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

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

Ex:

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

[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>

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

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

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

Ex:

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

[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>

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

(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 : 11/7/2023

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();

Note:

=>we can also add "attribute" to the "pageContext" object.

=>'pageScope' implicit object of EL-JSTL will access the

attribute of "pageContext" object of JSP.

=>"pageContext" implicit object of EL-JSTL will access the


remaining objects of EL-JSTL.

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

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.

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

faq:

define Custom tags?

=>The user defined tags are known as Custom Tags.

=>"[Link]" is JSP-API which supports user defined

tag construction.

Hierarchy of JSP-Tag-API:
=>we use the following steps to construct Custom Tag:

step-1 : Create the Tag handler class and perform action at the

start or at the end of the tag.

step-2 : Create the Tag Library Descriptor (TLD) file and define

tags
Step-3 : Create the JSP file that uses the Custom tag defined

in the TLD file

[Link]

package test;

import [Link].*;

import [Link].*;

import [Link].*;

@SuppressWarnings("serial")

public class TagHandler extends TagSupport{

public int doStartTag() throws JspException{

JspWriter out = [Link]();

try {

[Link]([Link]().getTime());

}catch(Exception e) {}

return SKIP_BODY;

[Link] (File created in WEB-INF)

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

<taglib>

<tlib-version>1.0</tlib-version>

<jsp-version>1.2</jsp-version>

<tag>

<name>today</name>

<tag-class>[Link]</tag-class>

</tag>

</taglib>
[Link]

<%@ page language="java"

contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<%@ taglib uri="/WEB-INF/[Link]" prefix="m" %>

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>Insert title here</title>

</head>

<body>

Current DateTime is : <m:today/>

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

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

Note:

=>To execute CustomTag applications,we must add "[Link]"

and "[Link]" to the applications using Build-path

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

Ex-application:(Demonstrating registration with validations)

[Link]
@charset "ISO-8859-1";
h1 {
margin-left: 70px;
}
form li {
list-style: none;
margin-bottom: 5px;
}

form ul li label{
float: left;
clear: left;
width: 100px;
text-align: right;
margin-right: 10px;
font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:14px;
}

form ul li input, select, span {


float: left;
margin-bottom: 10px;
}

form textarea {
float: left;
width: 350px;
height: 150px;
}

[type="submit"] {
clear: left;
margin: 20px 0 0 230px;
font-size:18px
}

p {
margin-left: 70px;
font-weight: bold;
}

[Link]
/**
*
*/
function formValidation()
{
var uid = [Link];
var passid = [Link];
var uname = [Link];
var uadd = [Link];
var ucountry = [Link];
var uzip = [Link];
var uemail = [Link];
var umsex = [Link];
var ufsex = [Link];
if(userid_validation(uid,5,12))
{
if(passid_validation(passid,7,12))
{
if(allLetter(uname))
{
if(alphanumeric(uadd))
{
if(countryselect(ucountry))
{
if(allnumeric(uzip))
{
if(ValidateEmail(uemail))
{
if(validsex(umsex,ufsex))
{
}
}
}
}
}
}
}
}
return false;

} function userid_validation(uid,mx,my)
{
var uid_len = [Link];
if (uid_len == 0 || uid_len >= my || uid_len < mx)
{
alert("User Id should not be empty / length be between "+mx+" to
"+my);
[Link]();
return false;
}
return true;
}
function passid_validation(passid,mx,my)
{
var passid_len = [Link];
if (passid_len == 0 ||passid_len >= my || passid_len < mx)
{
alert("Password should not be empty / length be between "+mx+"
to "+my);
[Link]();
return false;
}
return true;
}
function allLetter(uname)
{
var letters = /^[A-Za-z]+$/;
if([Link](letters))
{
return true;
}
else
{
alert('Username must have alphabet characters only');
[Link]();
return false;
}
}
function alphanumeric(uadd)
{
var letters = /^[0-9a-zA-Z]+$/;
if([Link](letters))
{
return true;
}
else
{
alert('User address must have alphanumeric characters only');
[Link]();
return false;
}
}
function countryselect(ucountry)
{
if([Link] == "Default")
{
alert('Select your country from the list');
[Link]();
return false;
}
else
{
return true;
}
}
function allnumeric(uzip)
{
var numbers = /^[0-9]+$/;
if([Link](numbers))
{
return true;
}
else
{
alert('ZIP code must have numeric characters only');
[Link]();
return false;
}
}
function ValidateEmail(uemail)
{
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-
]?\w+)*(\.\w{2,3})+$/;
if([Link](mailformat))
{
return true;
}
else
{
alert("You have entered an invalid email address!");
[Link]();
return false;
}
} function validsex(umsex,ufsex)
{
x=0;

if([Link])
{
x++;
} if([Link])
{
x++;
}
if(x==0)
{
alert('Select Male/Female');
[Link]();
return false;
}
else
{
alert('Form Succesfully Submitted');
[Link]()
return true;
}
}

[Link]
<!DOCTYPE html>
<html lang="en"><head>
<meta charset="utf-8">
<title>JavaScript Form Validation using a sample registration
form</title>
<meta name="keywords" content="example, JavaScript Form
Validation, Sample registration form" />
<meta name="description" content="This document is an example of
JavaScript Form Validation using a sample registration form. "
/>
<link rel='stylesheet' href='[Link]'
type='text/css' />
<script src="[Link]"></script>
</head>
<body onload="[Link]();">
<h1>Registration Form</h1>
Use tab keys to move from one input field to the next.
<form action="reg" method="post" name='registration'
onSubmit="return formValidation();">
<ul>
<li><label for="userid">User id:</label></li>
<li><input type="text" name="userid" size="12" /></li>
<li><label for="passid">Password:</label></li>
<li><input type="password" name="passid" size="12" /></li>
<li><label for="username">Name:</label></li>
<li><input type="text" name="username" size="50" /></li>
<li><label for="address">Address:</label></li>
<li><input type="text" name="address" size="50" /></li>
<li><label for="country">Country:</label></li>
<li><select name="country">
<option selected="" value="Default">(Please select a
country)</option>
<option value="Aus">Australia</option>
<option value="Canada">Canada</option>
<option value="India">India</option>
<option value="Russia">Russia</option>
<option value="USA">USA</option>
</select></li>
<li><label for="zip">ZIP Code:</label></li>
<li><input type="text" name="zip" /></li>
<li><label for="email">Email:</label></li>
<li><input type="text" name="email" size="50" /></li>
<li><label id="gender">Sex:</label></li>
<li><input type="radio" name="gen" value="Male"
checked="checked"/><span>Male</span></li>
<li><input type="radio" name="gen" value="Female"
/><span>Female</span></li>
<li><label>Language:</label></li>
<li><input type="checkbox" name="lan" value="english" checked
/><span>English</span></li>
<li><input type="checkbox" name="lan" value="hindi"
/><span>Hindi</span></li>
<li><input type="checkbox" name="lan"
value="telugu" /><span>Telugu</span></li>
<li><input type="checkbox" name="lan" value="noen" /><span>Non
English</span></li>
<li><label for="desc">About:</label></li>
<li><textarea name="desc" id="desc"></textarea></li>
<li><input type="submit" name="submit" value="Submit" /></li>
</ul>
</form>
</body>
</html>

[Link]

package test;

import [Link].*;

import [Link].*;

import [Link].*;
import [Link].*;

@WebServlet("/reg")

public class RegServlet extends HttpServlet{

protected void doPost(HttpServletRequest req,

HttpServletResponse res)throws ServletException,

IOException{

/* PrintWriter pw = [Link]();

[Link]("text/html");

String userId = [Link]("userid");

String passId = [Link]("passid");

String userName = [Link]("username");

String addr = [Link]("address");

String country = [Link]("country");

String zip = [Link]("zip");

String mId = [Link]("email");

String gen = [Link]("gen");

String lang[] = [Link]("lan");

String desc = [Link]("desc");

[Link](userId+"<br>");

[Link](passId+"<br>");

[Link](userName+"<br>");

[Link](addr+"<br>");

[Link](country+"<br>");

[Link](zip+"<br>");

[Link](mId+"<br>");

[Link](gen+"<br>");

for(String l : lang)

[Link](l+"<br>");

}
[Link](desc+"<br>");*/

[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>
<style>
table, th, td {
border: 1px solid;
}
</style>
</head>
<body>
<table>
<tr>
<td>UserID</td>
<td><%=[Link]("userid") %></td>
</tr>
<tr>
<td>PassId</td>
<td><%=[Link]("passid") %></td>
</tr>
<tr>
<td>UserName</td>
<td><%=[Link]("username") %></td>
</tr>
<tr>
<td>Address</td>
<td><%=[Link]("address") %></td>
</tr>
<tr>
<td>Country</td>
<td><%=[Link]("country") %></td>
</tr>
<tr>
<td>ZIP</td>
<td><%=[Link]("zip") %></td>
</tr>
<tr>
<td>MailId</td>
<td><%=[Link]("email") %></td>
</tr>
<tr>
<td>Gender</td>
<td><%=[Link]("gen") %></td>
</tr>
<tr>
<td>Languages</td>
<td><%
String lang[] = [Link]("lan");
for(String str : lang)
{
%>
<%=str %>
<%
}
%>
</td>
</tr>
<tr>
<td>Description</td>
<td><%=[Link]("desc") %></td>
</tr>
</table>

</body>
</html>

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

Dt : 13/7/2023

CoreJava Container Objects : 31 Objects(Min)

CoreJava Utility Objects : 5

CoreJava Cursor Objects : 4

JDBC Objects : 10

Servlet Objects : 10

JSP Objects :9

EL-JSTL : 11

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

Total Objects : 80 Objects

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

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

NASSCOM Examination:

Section-1 => CoreJava : 10


Section-2 => AdvJava : 9

Section-3 => Framework : 2

Section-4 => Database : 7

Section-5 => UI :4

Section-6 => Testing : 2

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

Total : 34

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

Case Study :

ProjectName : Student Management System

DB Tables : AdminTab52

Student53(rno,name,br,totmarks,per,result)

StuMarks53(rno,tel,hin,eng,maths,sci,sco)

You might also like