Adv - Java VM
Adv - Java VM
By VENKATESH MAIPATHI
DHANANJAYA ARJUN
Dt : 26/10/2023(day-1)
define Application?
=>Set-of-programs collected together to perform defined action is known
as Application.
Types of Applications:
=>Applications are categorized into four types:
[Link]-Alone-Applications
[Link] Applications
[Link] Applications
[Link] Applications
[Link]-Alone-Applications:
=>The Applications which are installed in one computer and performs
actions in the same Computer are knonw as Stand-Alone-Applications
or DeskTop Applications or Windows Applications
=>Based on user interaction the Stand-Alone-Applications are categorized
into two types:
(i)CUI Applications
(ii)GUI Applications
(i)CUI Applications:
=>The Applications in which the user interacts through Console
(CommandPrompt) are known as CUI Applications.
(CUI - Console User Interface)
(ii)GUI Applications:
=>The Applications in which the used interacts through GUI Components
are known as GUI Applications.
(GUI - Graphical User Interface)
=>we use the following to construct GUI Components:
AWT - Abstract Window Toolkit
Swing
JavaFX
------------------------------------------------------------------
*imp
[Link] Applications:
=>The applications which are executed in Web Environment or Internet
Environment are known as WebApplications or Internet Applications.
=>we use the following three technologies to construct WebApplications
(i)JDBC
(ii)Servlet
(iii)JSP
------------------------------------------------------------------
[Link] Applications:
=>The applications which are executing in distributed environment and
depending on the features like "Security","Load Balancing" and
"Clustering" are known as Enterprise Applications or Enterprise
Distribute Applications.
=>To develop Enterprise Applications we use Java Frameworks and
Java Tools.
-------------------------------------------------------------------------
[Link] Applications:
=>The appliactions which are executed in Mobile environment are known as
Mobile Applications.
==========================================================================
*imp
define Storage?(Syllabus)
=>The location where the data is available for access,is known as Storage.
Types of Storages:
=>According to Java Application development the storages are categorized
into four types:
[Link] Storage
[Link] Storage
[Link] Storage
[Link] Storage
Dt : 27/10/2023(day-2)
[Link] Storage:
=>The memory generated to hold 'single data value' is known as Field
Storage.
=>The primitive datatypes(byte,short,int,long,float,double,char,boolean)
will generate Field Storages.
*imp
[Link] Storage:
=>The memory generated to hold 'group members' is known as Object
Storage.
=>The NonPrimitive datatype(Class,Interface,Array,Enum) will generate
Object Storage.
Ex:
class Addition{
int a=10,b=20;
void add() {
int c = a+b;
[Link]("Sum="+c);
}
}
-------------------------------------------------------------------
faq:
wt is the diff b/w
(i)Object
(ii)Object reference
(iii)Object reference Variable
(i)Object:
=>The memory which is generated to hold instance members of Class is
known as Object.
(ii)Object reference
=>The address where object is generated is known as Object reference.
=====================================================================
[Link] Storage:
=>The smallest permanent storage of ComputerSystem which is controlled
and managed by the OperatingSystem is known as File Storage.
=>In the process of establishing communication b/w JavaProgram and
File-Storage,the JavaProgram must be constructed using 'classes and
Interfaces' available from '[Link]' package(IO Stream and FIle API).
Diagram:
======================================================================
Dis-Advantages of File-Storage:
[Link] Redundancy
[Link] Inconsistency
[Link] Integrity problem
[Link] Sharing Problem
[Link] Security Problem
[Link] Redundancy:
=>The process in which File-Storage will store duplicate data,known
as Data Redundancy or Data Replication.
[Link] Inconsistency:
=>The process in which File-storage will different data fields,known
as Data Inconsistency.
=================================================================
Note:
=>Because of DisAdvantages of File-Storage,we are not prefering to
take File-storage as Back-end for applications.
=====================================================================
Dt : 31/10/2023
*imp
[Link] Storage:
=>The largest permanent storage of ComputerSystem,which is 'downloaded
and installed' from externally is known as Database.
=>In the process of establishing communication b/w JavaProgram and
Database product,the JavaProgram must be constructed using 'Classes
and Interface' available from '[Link]' package(JDBC API) and the
JavaProgram must take the support of JDBC-driver
Diagram:
==================================================================
faq:
define driver?
=>The small s/w program used by OperatingSystem to establish connection
b/w two end-points
Ex:
Audio driver
Video driver
N/W driver
....
faq:
define JDBC driver?
=>The driver which is used to establish connection b/w JavaProgram and
Database product is known as JDBC driver.
(Java DataBase Connectivity driver)
Note:
=>In realtime application development we use Type-4(Thin) driver.
=====================================================================
faq:
define API?
=>API stands for 'Application Programming Interface' and which is a
PlatForm for programmers to develop applications using Language or
Technology or Frameworks
=>According to JavaLanguage,API means package.
=>The following are some important APIs(packages):
CoreJava:
[Link] - Language package(default package)
[Link] - Input/Output Stream and Files package
[Link] - Utility package
[Link] - Networking package
AdvJava:
[Link] - Database package(JDBC API)
[Link] - Servlet programming package(Servlet API)
[Link] - JSP Programming package(JSP API)
===================================================================
*imp
Making ComputerSystem environment ready for executing JDBC Applications:
faq:
define JAR file?
=>JAR stands for Java Archieve and which is compressed format of
more class files.
PortNo : 1521
ServiceName : XE
=======================================================================
Dt : 1/11/2023
*imp
JDBC API:
=>'[Link]' package is known as JDBC API and which provide 'Classes
and Interfaces' to Construct JDBC Applications.
=>'[Link]' interface is the root of JDBC API.
=>The following are some important methods from 'Connection' interface:
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
------------------------------------------------------------
=>we use getConnection() method from '[Link]' class to
create implemention object for 'Connection' interface.
=>This getConnection() method internally holding Anonymous Local InnerClass
as implementation class of 'Connection' interface.
syntax:
Connection con = [Link]("DBURL","UName","PWord");
[Link]:
=>'Statement' is an interface from [Link] package and which is used
to execute normal queries without IN Parameters.
(Normal Queries maens Create,Insert,Select,Update,Delete)
=>we use createStatement() method from 'Connection' interface to create
implementation object for 'Statement' interface.
=>This createStatement() method internally holding Anonymous Local
InnerClass as implementation class of 'Statement' interface.
syntax:
Statement stm = [Link]();
Method Signature:
public abstract [Link] executeQuery([Link])
throws [Link];
syntax:
ResultSet rs = [Link]("select-query");
(ii)executeUpdate():
=>executeUpdate() method is used to execute NonSelect-queries.
Method Signature:
public abstract int executeUpdate([Link])
throws [Link];
syntax:
int k = [Link]("NonSelect-query");
-------------------------------------------------------------
*imp
we use the following steps to establish connection to Database Product:
step-1 : Loading driver
step-2 : Creating Connection
step-3 : Preparing Statement
step-4 : Executing query
step-5 : Closing the connection
===================================================================
*imp
Creating JDBC application using IDE Eclipse:
step-1 : Open IDE Eclipse,while opening name the workspace and click
'Launch'.
step-2 : Create Java Project
Program : [Link]
package test;
import [Link].*;
public class DBCon1
{
public static void main(String[] args)
{
try
{
//step-1 : Loading driver
[Link]("[Link]");
//step-2 : Creating Connection
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
//step-3 : Preparing Statement
Statement stm = [Link]();
//step-4 : Executing query
ResultSet rs = [Link]
("select * from Customer57");
[Link]("****Customer-Details****");
while([Link]())
{
[Link]([Link](1)+"\t"+
[Link](2)+"\t"+[Link](3)+
"\t"+[Link](4)+"\t"+
[Link](5)+"\t"+[Link](6)+"\t"+
[Link](7));
}//end of loop
//step-5 : Closing the connection
[Link]();
}//end of try
catch(Exception e)
{
[Link]();
}
}
}
=========================================================================
Assignment:
Step-1 : Create table with name Product57
(code,name,price,qty)
===================================================================
faq:
define ResultSet?
=>ResultSet is an interface from [Link] package.
=>we use executeQuery() method to create implementation object for
ResultSet-Interface
=>This ResultSet-Object will hold the result generated from select
queries.
syntax:
ResultSet rs = [Link]("select-queries");
====================================================================
Ex-program:
Construct JDBC Application to read Customer details from Console input
and insert into Customer57-table
Program : [Link]
package test;
import [Link].*;
import [Link].*;
public class DBCon2
{
public static void main(String[] args)
{
Scanner s = new Scanner([Link]);
try(s;){
try {
[Link]("Enter the CustId:");
String cId = [Link]();
[Link]("Enter the CustName:");
String cName = [Link]();
[Link]("Enter the CustCity:");
String city = [Link]();
[Link]("Enter the CustState:");
String state = [Link]();
[Link]("Enter the PinCode:");
int pinCode = [Link]([Link]());
[Link]("Enter the CustMailId:");
String mId = [Link]();
[Link]("Enter the PhNO:");
long phNo = [Link]();
[Link]("[Link]");
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
Statement stm = [Link]();
int k = [Link]
("insert into Customer57
values('"+cId+"','"+cName+"','"+city+"','"+state+"',"+pinCode+",'"+mId+"',"+phNo+")");
if(k>0) {
[Link]("Customer details Inserted Successfully...");
}
[Link]();
}catch(Exception e) {[Link]();}
}//end of try-with-resource
}
}
o/p:
Enter the CustId:
A234
Enter the CustName:
Alex
Enter the CustCity:
Hyd
Enter the CustState:
TS
Enter the PinCode:
65432
Enter the CustMailId:
a@[Link]
Enter the PhNO:
7676761234
Customer details Inserted Successfully...
=====================================================================
Assignment:
Construct JDBC Application to read Product-Details from Console and
insert into Product57-table
======================================================================
Dt : 4/11/2023
Ex-program:
Construct JDBC Application to display Customer Details based on CustId.
Program : [Link]
package test;
import [Link].*;
import [Link].*;
public class DBCon3
{
public static void main(String[] args)
{
Scanner s = new Scanner([Link]);
try(s;){
try {
[Link]("Enter the CustId:");
String cId = [Link]();
[Link]("[Link]");
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
Statement stm = [Link]();
ResultSet rs = [Link]
("select * from Customer57 where cid='"+cId+"'");
if([Link]()) {
[Link]([Link](1)+"\t"+
[Link](2)+"\t"+[Link](3)+"\t"+
[Link](4)+"\t"+[Link](5)+
"\t"+[Link](6)+"\t"+
[Link](7));
}else {
[Link]("Invalid CustId...");
}
[Link]();
}catch(Exception e) {[Link]();}
}//end of try with resource
}
}
o/p:
Enter the CustId:
E111
E111 Ram Hyd TS 612345 r@[Link] 9898981234
====================================================================
Assignment:
Construct JDBC Application to display Product-details based on ProdCode.
=====================================================================
Assignment:
Create DB table with name : BookDetails57
(code,name,author,price,qty)
Prog-1 : Insert BookDetails
Prog-2 : Display All Book Details
Prog-3 : Display Book Details based on BookCode
================================================================
Dt : 6/11/2023
[Link]:
=>PreparedStatement is an interface from [Link] package and which is
used to execute normal queries with IN Parameters.
=>we use prepareStatement() method from 'Connection' interface to create
implementation object for 'PreparedStatement' interface.
syntax:
PreparedStatement ps = [Link]("query-structure");
(i)executeQuery():
=>executeQuery() method is used to execute select-queries.
Method Signature:
public abstract [Link] executeQuery()
throws [Link];
syntax:
ResultSet rs = [Link]();
(ii)executeUpdate():
=>executeUpdate() method is used to execute NonSelect-queries.
Method Signature:
public abstract int executeUpdate() throws [Link];
syntax:
int k = [Link]();
---------------------------------------------------------------------
Ex-program:
Construct JDBC Application to perform the following operations on DB-table
Product57 based on User Choice:
[Link]
[Link]
[Link]
[Link](price-qty)
[Link]
DB-table : Product57
Program : [Link]
package test;
import [Link].*;
import [Link].*;
public class DBCon3
{
public static void main(String[] args)
{
Scanner s = new Scanner([Link]);
try(s;){
try {
[Link]("Enter the CustId:");
String cId = [Link]();
[Link]("[Link]");
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
Statement stm = [Link]();
ResultSet rs = [Link]
("select * from Customer57 where cid='"+cId+"'");
if([Link]()) {
[Link]([Link](1)+"\t"+
[Link](2)+"\t"+[Link](3)+"\t"+
[Link](4)+"\t"+[Link](5)+
"\t"+[Link](6)+"\t"+
[Link](7));
}else {
[Link]("Invalid CustId...");
}
[Link]();
}catch(Exception e) {[Link]();}
}//end of try with resource
}
}
o/p:
****Choice*****
[Link]
[Link]
[Link]
[Link](price-qty)
[Link]
[Link]
Enter the Choice:
1
====Enter Product Details===
Enter ProdCode:
A111
Enter ProdName:
Mouse
Enter ProdPrice:
1200
Enter ProdQty:
12
Product added Successfully..
****Choice*****
[Link]
[Link]
[Link]
[Link](price-qty)
[Link]
[Link]
Enter the Choice:
1
====Enter Product Details===
Enter ProdCode:
A222
Enter ProdName:
CDR
Enter ProdPrice:
1600
Enter ProdQty:
15
Product added Successfully..
****Choice*****
[Link]
[Link]
[Link]
[Link](price-qty)
[Link]
[Link]
Enter the Choice:
------------------------------------------------------------------
Diagram:
=====================================================================
Dt : 7/11/2023
package test;
import [Link].*;
import [Link].*;
try(s;){
try {
[Link]("[Link]");
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
while(true)
[Link]("****Choice*****");
[Link]("[Link]"
+ "\t\[Link]"
+ "\t\[Link]"
+ "\t\[Link](price-qty)"
+ "\t\[Link]"
+ "\t\[Link]");
switch(choice)
case 1:
[Link]("Enter ProdCode:");
String pC = [Link]();
[Link]("Enter ProdName:");
String pN = [Link]();
[Link]("Enter ProdPrice:");
float pP = [Link]([Link]());
[Link]("Enter ProdQty:");
int pQ = [Link]([Link]());
[Link](1, pC);
[Link](2, pN);
[Link](3, pP);
[Link](4, pQ);
int k = [Link]();//Execution
if(k>0) {
break;
case 2:
while([Link]())
[Link]([Link](1)+"\t"+
[Link](2)+"\t"+
[Link](3)+"\t"+
[Link](4));
break;
case 3:
if([Link]()) {
[Link]([Link](1)+"\t"+
[Link](2)+"\t"+
[Link](3)+"\t"+
[Link](4));
}else {
[Link]("Invalid ProdCode...");
break;
case 4:
[Link](1, pC2);
if([Link]()) {
[Link]("Old Price:"+[Link](3));
[Link]("Existing Qty:"+[Link](4));
[Link](1, nPrice);
[Link](2, nQty);
[Link](3, pC2);
int k2 = [Link]();
if(k2>0) {
}else {
[Link]("Invalid ProdCode...");
}
break;
case 5:
[Link](1, pC3);
if([Link]()) {
[Link](1, pC3);
int k4 = [Link]();
if(k4>0) {
}else {
[Link]("Invalid ProdCode...");
break;
case 6:
[Link]("Operations Stopped...");
[Link](0);
default:
[Link]("Invalid Choice...");
}//end of switch
}//end of loop
}//end of try
catch(Exception e)
[Link]();
o/p:
****Choice*****
[Link]
[Link]
[Link]
[Link](price-qty)
[Link]
[Link]
A222
****Choice*****
[Link]
[Link]
[Link]
[Link](price-qty)
[Link]
[Link]
****Choice*****
[Link]
[Link]
[Link]
[Link](price-qty)
[Link]
[Link]
Operations Stopped...
==================================================================
Assignment:
Step-1 : Construct DB table with name Employee57
(eid,ename,edesg,bsal,totsal)
[Link]
[Link]
[Link]
[Link](bSal)
[Link]
Note:
totSal = bSal+hra+da;
da = 61% of bSal
========================================================================
Dt : 8/11/2023
*imp
ResultSet in JDBC:
=>ResultSet is an interface from [Link] package and which is instantiated
using executeQuery() method.
define 'type'?
=>'type' specifies the movement of Cursor on ResultSet object.
=>ResultSet provides the following fields related to 'type':
public static final int TYPE_FORWARD_ONLY;------>1003
public static final int TYPE_SCROLL_INSENSITIVE;---->1004
public static final int TYPE_SCROLL_SENSITIVE;------>1005
define 'mode'?
=>'mode' specifies the action to be performed on ResultSet Object.
=>ResultSet provides the following fields related to 'mode':
public static final int CONCUR_READ_ONLY;---->1007
public static final int CONCUR_UPDATABLE;---->1008
Note:
=>In 'TYPE_SCROLL_INSENSITIVE',the background buffer is not modified.
=>In 'TYPE_SCROLL_SENSITIVE',the backgound buffer is modified.
--------------------------------------------------------------------
=>The following are some important method to control cursor on
Scrollable ResultSet object:
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]():
=>afterLast() method will move cursor after the last row of ResultSet
[Link]():
=>beforeFirst() method will move the cursor before the first row of
ResultSet
[Link]():
=>last() method make the cursor point to the last row of ResultSet.
[Link]():
=>first() method make the cursor point to the first row of ResultSet.
[Link]():
=>previous() method will move the cursor in backward direction.
[Link]():
=>next() method will move the cursor in forward direction.
[Link](int):
=>absolute(int) method is used move the cursor to the specified row
number on the ResultSet object
[Link]():
=>relative() method is used to move the cursor from current position
to forward or backward by taking incre/decre value as parameter.
Ex:
[Link](+2);
[Link](-4);
----------------------------------------------------------------
Ex-1:
program : [Link]
package test;
import [Link].*;
public class DBCon5 {
public static void main(String[] args) {
try {
[Link]("[Link]");
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
Statement stm = [Link]
(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
/*
[Link](ResultSet.TYPE_FORWARD_ONLY);
[Link](ResultSet.TYPE_SCROLL_INSENSITIVE);
[Link](ResultSet.TYPE_SCROLL_SENSITIVE);
[Link](ResultSet.CONCUR_READ_ONLY);
[Link](ResultSet.CONCUR_UPDATABLE);
*/
ResultSet rs = [Link]
("select * from Customer57");
[Link]();
//Cursor pointing after the last row
[Link]("****Details****");
while([Link]())
{
[Link]([Link](1)+"\t"+
[Link](2)+"\t"+[Link](3)+
"\t"+[Link](4)+"\t"+
[Link](5)+"\t"+[Link](6)+"\t"+
[Link](7));
}
[Link]("====row-2=====");
[Link](2);
[Link]([Link](1)+"\t"+
[Link](2)+"\t"+[Link](3)+
"\t"+[Link](4)+"\t"+
[Link](5)+"\t"+[Link](6)+"\t"+
[Link](7));
[Link]("====relative(+2)=====");
[Link](+2);
[Link]([Link](1)+"\t"+
[Link](2)+"\t"+[Link](3)+
"\t"+[Link](4)+"\t"+
[Link](5)+"\t"+[Link](6)+"\t"+
[Link](7));
}catch(Exception e) {[Link]();}
}
}
o/p:
****Details****
B123 RETY Hyd TS 61234 r@ 6767671234
A234 Alex Hyd TS 65432 a@[Link] 7676761234
E22 Raj Hyd TS 612345 rj@[Link] 7878781234
E111 Ram Hyd TS 612345 r@[Link] 9898981234
====row-2=====
E22 Raj Hyd TS 612345 rj@[Link] 7878781234
====relative(+2)=====
B123 RETY Hyd TS 61234 r@ 6767671234
-----------------------------------------------------------------
Ex-2:
Program : [Link]
package test;
import [Link].*;
public class DBCon6 {
public static void main(String[] args) {
try {
[Link]("[Link]");
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
PreparedStatement ps = [Link]
("select * from Product57",1004,1007);
ResultSet rs = [Link]();
[Link]();
[Link]([Link](1)+"\t"+
[Link](2)+"\t"+[Link](3)+"\t"+
[Link](4));
}catch(Exception e) {[Link]();}
}
}
o/p:
A111 Mouse 1200.0 12
======================================================================
Dt : 9/11/2023
define 'RowSet'?
=>'RowSet' is an interface from [Link] package and which is extended
from [Link] interface.
java - represents JavaLib
javax - represents Extented-JavaLib
=>RowSet object will hold result-set data.
=>RowSet categorized into two types:
[Link]
[Link]
Hierarchy of RowSet:
--------------------------------------------------------------------
faq:
define 'RowSetFactory'?
=>'RowSetFactory' is an interface from [Link] package and
which provide the following method to create implementions for
'RowSet'.
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
=>we use newFactory() method from 'RowSetProvider' class to create
implementation object for 'RowSetFactory' interface.
syntax:
RowSetFactory rsf = [Link]();
---------------------------------------------------------------------
[Link]:
=>JdbcRowSet will hold data retrieved from DB-product and connection
to DB-product is not dis-connected automatically.
syntax:
JdbcRowSet jrs = [Link]();
[Link]:
=>CachedRowSet also hold the data retrieved from DB-product,but
Connection to DB-Product is closed automatically.
syntax:
CachedRowSet crs = [Link]();
--------------------------------------------------------------------
Note:
(i)FilteredRowSet will hold data retrieved based on Condition,which
means holds filtered data.
(ii)JoinRowSet will hold data by joining multiple RowSet-Objects
=====================================================================
Program : [Link]
package test;
import [Link].*;
import [Link].*;
public class DBCon7 {
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
try(s;){
try {
RowSetFactory rsf = [Link]();
//RowSetFactory Object created
[Link]("****Choice****");
[Link]("\[Link]"
+ "\n\[Link]");
[Link]("Enter the Choice:");
int choice = [Link]();
switch(choice)
{
case 1:
JdbcRowSet jrs = [Link]();
//JdbcRowSet Object created
[Link]("jdbc:oracle:thin:@localhost:1521:xe");
[Link]("system");
[Link]("manager");
[Link]("select * from Product57");
[Link]();
while([Link]()) {
[Link]([Link](1)+"\t"
+[Link](2)+"\t"
+[Link](3)+"\t"
+[Link](4));
}
[Link]();
break;
case 2:
CachedRowSet crs = [Link]();
//CachedRowSet Object
[Link]("jdbc:oracle:thin:@localhost:1521:xe");
[Link]("system");
[Link]("manager");
[Link]("select * from Product57");
[Link]();
while([Link]()) {
[Link]([Link](1)+"\t"
+[Link](2)+"\t"
+[Link](3)+"\t"
+[Link](4));
}
[Link]();
break;
default:
[Link]("Invalid Choice...");
}//end of switch
}catch(Exception e) {[Link]();}
}//end of try with resource
}
}
=======================================================================
Dt : 10/11/2023
Assignment:
DB table : UserReg57
(uname,pword,fname,lname,addr,mid,phN)
primary key : uname
[Link]-Registration:
=>read all user details from console and Insert into DB table
o/p:
User registered Successfully...
[Link]-Registration
[Link]-Login
define Functions?
=>The part of program which is executed out of main-program in C-lang
is known as Function.
define Methods?
=>The functions which are declared only inside the class in Java-Lang
are known as Methods.
--------------------------------------------------------------------
faq:
define Procedure?
=>Procedure is a set-of-queries executed on DB product,and which
willnot return any value after execution.
(Procedure means NonReturn_type)
structure of procedure:
faq:
define Function?
=>Function is also a set-of-queries executed on DB product and which
will return value after execution.(Function means Return_type)
structure of Function:
EmpData57(eid,ename,edesg)
EmpSalary57(eid,bsal,totsal)
Layout:
Program : [Link]
package test;
import [Link].*;
import [Link].*;
public class DBCon8 {
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
try(s;){
try {
[Link]("[Link]");
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
CallableStatement cs = [Link]
("{call InsertDetails57(?,?,?,?,?)}");
}catch(Exception e) {[Link]();}
}//try with resource
}
}
o/p:
Enter the empId:
A111
Enter the empName:
Raj
Enter the empDesg:
SE
Enter the empBSal:
120000
EmpDetails inserted Successfully...
DBTables:
Layout:
Program : [Link]
package test;
import [Link].*;
import [Link].*;
public class DBCon9 {
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
try(s;){
try {
[Link]("[Link]");
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
CallableStatement cs = [Link]
("{call RetrieveDetails57(?,?,?,?,?)}");
[Link]();
[Link]("====EmpDetails====");
[Link]("EmpId:"+eId);
[Link]("EmpName:"+[Link](2));
[Link]("EmpDesg:"+[Link](3));
[Link]("EmpBSal:"+[Link](4));
[Link]("EmpTotSal:"+[Link](5));
}catch(Exception e) {[Link]();}
}//try with resource
}
}
o/p:
Enter the EmpId:
A111
====EmpDetails====
EmpId:A111
EmpName:Raj
EmpDesg:SE
EmpBSal:120000
EmpTotSal:304800.0
=================================================================
Dt : 15/11/2023
faq:
define registerOutParameter() method?
=>registerOutParameter() method will specify the type of value to be
stored in Parameter-index-field
syntax:
[Link](para_index,[Link]);
Note:
=>'[Link]' is a class holding SQL-DataTypes and which are
represented part of registerOutParameter() method.
Ex:
public static final int INTEGER;
public static final int BIGINT;
public static final int FLOAT;
public static final int VARCHAR;
...
--------------------------------------------------------------------
Assignment-1:
step-1 : Construct the following DB tables
CustData57(cid,cname)
CustAddress57(cid,city,state,pincode)
CustContact57(cid,mid,phno)
Program : [Link]
package test;
import [Link].*;
import [Link].*;
public class DBCon10 {
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
try(s;){
try {
[Link]("[Link]");
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
CallableStatement cs = [Link]
("{call ?:=RetrieveTotSal57(?)}");
[Link]("Enter EmpId:");
String eId = [Link]();
[Link](1, [Link]);
[Link](2, eId);
[Link]();
[Link]("====Details====");
[Link]("Emp-Id:"+eId);
[Link]("Emp-TotSal:"+[Link](1));
}catch(Exception e) {[Link]();}
}//end of try with resource
}
}
o/p:
Enter EmpId:
A111
====Details====
Emp-Id:A111
Emp-TotSal:304800.0
Diagram:
========================================================
Assignment-3:
step-1 : Construct Function to retrieve PhoneNo based on CustId
step-2 : Construct JDBC Application to execute Function
==========================================================
*imp
Transaction Management in JDBC:
define Transaction?
=>set-of-statements executed on a resource or resources using ACID
properties is known as Transaction.
A - Atomicity
C - Consistency
I - Isolation
D - Durability
A - Atomicity
=>Atomicity means all statements in the Transaction are completed
Successfully or not happened Successfully
C - Consistency
=>The resource state which is selected by the user,remains same
until the transaction is completed is known as Consistency.
I - Isolation
=>The process of running multiple users independently is known as
Isolation process.
D - Durability
=>The process of storing Transaction details and making it available
to user,is known as Durability.
==============================================================
Dt : 16/11/2023
faq:
define Transaction Management?
=>The process of controling the transaction from starting to ending is
known as Transaction Management.
Note:
=>JDBC Applications will perform auto-commit operation,which means
Commit-operation is performed automatically
=>Part of Transaction Management the auto-commit operation must be
stopped,which means we perform commit-operation manually.
----------------------------------------------------------------
=>To perform Transaction Management,we use the following methods:
(a)getAutoCommit()
(b)setAutoCommit()
(c)setSavepoint()
(d)releaseSavepoint()
(e)commit()
(f)rollback()
(a)getAutoCommit():
=>getAutoCommit() method is used know the status of commit-operation
syntax:
boolean b1 = [Link]();
(b)setAutoCommit():
=>setAutoCommit() method is used to set auto-commit-operation to 'false'
syntax:
[Link](false);
(c)setSavepoint():
=>setSavepoint() method is used to take one status-point to perform
rollback-operation when transaction-failed
syntax:
Savepoint sp = [Link]();
(d)releaseSavepoint():
=>releaseSavepoint() method is used to delete savepoints.
syntax:
[Link](sp);
(e)commit():
=>commit() method is used to save the data from temporary buffer to DB
product permanently.
syntax:
[Link]();
(f)rollback():
=>rollback() method is used to perform rollback-operation.
syntax:
[Link](sp);
---------------------------------------------------------------
Ex-program:(Demonstrating Transaction Management)
DB Table : BankCutomer57(accno,cname,bal,acctype)
primary key : accno
Program : [Link]
package test;
import [Link].*;
import [Link].*;
public class DBCon11 {
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
try(s;){
try {
[Link]("[Link]");
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
[Link]("Commit-status :
"+[Link]());
[Link](false);
[Link]("Commit-status :
"+[Link]());
PreparedStatement ps1 = [Link]
("select * from BankCustomer57 where accno=?");
PreparedStatement ps2 = [Link]
("update BankCustomer57 set bal=bal+? where
accno=?");
Savepoint sp = [Link]();
[Link]("Enter the HomeAccNo:");
long hAccNo = [Link]();
[Link](1, hAccNo);
ResultSet rs1 = [Link]();
if([Link]()) {
float bl = [Link](3);
[Link]("Enter benifiecieryAccNo:");
long bAccNo = [Link]();
[Link](1, bAccNo);
ResultSet rs2 = [Link]();
if([Link]()) {
[Link]("Enter the amt to be
transferred:");
int amt = [Link]();
if(amt<=bl) {
[Link](1, -amt);
[Link](2, hAccNo);
int k = [Link]();//Buffer
Updated
[Link](1, +amt);
[Link](2, bAccNo);
int z = [Link]();//Buffer
Updated
}else {
[Link]("Insuffiecient
fund...");
}
}else {
[Link]("Invalid bAccNo...");
}
}else {
[Link]("Invalid homeAccNo...");
}
}catch(Exception e) {[Link]();}
}//end of try with resource
}
}
o/p:
Commit-status : true
Commit-status : false
Enter the HomeAccNo:
6123456
Enter benifiecieryAccNo:
313131
Enter the amt to be transferred:
3000
Transaction Successfull..
Note:
step-1 : set auto-commit-operation to false
step-2 : Take savepoint to perform rollback
step-3 : Execute all sub-statements in Transaction
step-4 : Check all sub-statements are executed successfully or not
step-5 : If all sub-statements are executed successfully then perform
commit-operation,else perform rollback-operation
==================================================================
Assignment:
Update above application by converting else-block messages to catch-block
messages(exception-messages)
=====================================================================
Dt : 17/11/2023
*imp
Connection Pooling in JDBC:
=>The process of organizing multiple pre-initialized database connections
among multiple users,is known as Connection Pooling Concept.
Note:
=>In realtime [Link]<E> is used to hold multiple
Pre-Initialized Database Connections(Connection-Objects)
Hierarchy of Vector<E>:
------------------------------------------------------------
Layout:
Ex-program:
[Link]
package test;
import [Link].*;
import [Link].*;
public class ConnectionPooling
{
public String url,uName,pWord;
public ConnectionPooling(String url,String uName,String pWord)
{
[Link]=url;
[Link]=uName;
[Link]=pWord;
}
public Vector<Connection> v = new Vector<Connection>();
public void addConnectionsToPool()
{
try {
while([Link]()<5)
{
[Link]("Pool is Not full....");
Connection con = [Link]
(url,uName,pWord);
[Link](con);//Adding Connection to Pool
[Link](con);
}//end of loop
if([Link]()==5)
{
[Link]("pool is full...");
}
}catch(Exception e) {[Link]();}
}//end of loop
public Connection userConnectionFromPool()
{
Connection con = [Link](0);
[Link](0);
return con;
}//end of method
public void returnConnectionToPool(Connection con)
{
[Link](con);//Adding Connection back to pool
[Link]("Connection added back to pool...");
}//end of method
}
[Link](MainClass)
package test;
import [Link].*;
public class DBCon12 {
public static void main(String[] args) {
try {
ConnectionPooling cp =
new ConnectionPooling
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
[Link]();
[Link]("Size of Pool : "+[Link]());
[Link]("*****User-1*****");
Connection con1 = [Link]();
[Link](con1);
[Link]("Size of Pool : "+[Link]());
[Link]("****User-2****");
Connection con2 = [Link]();
[Link](con2);
[Link]("Size of Pool : "+[Link]());
[Link]("****User-1*****");
[Link](con1);
[Link]("Size of Pool : "+[Link]());
[Link]("****User-2*****");
[Link](con2);
[Link]("Size of Pool : "+[Link]());
[Link]("====Connections=====");
[Link]((k)->
{
[Link](k);
});
}catch(Exception e) {[Link]();}
}
}
o/p:
Pool is Not full....
[Link].T4CConnection@3159c4b8
Pool is Not full....
[Link].T4CConnection@525f1e4e
Pool is Not full....
[Link].T4CConnection@75f9eccc
Pool is Not full....
[Link].T4CConnection@67e2d983
Pool is Not full....
[Link].T4CConnection@5d47c63f
pool is full...
Size of Pool : 5
*****User-1*****
[Link].T4CConnection@3159c4b8
Size of Pool : 4
****User-2****
[Link].T4CConnection@525f1e4e
Size of Pool : 3
****User-1*****
Connection added back to pool...
Size of Pool : 4
****User-2*****
Connection added back to pool...
Size of Pool : 5
====Connections=====
[Link].T4CConnection@75f9eccc
[Link].T4CConnection@67e2d983
[Link].T4CConnection@5d47c63f
[Link].T4CConnection@3159c4b8
[Link].T4CConnection@525f1e4e
================================================================
Dt : 18/11/2023
*imp
process of Connection Pooling:
[Link] Object
[Link] Object
[Link] Object
[Link] Object
[Link] Object
(i)Scrollable ResultSet Object
(ii)NonScrollable ResultSet Object
[Link] Object
(i)JdbcRowSet Object
(ii)CachedRowSet Object
=>WebRowSet Object
(i)FilteredRowSet Object
(ii)JoinRowSet Object
[Link] Object
[Link] Object
[Link] Object
[Link] Object
Diagram:
--------------------------------------------------------------------
faq:
define Metadata?
=>The data which is holding information about other data is known as
Metadata.
=>The following are some important metadata components in JDBC:
[Link]
[Link]
[Link]
[Link]
[Link]:
=>DatabaseMetaData object will hold information about Connection-Object.
syntax:
DatabaseMetaData dmd = [Link]();
[Link]:
=>ParameterMetaData object will hold information about PreparedStatement
Object
syntax:
ParameterMetaData pmd = [Link]();
[Link]:
=>ResultSetMetaData object will hold information about ResultSet Object.
syntax:
ResultSetMetaData rsmd = [Link]();
[Link]:
=>RowSetMetaData Object will hold information about RowSet Objects
syntax:
RowSetMetaData rsd = (RowSetMetaData)[Link]();
Program : [Link]
package test;
import [Link].*;
import [Link].*;
import [Link];
public class DBCon13 {
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
try(s;){
try {
[Link]("[Link]");
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
[Link]("***DatabaseMetaData****");
DatabaseMetaData dmd = [Link]();
[Link]("DB
Version:"+[Link]());
[Link]("DB Driver:"+[Link]());
PreparedStatement ps = [Link]
("select fname,mid,phno from Admin56 where uname=?
and pword=?");
[Link]("***ParameterMetaData****");
ParameterMetaData pmd = [Link]();
[Link]("Count of
Parameters:"+[Link]());
[Link]("Enter the UserName:");
String uName = [Link]();
[Link]("Enter the PassWord:");
String pWord = [Link]();
[Link](1, uName);
[Link](2, pWord);
ResultSet rs = [Link]();
[Link]("****ResultSetMetaData****");
ResultSetMetaData rsmd = [Link]();
int count = [Link]();
[Link]("Count of Column:"+count);
for(int i=1;i<=count;i++)
{
String nm = [Link](i);
[Link]("Column Name : "+nm);
}//end of loop
[Link]("====Details====");
if([Link]()) {
[Link]([Link](1)+"\t"+
[Link](2)+"\t"+[Link](3));
}//end of if
else {
[Link]("Inavlid UName or PWord..");
[Link](0);
}
//RowSetMetaData rsd =
(RowSetMetaData)[Link]();
}catch(Exception e) {[Link]();}
}//end of try with resource
}
}
o/p:
***DatabaseMetaData****
DB Version:11
DB Driver:Oracle JDBC driver
***ParameterMetaData****
Count of Parameters:2
Enter the UserName:
nit.v
Enter the PassWord:
mzu672
****ResultSetMetaData****
Count of Column:3
Column Name : FNAME
Column Name : MID
Column Name : PHNO
====Details====
Venkat v@[Link] 9898981234
===========================================================
Dt : 20/11/2023
*imp
Streams with Database:
define Stream?
=>The contineous flow of data is known as Stream.
Types of Streams:
=>Streams in Java are categorized into two types:
(i)Byte Stream
(ii)Character Stream
(i)Byte Stream:
=>The contineous flow of data in the form of 8-bits is known as
Byte Stream or Binary Stream.
=>Byte Stream supports all multi-media data formats like Audio,Video,
Image,Animation and Text.
(ii)Character Stream:
=>The contineous flow of data in the form of 16-bits is known as
Character Stream or Text Stream.
=>Character Stream is preferable for Text data and not preferable
for Audio,Video,Image and Animations files.
faq:
define Input Stream?
=>The stream coming into JavaProgram is known as Input Stream.
faq:
define Output Stream?
=>The stream going outof JavaProgram is known as Output Stream
---------------------------------------------------------------------
=>The following SQL-types will support Stream data:
(a)BLOB
(b)CLOB
(a)BLOB:
=>BLOB stands for 'Binary Large OBjects' and which support Byte
Stream data.
(b)CLOB:
=>CLOB stands for 'Character Large OBjects' and which support
Character Stream data.
--------------------------------------------------------------------
*imp
Construct JDBC Application to Store Image onto DB product:
step-1 : Create table with name StreamTab57 from SQLCommandLine
Diagram:
======================================================================
*imp
Construct JDBC Application to retrieve image from DB Product:
Program : [Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
public class DBCon15 {
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
try(s;){
try {
[Link]("[Link]");
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
PreparedStatement ps = [Link]
("select * from StreamTab57 where id=?");
[Link]("Enter the id:");
String id = [Link]();
[Link](1, id);
ResultSet rs = [Link]();
if([Link]()) {
Blob b = [Link](2);
byte by[] = [Link](1, (int)[Link]());
[Link]("Enter the fPath&fName:(Destination)");
File f = new File([Link]());
FileOutputStream fos = new FileOutputStream(f);
[Link](by);
[Link]("Image retrieved Successfully...");
[Link]();
}else {
[Link]("Invalid id...");
}
[Link]();
}catch(Exception e) {[Link]();}
}//end of try with resource
}
}
o/p:
Enter the id:
A111
Enter the fPath&fName:(Destination)
D:\Images\[Link]
Image retrieved Successfully...
Diagram:
======================================================================
Dt : 21/11/2023
faq:
define FileInputStream?
=>FileInputStream is a class from [Link] package and which is used to
find the file and opens the file to read byte-stream data.
syntax:
FileInputStream fis = new FileInputStream("fPath&fName");
faq:
define FileOutputStream?
=>FileOutputStream is also a class from [Link] package and which is
used to create a new file and opens the file to write byte-stream
data.
syntax:
FileOutputStream fos = new FileOutputStream("fPath&fName");
faq:
define 'File' class?
=>'File' class is from [Link] package and which is used to find the
properties of file like file_length,file_path,file_exists or not,...
syntax:
File f = new File("fPath&fname");
faq:
define Blob?
=>'Blob' is an interface from [Link] package and which supports to
retrieve byte-stream data from the DB Product.
=>The following are some important methods from 'Blob' interface:
public abstract long length() throws [Link];
public abstract byte[] getBytes(long, int)
throws [Link];
===================================================================
faq:
define 'Wrapper'?
=>'Wrapper' is an interface from [Link] package and which is Parent
interface of '[Link]' interface and '[Link]'
interface.
=>This 'Wrapper' supports binding components to Objects.
(Supports binding process)
=====================================================================
faq:
define 'AutoCloseable'?
=>The resources which are used in try-with-resource statement must be
implementations of 'AutoCloseable' interface,then the resources are
closed automatically.
Note:
=>Connection,Statement,PreparedStatement and CallableStatement can be
used part of try-with-resource statement.
=====================================================================
Dt : 22/11/2023
Ex-program:
JDBC Application to execute create-query from Java Program.
Program : [Link]
package maccess;
import [Link].*;
import [Link].*;
public class DBCon16 {
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
try(s;){
try {
[Link]("[Link]");
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
Statement stm = [Link]();
[Link]("Enter query(Create/insert/update/delete)");
String qr = [Link]();
int k = [Link](qr);
[Link]("The value k:"+k);
if(k>=0) {
[Link]("qurey executed...");
}
[Link]("Enter select query:");
String qr2 = [Link]();
ResultSet rs = [Link](qr2);
while([Link]()) {
[Link]([Link](1)+"\t"+
[Link](2));
}
}catch(Exception e) {[Link]();}
}//end of try with resource
}
}
o/p:
Enter query(Create/insert/update/delete)
insert into Emp7 values('A22','Alex')
The value k:1
qurey executed...
Enter select query:
select * from Emp7
A11 Raj
A22 Alex
===================================================================
faq:
define Batch Processing in JDBC?
=>The process of collecting multiple queries as batch and executing
at-a-time on DB product,is known as Batch Processing.
=>The queries declared in batch must be only NonSelect queries,because
of this reason Batch processing is also known as Batch Update
processing
=>we use the following methods in Batch Processing:
(a)addBatch()
(b)executeBatch()
(c)clearBatch()
(a)addBatch():
=>addBatch() method is used to add query to the batch.
Method Signature:
public abstract void addBatch([Link])throws [Link];
(b)executeBatch():
=>executeBatch() method executed execute batch on DB product.
Method Signature:
public abstract int[] executeBatch()throws [Link];
(c)clearBatch():
=>clearBatch() method is used to delete all queries from the batch and
destroy the batch.
Method Signature:
public abstract void clearBatch() throws [Link];
---------------------------------------------------------------
Ex-program:
Batch:
query-1 : create table emp9(id,name)
query-2 : create table cust9(id,name,phno)
query-3 : insert into emp9
query-4 : insert into cust9
Program : [Link]
package maccess;
import [Link].*;
import [Link].*;
public class DBCon17 {
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
try(s;){
try {
[Link]("[Link]");
Connection con = [Link]
("jdbc:oracle:thin:@localhost:1521:xe",
"system","manager");
Statement stm = [Link]();
[Link]("Enter number of queries to be added to batch:");
int n = [Link]([Link]());
[Link]("Enter "+n+" queries..");
for(int i=1;i<=n;i++)
{
[Link]("Enter the query-"+i);
String qr = [Link]();
[Link](qr);
}//end of loop
int k[] = [Link]();
for(int i : k) {
[Link]("value i : "+i);
[Link]("query executed...");
}//end of loop
[Link]();
}catch(Exception e) {[Link]();}
}//end of try
}
}
o/p:
Enter number of queries to be added to batch:
4
Enter 4 queries..
Enter the query-1
create table Emp9(id varchar2(10),name varchar2(15),primary key(id))
Enter the query-2
create table Cust9(id varchar2(10),name varchar2(15),phno number(15),primary key(id))
Enter the query-3
insert into emp9 values('A11','Raj')
Enter the query-4
insert into cust9 values('A11','Raj',989898)
value i : 0
query executed...
value i : 0
query executed...
value i : 1
query executed...
value i : 1
query executed...
=================================================================
Note:
(i)we can perform batch processing using 'Statement' and
'PreparedStatement'
(ii)Batch Processing using 'Statement' we can perform operations on
Multiple DB tables.
(iii)Batch Processing using 'PreparedStatement' we can perform operations
only on single DB Table.
================================================================
faq:
wt is the diff b/w
(i)Procedures
(ii)Batch Processing
Advantage:
=>Type-1 driver will connect to any database.
DisAdvatage:
=>Type-1 driver will degrade the performance of an application,because
more conversions are available and which consumes more execution time.
Note:
=>From Java8 version onwards Type-1 driver support is not available.
---------------------------------------------------------------
faq:
define ODBC driver?
=>ODBC stands for Open DataBase Connectivity and this ODBC driver will
support connect to any type of database.
=>ODBC driver internally having c/c++ code and which is Platform
dependent driver.
=======================================================================
Dt : 23/11/2023
[Link] API driver(Type-2):
=>Native API driver will take the support of Database Client Libraries
to establish connection to Database product.
=>when we use Native API driver then the Client Computer must be
installed with Database related Client Libraries.
Diagram:
Advantage:
=>In Type-2 driver ODBC-driver is not involved and which saves the
execution time and generate HighPerformance of an application.
DisAdvantage:
=>The Client Computer must be installed with Database related Client
libraries and which makes the application Database dependent.
===============================================================
[Link] Protocol driver(Type-3):
=>Network Protocol driver will take the support of Middleware Servers
to Communicate database product.
Diagram:
Advantage:
=>Middleware Servers will hold database related code.
=>ODBC-driver and Database related Client libraries are not involved.
DisAdvantage:
=>In Network Protocol driver,the network related components and code
invloved in execution process and degrade the performance of an
application.
======================================================================
[Link] driver(Type-4)
=>Thin driver will take the support of Database Network protocol to
Communicate with database product directly.
=>Thin driver is Pure Java Driver and Platform independent driver,
and which generate HighPerformance of an application.
Diagram:
Advantage:
=>HighPerformance driver
=>ODBC-driver,database related Client Libraries and MiddleWare Servers
are not involved.
======================================================================
*imp
Summary of Objects created from CoreJava:
[Link] defined Class Objects
[Link]-Objects
[Link]-Objects
[Link]-Objects
[Link]<E>-Objects
[Link]<K,V>-Objects
[Link]<E>-Objects
Coding Rule:
=>To perform Serialization process the class must be implemented from
'[Link]' interface.
===================================================================
=>Based on Serialization process the Objects in Java are categorized
into two types:
(i)Serializable Objects
(ii)NonSerializable Objects
(i)Serializable Objects:
=>The Objects which are generated from implementation classes of
"[Link]" interface are Serializable Objects.
Ex:
All CoreJava Objects
(ii)NonSerializable Objects:
=>The Objects which are generated from NonImplementation classes of
"[Link]" interface are NonSerializable Objects.
Ex:
All JDBC Objects
==================================================================
faq:
why we have to perform Serialization process?
=>Through Serialization process we can make objects available in the
form of Stream and can be moved on the Network from one location to
another location.
Conclusion:
=>Serializable CoreJava Objects can be moved on the Network directly,
but NonSerializable JDBC Objects cannot be moved on the Network
directly
======================================================================
Dt : 24/11/2023
Java Technology:
=>The process of applying the knowledge for realtime world application
development is known as Technology.
=>Java Technology internally categorized into two parts:
[Link]
[Link]
[Link]:
=>Java is a Language because it is having its own syntax(grammer),
alphabets(programming components) and Construction rules.
[Link]:
=>Java is also a PlatForm,beacuse it is having its own environment
for execution.
=>Java Paltforms are categorized into the following:
(a)JavaSE
(b)JavaEE
(c)JavaME
(a)JavaSE:
=>JavaSE means 'Java Standard Edition' and which is used for NonServer
application development.
=>JavaSE means 'CoreJava+JDBC'
(b)JavaEE:
=>JavaEE means 'Java Enterprise Edition' and which is used for Server
based application Development.
=>Part of JavaEE,AdvJava covers Servet and JSP.
(c)JavaME:
=>JavaME means 'Java Micro Edition' and which is used for Machine and
Mobile related application development.
=>JavaME also known as Machine Edition or Mobile Edition.
=====================================================================
*imp
Servlet Programming:(Part-2)
define Servlet?
=>The platform independent JavaProgram which is executed in Server
environment and interacts with user through WebBrowser is knwon as
Servlet Program or Server Program.
=>Servlet Programs will extent the functionality of Server.
=>Servlet program will accept the request from the User and provides the
response.
Diagram:
------------------------------------------------------------------
faq:
define Web Application?
=>The application which is executed in Web Environment or Internet
environment is known as Web Application.
=>These WebApplications will interact with WebBrowsers.
--------------------------------------------------------------------
=>These Web Applications are loaded to Web-Container of Server for
execution.
------------------------------------------------------------------
faq:
define Server?
=>Server means Service provider,which means accepts the request and
provides the response.
=>Servers are categorized into two types:
[Link] Servers
[Link] Servers
[Link] Servers:
=>Web Servers will have only Web-Container.
=>Web Servers are used to execute Web Applications.
=>Web Servers will accept request from HTTP protocol.
Ex:
Tomcat
[Link] Servers:
=>Application Servers will have both Web-Container and EJB Container
(EJB - Enterprise Java Bean)
=>Applications Servers are used to execute both Web Applications and
Enterprise Applications.
=>Application Servers will request from HTTP,RMI and RPC protocols
(RMI - Remote Method Inovacation)
(RPC - Remote Procedure Call)
Ex:
WebSphere,JBoss,IIS,...
===============================================================
Dt : 25/11/2023
*imp
Installing Web Server(Tomcat Server):
User Name :V
Password : nit
(click on Next)
=================================================================
*imp
Servlet API:
=>'[Link]' package is known as Servlet-API
=>'[Link]' interface is a root of Servlet-Programming or
Servlet-API.
=>The following are some important methods of 'Servlet' interface:
[Link]()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]():
=>we use init() method to perform initialization process,which means
making the programming components ready for service() method.
Method Signature:
public abstract void init([Link])
throws [Link];
[Link]():
=>Using service() method we provide service to user,which means accepts
the request and provides the response.
Method Signature:
public abstract void service([Link],
[Link]) throws [Link],
[Link];
[Link]():
=>we use destroy() method to perform destroying process.
Method Signature:
public abstract void destroy();
Note:
=>init(),service() and destroy() methods are known as Life-cycle methods
and which are executed automatically in the same order.
[Link]():
=>getServletInfo() method is coded with servlet information and which
is not Life-cycle method.
Method Signature:
public abstract [Link] getServletInfo();
[Link]():
=>getServletConfig() method is used get Servlet Configuratiuon details
and which is alos not Life-cycle method.
Method Signature:
public abstract [Link] getServletConfig();
===============================================================
Dt : 28/11/2023
Hierarchy of 'Servlet' interface:
=================================================================
=>In the process of constructing Servlet programs,we use any one of the
following model:
(a)Servlet-program implementing from 'Servlet' interface
(b)Servlet-program extending from 'GenericServlet' AbstractClass
(c)Servlet-program extending from 'HttpServlet' AbstractClass
-------------------------------------------------------
(b)Servlet-program extending from 'GenericServlet' AbstractClass:
=>If the Servlet-program extends from 'GenericServlet' AbstractClass,
then we must construct body for only service() method and remaining
methods are optional methods.
Diagram:
--------------------------------------------------------------------
Conclusion:
=>The Servlet-Objects generated from 'Servlet' interface are
NonSerializable Objects
=>The Servlet-Objects generated from 'GenericServlet' and 'HttpServlet'
are Serializable Objects.
====================================================================
*imp
Construct Servlet Application(Web Application) using IDE Eclipse:
step-1 : Open IDE Eclipse,while opening name the WorkSpace and click
'Launch'
step-2 : Create 'Dynamic Web Project'
[Link]
[Link]
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/dis")
public class DisplayServlet extends GenericServlet
{
@Override
public void init()throws ServletException
{
//NoCode
}
@Override
public void service(ServletRequest req,ServletResponse res)throws
ServletException,IOException
{
PrintWriter pw = [Link]();
[Link]("text/html");
String uName = [Link]("uname");
String mId = [Link]("mid");
[Link]("*****DisplayServlet****");
[Link]("<br>UserName:"+uName);
[Link]("<br>MailId:"+mId);
}
@Override
public void destroy()
{
//NoCode
}
}
[Link]
======================================================================
Dt : 29/11/2023
Execution flow of above application:
[Link]
----------------------------------------------------------------------
ServletContext:
=>ServletContext is an interface from [Link] package and which
is instantiated automatically when Web-Application deployed into
Server.
=>This ServletContext object is loaded with Server Information.
ServletConfig:
=>ServletConfig is an interface from [Link] package and which is
instantiated automatically when Servlet-program loaded for execution.
=>This ServletConfig Object is loaded with Servlet_name.
Note:
=>After ServletConfig Object instantiation completed,then Servlet
Object is created.
=>After Servlet Object creation completed,then we can find three life
cycle methods and executed automatically
ServletRequest:
=>ServletRequest is an interface from [Link] package and which is
instantiated automatically while service()-method execution.
=>This ServletRequest object will hold the data submitted from HTML
forms.
ServletResponse:
=>ServletResponse is an interface from [Link] package and which
is instantiated automatically while service()-method execution.
=>This ServletResponse object is loaded with response data or output
data.
faq:
define getWriter() method?
=>getWriter() method is from ServletResponse and which is used to
create object for "[Link]" Class.
Method Signature:
public abstract [Link] getWriter()
throws [Link];
syntax:
PrintWriter pw = [Link]();
faq:
define setContentType() method?
=>setContentType() method will specify the type of data sending as
output(sending as response).
=>This setContentType() method is also available from 'ServletResponse'
Method Signature:
public abstract void setContentType([Link]);
syntax:
[Link]("text/html");
faq:
define getParameter() method?
=>getParameter() method is used to get the data from ServletRequest
object into Servlet-program.
=>This getParameter() method is from "ServletRequest".
Method Signature:
public abstract [Link] getParameter([Link]);
syntax:
String var = [Link]("para_name");
====================================================================
Assignment-1:
Construct Servlet-Application to read and display Product details.
(code,name,price,qty)
Assignment-2:
Construct Servlet-Application to read and display Customer details.
(CustId,CustName,CustCity,CustState,CustMailId,CustPhNo)
===================================================================
Dt : 1/12/2023
*imp
RequestDispatcher:
=>RequestDispatcher is an interface from [Link] package and which
is used to perform the following Servlet-Communications:
(i)Servlet to Servlet Communication
(ii)Servlet to HTML Communication
(iii)Servlet to JSP Communication
=>Servlet-Communications are categorized into two types:
(a)forward communication
(b)include communication
(a)forward communication:
=>In forward Communication process,ServletProgram1 will take the request
and forwards the request to ServletProgram2,in this process the
response is generated from ServletProgram2.
=>This ServletProgram2 can be replace with HTML file or JSP file.
=>we use forward() method from 'RequestDispatcher' to perform forward
communication process.
Method Signature of forward():
public abstract void forward([Link],
[Link]) throws [Link],
[Link];
Diagram:
-------------------------------------------------------------------
(b)include communication:
=>In include communication process,the ServletProgram1 will take the
request and generate response,but the response is included with the
response of ServletProgram2.
=>This ServletProgram2 can be replaced with HTML file or JSP file.
=>we use include() method from 'RequestDispatcher' to perform include
Communication process.
Method Signature of include():
public abstract void include([Link],
[Link]) throws [Link],
[Link];
Diagram:
======================================================================
=>we use getRequestDispatcher() method from 'ServletRequest' to create
implementation object for 'RequestDispatcher' interface.
Method Signature of getRequestDispatcher();
public abstract [Link]
getRequestDispatcher([Link]);
syntax:
RequestDispatcher rd = [Link]("Servlet-url/HTML/JSP");
[Link](req,res);
[Link](req,res);
================================================================
Ex-Application:(Demonstrating RequestDispatcher)
Layout:
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="choice" method="post">
Enter the Value:<input type="text" name="val"><br>
<input type="submit" value="Factorial" name="s1">
<input type="submit" value="Prime" name="s1">
</form>
</body>
</html>
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/choice")
public class ChoiceServlet extends GenericServlet
{
@Override
public void service(ServletRequest req,ServletResponse res)throws
ServletException,IOException{
String s1 = [Link]("s1");
if([Link]("Factorial")) {
RequestDispatcher rd =
[Link]("xyz");
[Link](req, res);
}else {
RequestDispatcher rd =
[Link]("pqr");
[Link](req, res);
}
}
}
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/xyz")
public class FactorialServlet extends GenericServlet{
@Override
public void service(ServletRequest req,ServletResponse res)throws
ServletException,IOException{
PrintWriter pw = [Link]();
[Link]("text/html");
int n = [Link]([Link]("val"));
int fact=1;
for(int i=n;i>=1;i--)
{
fact=fact*i;
}
[Link]("Factorial : "+fact+"<br>");
RequestDispatcher rd =
[Link]("[Link]");
[Link](req, res);
}
}
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/pqr")
public class PrimeServlet extends GenericServlet{
@Override
public void service(ServletRequest req,ServletResponse res)throws
ServletException,IOException{
PrintWriter pw = [Link]();
[Link]("text/html");
int n = [Link]([Link]("val"));
int count=0;
for(int i=1;i<=n;i++)
{
if(n%i==0)
{
count++;
}
}
if(count==2) [Link]("Prime Number..<br>");
else [Link]("Not Prime Number...<br>");
RequestDispatcher rd =
[Link]("[Link]");
[Link](req, res);
}
}
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
=============================================================
Assignment:
Construct Servlet Application to perform the following operations
Add,Sub,Mul,Div,ModDiv,Greater,Smaller
===============================================================
Dt : 2/12/2023
*imp
JSP Programming:
=>JSP stands for 'Java Server Page' and which is response from Web-App.
=>JSP is more simple when compared with Servlet-programming,because JSP
is tag-based-programming language.
=>In JSP,the programs are saved with (.jsp) as an extention.
=>JSP programs will hold both HTML-Code and Java-Code.
=>JSP used the followimg tags to write Java-code in JSP programs:
[Link] tags
[Link] tags
[Link] tags
[Link] tags:
=>The Scripting tags are used to write JavaCode in JSP programs.
=>These Scripting tags are categorized into the following:
(a)Scriptlet tag
(b)Expression tag
(c)Declarative tag
(a)Scriptlet tag:
=>Scriptlet tag is used to write Normal JavaCode or ServletCode in JSP
programs.
syntax:
<% code %>
(b)Expression tag:
=>Expression tag is used to assign the value to variable or used to
display the data to WebBrowser directly.
syntax:
<%= value/Expression %>
(c)Declarative tag:
=>Declarative tag is used to declare variables and methods in JSP
Programs.
syntax:
<%! Variables;Methods %>
---------------------------------------------------------------
[Link] tags:
=>The tags which are used to specify the directions in translation
process of JSP Programs.
=>Directive tags are categorized into the following:
(a)@page
(b)@include
(c)@taglib
(a)@page:
=>'@page' will specify Langauge used in JSP,contextType,pageEncoding,
importing and so on...
(Specifications about the JSP page)
syntax:
<%@page ... %>
(b)@include:
=>'@include' will specify which page must be included to current running
JSP program
syntax:
<%@include file="File_name"/%>
(c)@taglib:
=>'@taglib' is used to link external libraries to current JSP program.
syntax:
<%@tablib ....%>
---------------------------------------------------------------------
[Link] tags:
=>Action tage used to perform some actions related to JSP programs while
execution process.
=>These Action tage are categorized into the following:
(a)<jsp:include>
(b)<jsp:forward>
(c)<jsp:param>
(d)<jsp:useBean>
(e)<jsp:setProperty>
(f)<jsp:getProperty>
======================================================================
Ex-application:(Demonstrating Communication b/w Servlet and JSP)
Layout:
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="dis" method="post">
ProductCode:<input type="text" name="pcode"><br>
ProductName:<input type="text" name="pname"><br>
ProductPrice:<input type="text" name="pprice"><br>
ProductQty:<input type="text" name="pqty"><br>
<input type="submit" name="Dispaly">
</form>
</body>
</html>
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/dis")
public class ControllerServlet extends GenericServlet{
@Override
public void service(ServletRequest req,ServletResponse res)throws
ServletException,IOException{
RequestDispatcher rd =
[Link]("[Link]");
[Link](req, res);
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String code = [Link]("pcode");
String name = [Link]("pname");
float price =
[Link]([Link]("pprice"));
int qty = [Link]([Link]("pqty"));
[Link]("Code="+code);
[Link]("<br>Name="+name);
[Link]("<br>Price="+price);
[Link]("<br>Qty="+qty);
%>
</body>
</html>
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
====================================================================
Dt : 4/12/2023
define Java Bean Class?
=>The class which is constructed with the following rules is known as
Java Bean Class.
Rule-1 : The class must be implemented from '[Link]'
interface
Rule-2 : The variables declared in the class must be 'private' variables
Rule-3 : The Class must be declared with 0-argument Constructor or
0-parameter Constructor.
Rule-4 : The class must be declared with "Getter" and "Setter" methods.
Note:
=>These Bean-classes will generate bean-objects and the bean-objects will
hold data going onto Database product and also will hold coming from
Database product.
(bean-objecst are intermediate storages b/w Servlet-program and Database
product)
----------------------------------------------------------------------
faq:
define Getter methods?
=>The methods which are used to get the data from the objects are known
as Getter methods.
faq:
define Setter methods?
=>The methods which are used to set the data for the objects are known as
Setter methods.
Diagram:
=======================================================================
*imp
Objects in ServletProgramming:
========================================================================
*imp
"attribute" in ServletProgramming"
=>'attribute' is a variable in ServletProgramming which can be added to
ServletContext object,ServletRequest object and HttpSession Object.
=>The following are some important methods related to 'attribute':
(i)setAttribute()
(ii)getAttribute()
(iii)removeAttribute()
(iv)getAttributeNames()
(i)setAttribute():
=>setAttribute() method is used to add variable to objects.
Method Signature:
public abstract void setAttribute([Link],[Link]);
(ii)getAttribute():
=>getAttribute() method is used to get the attribute from the Objects.
Method Signature:
public abstract [Link] getAttribute([Link]);
(iii)removeAttribute():
=>removeAttribute() method is used to remove the attribute from the
Objects.
Method Signatute:
public abstract void removeAttribute([Link]);
(iv)getAttributeNames():
=>getAttributeNames() method is used to get all attribute names from the
Objects.
Method Signature:
public abstract [Link]<[Link]>
getAttributeNames();
========================================================================
faq:
define request?
=>The query which is generated from the WebBrowser(Client) to Server
program is known as request.
=>requests generated from the Client are categorized into two types:
[Link] request
[Link] request
[Link] request:
=>The request which is generated to send data to Server is known as
POST request.
=>Through POST request we can send all types of data,which means we can
send Text,Audio,Video,Image and Animation data.
=>Through POST request we can send UnLimited data.
=>The POST request data is secure,because the data is encapsulated to the
body-part of HTTP protocol.
=>We use the following syntax to raise POST request:
<form action="url" method="POST">
.....
</form>
=>we use doPost() method from 'HttpServlet' to accept POST request.
Method Signature of doPost():
protected void doPost([Link],
[Link])throws
[Link],[Link];
-----------------------------------------------------------------
[Link] request:
=>The request which is generated to get the data from the server is known
as GET request.
=>Through GET request we can send only Text data.
=>Through GET request we can send only 4KB or 8KB data.
=>The GET request data is not secure,because the data is added to query
String and displayed in AddressBar.
=>We use the following four ways to raise GET request:
(i)declare method="GET" in <form> tag
syntax:
<form action="url" method="GET">
...
</form>
(ii)declare <form> tag without "method"
syntax:
<form action="url">
...
</form>
(iii)The request raised through hyperlinks is GET request
(iv)Raising request by declared servlet-url-pattern in AddressBar is
GET request
=>we use doGet() method from [Link] to accept
GET request.
Method Signature of doGet():
protected void doGet([Link],
[Link])throws
[Link],[Link];
==================================================================
Dt : 5/12/2023
Ex-Application:
Construct Servlet-Application to perform the following operations:
[Link]
[Link]
DB Table : Product57(code,name,price,qty)
Layout:
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="[Link]">AddProduct</a>
<a href="view">ViewProducts</a>
</body>
</html>
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="add" method="post">
ProductCode:<input type="text" name="code"><br>
ProductName:<input type="text" name="name"><br>
ProductPrice:<input type="text" name="price"><br>
ProductQty:<input type="text" name="qty"><br>
<input type="submit" value="AddProduct">
</form>
</body>
</html>
[Link]
package test;
import [Link].*;
@SuppressWarnings("serial")
public class ProductBean implements Serializable
{
private String code,name;
private float price;
private int qty;
public ProductBean() {}
public String getCode() {
return code;
}
public void setCode(String code) {
[Link] = code;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
[Link] = price;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
[Link] = qty;
}
[Link](Interface)
package test;
public interface DBInfo
{
public static final String
dbUrl="jdbc:oracle:thin:@localhost:1521:xe";
public static final String uName="system";
public static final String pWord="manager";
[Link]
package test;
import [Link].*;
import static [Link].*;
public class DBConnection
{
private static Connection con=null;
private DBConnection() {}
static
{
try {
[Link]("[Link]");
con = [Link](dbUrl,uName,pWord);
}catch(Exception e) {[Link]();}
}
public static Connection getCon()
{
return con;
}
}
[Link]
package test;
import [Link].*;
public class AddProductDAO
{
public int k=0;
public int insert(ProductBean pb)
{
try {
Connection con = [Link]();
//Access Database connection
PreparedStatement ps = [Link]
("insert into Product57 values(?,?,?,?)");
[Link](1, [Link]());
[Link](2, [Link]());
[Link](3, [Link]());
[Link](4, [Link]());
k = [Link]();
}catch(Exception e) {[Link]();}
return k;
}
}
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/add")
public class AddProductServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req,
HttpServletResponse res)throws ServletException,
IOException{
ProductBean pb = new ProductBean();
[Link]([Link]("code"));
[Link]([Link]("name"));
[Link]([Link]([Link]("price")));
[Link]([Link]([Link]("qty")));
int k = new AddProductDAO().insert(pb);
if(k>0) {
[Link]("msg", "Product Added Successfully..<br>");
RequestDispatcher rd =
[Link]("[Link]");
[Link](req, res);
}
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String msg = (String)[Link]("msg");
[Link](msg);
%>
<a href="[Link]">AddProduct</a>
<a href="view">ViewProducts</a>
</body>
</html>
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
===================================================================
Asignment:
Construct Servlet application to perform the following operations:
[Link]
[Link]
DB Table : Employee57(eid,ename,edesg,bsal,hra,da,totsal)
===================================================================
Dt : 6/12/2023
Layout:
[Link]
package test;
import [Link].*;
import [Link].*;
public class ViewProductsDAO
{
public ArrayList<ProductBean> al = new ArrayList<ProductBean>();
public ArrayList<ProductBean> retrieve()
{
try {
Connection con = [Link]();
PreparedStatement ps = [Link]
("select * from Product57");
ResultSet rs = [Link]();
while([Link]()) {
ProductBean pb = new ProductBean();
[Link]([Link](1));
[Link]([Link](2));
[Link]([Link](3));
[Link]([Link](4));
[Link](pb);//Bean Object added to ArrayList
}//end of loop
}catch(Exception e) {[Link]();}
return al;
}
}
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/view")
public class ViewProductsServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
ArrayList<ProductBean> al = new ViewProductsDAO().retrieve();
[Link]("list", al);
RequestDispatcher rd =
[Link]("[Link]");
[Link](req, res);
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="[Link].*,[Link]"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
ArrayList<ProductBean> al =
(ArrayList<ProductBean>)[Link]("list");
if([Link]()==0){
[Link]("No Product available...<br>");
}else{
Iterator<ProductBean> it = [Link]();
while([Link]()){
ProductBean pb = [Link]();
[Link]([Link]()+"  "+
"  "+[Link]()+"  "+
[Link]()+"  "+[Link]()+"<br>");
}
}
%>
<jsp:include page="[Link]"/>
</body>
</html>
=================================================================
Asignment:(Update Assignment)
Construct Servlet application to perform the following operations:
[Link]
[Link]
[Link]
DB Table : Employee57(eid,ename,edesg,bsal,hra,da,totsal)
===================================================================
Summary:
Dt : 7/12/2023
Session Tracking in Servlet Programming:
define 'Session'?
=>The time interval b/w login to logout is known as Session.
[Link]:
=>The small piece of information available b/w multiple requests is
knwon as cookie.
=>The cookie is generated from Server-application,but Stored in Web
Browser to track the user.
=>These cookies are categorized into two types:
(i)persistent cookies
(ii)NonPersistent cookies
(i)persistent cookies:
=>persistent cookies will be stored and available in WebBrowsers until
User logout.
(ii)NonPersistent cookies:
=>NonPersistent cookies will be destroyed automatically when WebBrowser
is closed.
Note:
=>we use '[Link]' class to construct Cookie Session
Tracking process.
=>The following are some important methods from 'Cookie' class:
public [Link]([Link], [Link]);
Hierarchy of Cookie:
Note:
=>Cookie-Objects are Serializable objects and Cloneable Objects.
=====================================================================
Ex-Application : UserApp_Cookie_Session_Tracking
DB Table : UserReg57(uname,pword,fname,lname,addr,mid,phno)
Layout:
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="log" method="post">
UserName:<input type="text" name="uname"><br>
Password:<input type="password" name="pword"><br>
<input type="submit" value="Login">
<a href="[Link]">NewUser?</a>
</form>
</body>
</html>
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="reg" method="post">
UserName:<input type="text" name="uname"><br>
Password:<input type="password" name="pword"><br>
FirstName:<input type="text" name="fname"><br>
LastName:<input type="text" name="lname"><br>
Address:<input type="text" name="addr"><br>
MailId:<input type="text" name="mid"><br>
PhoneNo:<input type="text" name="phno"><br>
<input type="submit" value="Register">
</form>
</body>
</html>
[Link]
package test;
public interface DBInfo
{
public static final String
dbUrl="jdbc:oracle:thin:@localhost:1521:xe";
public static final String uName="system";
public static final String pWord="manager";
[Link]
package test;
import [Link].*;
import static [Link].*;
public class DBConnection
{
private static Connection con=null;
private DBConnection() {}
static
{
try {
[Link]("[Link]");
con = [Link](dbUrl,uName,pWord);
}catch(Exception e) {[Link]();}
}
public static Connection getCon()
{
return con;
}
}
[Link]
package test;
import [Link].*;
@SuppressWarnings("serial")
public class UserBean implements Serializable{
private String uName,pWord,fName,lName,addr,mId;
private long phNo;
public UserBean() {}
public String getuName() {
return uName;
}
public void setuName(String uName) {
[Link] = uName;
}
public String getpWord() {
return pWord;
}
public void setpWord(String pWord) {
[Link] = pWord;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
[Link] = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
[Link] = lName;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
[Link] = addr;
}
public String getmId() {
return mId;
}
public void setmId(String mId) {
[Link] = mId;
}
public long getPhNo() {
return phNo;
}
public void setPhNo(long phNo) {
[Link] = phNo;
}
[Link]
package test;
import [Link].*;
public class RegisterDAO {
public int k=0;
public int register(UserBean ub) {
try {
Connection con = [Link]();
PreparedStatement ps = [Link]
("insert into UserReg57 values(?,?,?,?,?,?,?)");
[Link](1, [Link]());
[Link](2, [Link]());
[Link](3, [Link]());
[Link](4, [Link]());
[Link](5, [Link]());
[Link](6, [Link]());
[Link](7, [Link]());
k = [Link]();
}catch(Exception e) {[Link]();}
return k;
}
}
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/reg")
public class RegServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
UserBean ub = new UserBean();
[Link]([Link]("uname"));
[Link]([Link]("pword"));
[Link]([Link]("fname"));
[Link]([Link]("lname"));
[Link]([Link]("addr"));
[Link]([Link]("mid"));
[Link]([Link]([Link]("phno")));
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String msg = (String)[Link]("msg");
[Link](msg);
%>
<jsp:include page="[Link]"/>
</body>
</html>
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
==================================================================
Dt : 8/12/2023
Layout:
[Link]
package test;
import [Link].*;
public class LoginDAO {
public UserBean ub=null;
public UserBean login(String uName,String pWord) {
try {
Connection con = [Link]();
PreparedStatement ps = [Link]
("select * from UserReg57 where uname=? and
pword=?");
[Link](1, uName);
[Link](2, pWord);
ResultSet rs = [Link]();
if([Link]()) {
ub = new UserBean();
[Link]([Link](1));
[Link]([Link](2));
[Link]([Link](3));
[Link]([Link](4));
[Link]([Link](5));
[Link]([Link](6));
[Link]([Link](7));
}
}catch(Exception e) {[Link]();}
return ub;
}
}
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/log")
public class LoginServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
UserBean ub =new LoginDAO().login([Link]("uname"),
[Link]("pword"));
if(ub==null) {
[Link]("msg","Invalid Login process...<br>");
RequestDispatcher rd = [Link]("[Link]");
[Link](req, res);
}else {
ServletContext sct = [Link]();
//Getting the reference of ServletContext
[Link]("ubean", ub);
//Adding attribute to Context
Cookie ck = new Cookie("name",[Link]());
[Link](ck);//Adding Cookie to response
RequestDispatcher rd = [Link]("[Link]");
[Link](req, res);
}
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String msg = (String)[Link]("msg");
[Link](msg);
%>
<jsp:include page="[Link]"/>
</body>
</html>
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="[Link]"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
UserBean ub = (UserBean)[Link]("ubean");
[Link]("Welcome User : "+[Link]()+"<br>");
%>
<a href="view">ViewProfile</a>
<a href="logout">Logout</a>
</body>
</html>
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/view")
public class ViewProfileServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
Cookie c[] = [Link]();
if(c==null) {
[Link]("msg","Session Expired..<br>");
RequestDispatcher rd = [Link]("[Link]");
[Link](req, res);
}else {
String fName = c[0].getValue();
[Link]("fname", fName);
RequestDispatcher rd =
[Link]("[Link]");
[Link](req, res);
}
} }
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="[Link]"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String fName = (String)[Link]("fname");
UserBean ub = (UserBean)[Link]("ubean");
[Link]("Page belongs to : "+fName+"<br>");
[Link]([Link]()+"  "+[Link]()+" &nb
sp"+
[Link]()+"  "+[Link]()+"  "+
[Link]()+"<br>");
%>
<a href="logout">Logout</a>
</body>
</html>
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/logout")
public class LogoutServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
Cookie c[] = [Link]();
if(c==null) {
[Link]("msg", "Session Expired...");
}else {
ServletContext sct = [Link]();
[Link]("ubean");
c[0].setMaxAge(0);
[Link](c[0]);
[Link]("msg", "User loggedout Successfully..<br>");
}
RequestDispatcher rd = [Link]("[Link]");
[Link](req, res);
} }
=============================================================
Dt : 9/12/2023
Layout:
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/edit")
public class EditProfileServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
Cookie c[] = [Link]();
if(c==null) {
[Link]("msg", "Session Expired...<br>");
RequestDispatcher rd = [Link]("[Link]");
[Link](req, res);
}else {
String fName = c[0].getValue();
[Link]("fname",fName);
RequestDispatcher rd = [Link]
("[Link]");
[Link](req, res);
}
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="[Link]"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String fName = (String)[Link]("fname");
UserBean ub = (UserBean)[Link]("ubean");
[Link]("Page belongs to : "+fName+"<br>");
%>
<form action="update" method="post">
Address:<input type="text" name="addr" value=<%=[Link]()
%>><br>
MailId:<input type="text" name="mid" value=<%=[Link]()
%>><br>
PhoneNo:<input type="text" name="phno" value=<%=[Link]()
%>><br>
<input type="submit" value="UpdateProfile">
</form>
</body>
</html>
[Link]
package test;
import [Link].*;
public class UpdateProfileDAO {
public int k=0;
public int update(UserBean ub) {
try {
Connection con = [Link]();
PreparedStatement ps = [Link]
("update UserReg57 set addr=?,mid=?,phno=? where
uname=? and pword=?");
[Link](1, [Link]());
[Link](2, [Link]());
[Link](3, [Link]());
[Link](4, [Link]());
[Link](5, [Link]());
k = [Link]();
}catch(Exception e) {[Link]();}
return k;
}
}
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/update")
public class UpdateProfileServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
Cookie c[] = [Link]();
if(c==null) {
[Link]("msg", "Session Expired...<br>");
RequestDispatcher rd =
[Link]("[Link]");
[Link](req, res);
}else {
ServletContext sct = [Link]();
//Accessing the reference of ServletContext Object
UserBean ub = (UserBean)[Link]("ubean");
[Link]([Link]("addr"));
[Link]([Link]("mid"));
[Link]([Link]([Link]("phno")));
int k = new UpdateProfileDAO().update(ub);
String fName = c[0].getValue();
[Link]("fname", fName);
if(k>0) {
[Link]("msg", "Profile Updated Successfully..<br>");
}
RequestDispatcher rd = [Link]
("[Link]");
[Link](req, res);
}
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String fName = (String)[Link]("fname");
String msg = (String)[Link]("msg");
[Link]("Page belongs to : "+fName+"<br>");
[Link](msg);
%>
<a href="view">ViewProfile</a>
<a href="logout">Logout</a>
</body>
</html>
====================================================================
Assignment:
ApplicationName : EmployeeMangement
DB Tables :
AdminTab57(uname,pword,fname,lname,addr,mid,phno)
Employee57(eid,ename,edesg,bsal,hra,da,totsal)
Layout:
=======================================================================
Dt : 11/12/2023
Summary Diagram:
==========================================================================
faq:
define addCookie()?
=>addCookie() method is from HttpServletResponse and which is used to add
Cookie-Object to response.
Method Signature of addCookie():
public abstract void addCookie([Link]);
syntax:
[Link](ck);
=>This addCookie() method will perform serialization process,which means converts
Cookie-Object into Stream.
=========================================================================
faq:
define getCookies()?
=>getCookies() method is from HttpServletRequest and which is used to get all
cookies from the request object.
Method Signature of getCookie():
public abstract [Link][] getCookies();
syntax>
Cookie c[] = [Link]();
=>getCookies() method internally perform De-Serialization process,which means
convers Stream into Objects
===========================================================================
=
Application : HTML-FORM to Servlet Program
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="dis" method="post">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="tname" value=""></td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" name="tage" value=""></td>
</tr>
<tr>
<td>Gender</td>
<td><input type="radio" name="gen" value="M"
checked="checked"/>Male
<input type="radio" name="gen" value="F"/>Female
</td>
</tr>
<tr>
<td>Address</td>
<td>
<textarea name="taddress" rows="4" cols="20">enter
address</textarea>
</td>
</tr>
<tr>
<td>MaritalStatus</td>
<td><input type="checkbox" name="ms"
value="married"/>Married</td>
</tr>
<tr>
<td>Qualification</td>
<td>
<select name="qlfy">
<option value="[Link]">Engg</option>
<option value="MBBS">Medical</option>
<option value="B.A">Arts</option>
</select>
</td>
</tr>
<tr>
<td>Courses</td>
<td>
<select name="crs" size="3" multiple="multiple">
<option value="java">JAVA</option>
<option value=".net">.Net</option>
<option value="Testing">Testing</option>
</select>
</td>
</tr>
<tr>
<td>Hobbies</td>
<td>
<input type="checkbox" name="hb" value="read" checked/>
Reading
<input type="checkbox" name="hb" value="stamps"/> Stamp
Collection
<input type="checkbox" name="hb" value="travel"/>
Traveling
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="submit">
<input type="reset" value="cancel">
</td>
</tr>
</table>
</form>
</body>
</html>
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/dis")
public class ControllerServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException{
RequestDispatcher rd =
[Link]("[Link]");
[Link](req, res);
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String name = [Link]("tname");
int age = [Link]([Link]("tage"));
String gen = [Link]("gen");
String addr = [Link]("taddress");
String ms = [Link]("ms");
String qlfy = [Link]("qlfy");
String course = [Link]("crs");
String hb[] = [Link]("hb");
[Link]("Name:"+name);
[Link]("<br>Age:"+age);
[Link]("<br>Gen:"+gen);
[Link]("<br>Address:"+addr);
[Link]("<br>MS:"+ms);
[Link]("<br>Qlfy:"+qlfy);
[Link]("<br>Course:"+course);
[Link]("<br>Hobbies : ");
for(String k : hb)
{
[Link](k+"  ");
%>
</body>
</html>
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
Dt : 12/12/2023
faq:
wt is the diff b/w
(i)getParameter()
(ii)getParameterValues()
(i)getParameter():
=>getParameter() method is used to get single parameter-value from the request-object.
syntax:
String var = [Link]("para_name");
(ii)getParameterValues():
=>getParameterValues() method is used to get group parameter-values from the request
object.
syntax:
String arr_var[] = [Link]("para_name");
==========================================================================
===
*imp
[Link]:
=>HttpSession is an interface from [Link] package and which is used in
Session tracking process.
=>The following are some important methods of HttpSession:
public abstract void setAttribute([Link], [Link]);
public abstract [Link] getAttribute([Link]);
public abstract void removeAttribute([Link]);
public abstract [Link]<[Link]> getAttributeNames();
syntax:
servlet-url-pattern?para=value¶=value&...
Ex:
[Link]
===========================================================================
========
[Link] form fields:
=>The process of declaring <input type="hidden"...> in <form> tag of HTML is known as
Hidden form fields.
=>The values in Hidden form fields are not displayed to the end-user,which means not
shown to the end-user.
syntax:
<form action="url" method="POST/GET">
<input type="hidden" name="name" value="value">
....
</form>
===========================================================================
=====
Note:
=>'URL re-write' and 'Hidden form fields' are Sub-techniques in Session Tracking
process and which are also used to send data from one Servlet-program to another
Servlet-program
===========================================================================
==========
ProjectName : OnlineBookStore
Users :
Admin
Customer
DB tables:
Admin57(uname,pword,fname,lname,addr,mid,phno)
Customer57(uname,pword,fname,lname,addr,mid,phno)
BookDetails57(code,name,author,price,qty)
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="[Link]">AdminLogin</a>
<a href="[Link]">CutomerLogin</a>
</body>
</html>
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="adminLog" method="post">
UserName:<input type="text" name="uname"><br>
Password:<input type="password" name="pword"><br>
<input type="submit" value="AdminLogin">
</form>
</body>
</html>
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="customerLog" method="post">
UserName:<input type="text" name="uname"><br>
Password:<input type="password" name="pword"><br>
<input type="submit" value="CutomerLogin">
<a href="[Link]">NewCutomer?</a>
</form>
</body>
</html>
[Link]
package test;
public interface DBInfo
{
public static final String
dbUrl="jdbc:oracle:thin:@localhost:1521:xe";
public static final String uName="system";
public static final String pWord="manager";
[Link]
package test;
import [Link].*;
import static [Link].*;
public class DBConnection
{
private static Connection con=null;
private DBConnection() {}
static
{
try {
[Link]("[Link]");
con = [Link](dbUrl,uName,pWord);
}catch(Exception e) {[Link]();}
}
public static Connection getCon()
{
return con;
}
}
[Link]
package test;
import [Link].*;
@SuppressWarnings("serial")
public class AdminBean implements Serializable{
private String uName,pWord,fName,lName,addr,mId;
private long phNo;
public AdminBean() {}
public String getuName() {
return uName;
}
public void setuName(String uName) {
[Link] = uName;
}
public String getpWord() {
return pWord;
}
public void setpWord(String pWord) {
[Link] = pWord;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
[Link] = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
[Link] = lName;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
[Link] = addr;
}
public String getmId() {
return mId;
}
public void setmId(String mId) {
[Link] = mId;
}
public long getPhNo() {
return phNo;
}
public void setPhNo(long phNo) {
[Link] = phNo;
}
[Link]
package test;
import [Link].*;
public class AdminLoginDAO {
public AdminBean ab=null;
public AdminBean login(String uName,String pWord) {
try {
Connection con = [Link]();
PreparedStatement ps = [Link]
("select * from Admin57 where uname=? and pword=?");
[Link](1, uName);
[Link](2, pWord);
ResultSet rs = [Link]();
if([Link]()) {
ab = new AdminBean();
[Link]([Link](1));
[Link]([Link](2));
[Link]([Link](3));
[Link]([Link](4));
[Link]([Link](5));
[Link]([Link](6));
[Link]([Link](7));
}
}catch(Exception e) {[Link]();}
return ab;
}
}
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/adminLog")
public class AdminLoginServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException{
AdminBean ab = new AdminLoginDAO().login([Link]("uname"),
[Link]("pword"));
if(ab==null) {
[Link]("msg","Invalid Login process...<br>");
[Link]("[Link]").forward(req, res);
}else {
HttpSession hs = [Link]();//Creating new Session
[Link]("abean", ab);
[Link]("[Link]").forward(req, res);
}
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="[Link]"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
AdminBean ab = (AdminBean)[Link]("abean");
[Link]("Welcome Admin : "+[Link]()+"<br>");
%>
<a href="[Link]">AddBookDetails</a>
<a href="view1">ViewAllBookDetails</a>
<a href="logout">Logout</a>
</body>
</html>
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String msg = (String)[Link]("msg");
[Link](msg);
%>
<jsp:include page="[Link]"/>
</body>
</html>
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
Dt : 13/12/2023
Layout:
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="add" method="post">
BookCode:<input type="text" name="code"><br>
BookName:<input type="text" name="name"><br>
BookAuthor:<input type="text" name="author"><br>
BookPrice:<input type="text" name="price"><br>
BookQty:<input type="text" name="qty"><br>
<input type="submit" value="AddBookDetails">
</form>
</body>
</html>
[Link]
package test;
import [Link].*;
@SuppressWarnings("serial")
public class BookBean implements Serializable{
private String code,name,author;
private float price;
private int qty;
public BookBean() {}
public String getCode() {
return code;
}
public void setCode(String code) {
[Link] = code;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
[Link] = author;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
[Link] = price;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
[Link] = qty;
}
[Link]
package test;
import [Link].*;
public class AddBookDetailsDAO {
public int k=0;
public int insert(BookBean bb) {
try {
Connection con = [Link]();
PreparedStatement ps = [Link]
("insert into BookDetails57
values(?,?,?,?,?)");
[Link](1, [Link]());
[Link](2, [Link]());
[Link](3, [Link]());
[Link](4, [Link]());
[Link](5, [Link]());
k=[Link]();
}catch(Exception e) {[Link]();}
return k;
}
}
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/add")
public class AddBookDetailsServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException{
HttpSession hs = [Link](false);//Accessing existing session
if(hs==null) {
[Link]("msg","Session Expired...<br>");
RequestDispatcher rd = [Link]("[Link]");
[Link](req, res);
}else {
BookBean bb = new BookBean();
[Link]([Link]("code"));
[Link]([Link]("name"));
[Link]([Link]("author"));
[Link]([Link]([Link]("price")));
[Link]([Link]([Link]("qty")));
int k = new AddBookDetailsDAO().insert(bb);
if(k>0) {
[Link]("msg", "Book details added Successfully...<br>");
}
RequestDispatcher rd = [Link]("[Link]");
[Link](req, res);
}
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="[Link]"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
AdminBean ab = (AdminBean)[Link]("abean");
String msg = (String)[Link]("msg");
[Link]("Page belongs to : "+[Link]()+"<br>");
[Link](msg);
%>
<a href="[Link]">AddBookDetails</a>
<a href="view1">ViewAllBookDetails</a>
<a href="logout">Logout</a>
</body>
</html>
[Link]
package test;
import [Link].*;
import [Link].*;
public class ViewAllBooksDAO {
public ArrayList<BookBean> al = new ArrayList<BookBean>();
public ArrayList<BookBean> retrieve(){
try {
Connection con = [Link]();
PreparedStatement ps = [Link]
("select * from BookDetails57");
ResultSet rs = [Link]();
while([Link]()) {
BookBean bb = new BookBean();
[Link]([Link](1));
[Link]([Link](2));
[Link]([Link](3));
[Link]([Link](4));
[Link]([Link](5));
[Link](bb);
}
}catch(Exception e) {[Link]();}
return al;
}
}
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/view1")
public class ViewAllBooksServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException{
HttpSession hs = [Link](false);
if(hs==null) {
[Link]("msg", "Session Expired...<br>");
[Link]("[Link]").forward(req, res);
}else {
ArrayList<BookBean> al = new ViewAllBooksDAO().retrieve();
[Link]("alist", al);
[Link]("[Link]").forward(req, res);
}
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="test.*,[Link].*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
AdminBean ab = (AdminBean)[Link]("abean");
ArrayList<BookBean> al =
(ArrayList<BookBean>)[Link]("alist");
[Link]("Page belongs to : "+[Link]()+"<br>");
if([Link]()==0){
[Link]("Books Not Available...<br>");
}else{
Iterator<BookBean> it = [Link]();
while([Link]()){
BookBean bb = [Link]();
[Link]([Link]()+"  "+[Link]()+" &
nbsp"+
[Link]()+"  "+[Link]()+"  "+
[Link]()+"  "+"<a
href='edit?bcode="+[Link]()+"'>Edit</a>"+"  "+
"<a
href='delete?bcode="+[Link]()+"'>Delete</a>"+"<br>");
}
}
%>
<a href="logout">Logout</a>
</body>
</html>
===========================================================================
=====
Dt : 14/12/2023
Layout:
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/edit")
public class EditBookDetailsServlet extends HttpServlet{
@SuppressWarnings("unchecked")
@Override
protected void doGet(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException{
HttpSession hs = [Link](false);
if(hs==null) {
[Link]("msg","Session Expired...<br>");
[Link]("[Link]").forward(req, res);
}else {
String bCode = [Link]("bcode");
ArrayList<BookBean> al = (ArrayList<BookBean>)[Link]("alist");
BookBean bb = null;
Iterator<BookBean> it = [Link]();
while([Link]()) {
bb = [Link]();
if([Link]([Link]())) {
break;
}
}//end of loop
[Link]("bbean", bb);
[Link]("[Link]").forward(req, res);
} }
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="test.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
AdminBean ab = (AdminBean)[Link]("abean");
BookBean bb = (BookBean)[Link]("bbean");
[Link]("Page belongs to : "+[Link]()+"<br>");
%>
<form action="update" method="post">
<input type="hidden" name="bcode" value=<%=[Link]() %>>
BookPrice:<input type="text" name="bprice"
value=<%=[Link]() %>><br>
BookQty:<input type="text" name ="bqty" value=<%=[Link]()
%>><br>
<input type="submit" value="UpdateBookDetails">
</form>
</body>
</html>
[Link]
package test;
import [Link].*;
public class UpdateBookDetailsDAO {
public int k=0;
public int update(BookBean bb) {
try {
Connection con = [Link]();
PreparedStatement ps = [Link]
("update BookDetails57 set price=?,qty=? where
code=?");
[Link](1, [Link]());
[Link](2, [Link]());
[Link](3, [Link]());
k = [Link]();
}catch(Exception e) {[Link]();}
return k;
}
}
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/update")
public class UpdateBookDetailsServlet extends HttpServlet{
@SuppressWarnings("unchecked")
@Override
protected void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException{
HttpSession hs = [Link](false);
if(hs==null) {
[Link]("msg", "Session Expired...<br>");
[Link]("[Link]").forward(req, res);
}else {
String bCode = [Link]("bcode");
ArrayList<BookBean> al = (ArrayList<BookBean>)[Link]("alist");
BookBean bb = null;
Iterator<BookBean> it = [Link]();
while([Link]()) {
bb = [Link]();
if([Link]([Link]())) {
break; }
} //end of loop
[Link]([Link]([Link]("bprice")));
[Link]([Link]([Link]("bqty")));
int k = new UpdateBookDetailsDAO().update(bb);
if(k>0) {
[Link]("msg", "Book details Updated Successfully..<br>");
[Link]("[Link]").forward(req, res);
}
}
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="test.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
AdminBean ab = (AdminBean)[Link]("abean");
String msg = (String)[Link]("msg");
[Link]("page belongs to : "+[Link]()+"<br>");
[Link](msg);
%>
<a href="[Link]">AddBookDetails</a>
<a href="view1">ViewAllBookDetails</a>
<a href="logout">Logout</a>
</body>
</html>
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/logout")
public class LogoutServlet extends HttpServlet{
protected void doGet(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException{
HttpSession hs = [Link](false);
if(hs==null) {
[Link]("msg","Session expired...<br>");
[Link]("[Link]").forward(req, res);
}else {
[Link]("[Link]").forward(req, res);
}
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
[Link]();
[Link]("Loggedout Successfully...<br>");
%>
<jsp:include page="[Link]"/>
</body>
</html>
===========================================================================
===
Dt : 15/12/2023
Assignment:(Construct Customer-Login for above appliaction using the following Layout)
===========================================================================
faq:
wt is the diff b/w
(i)Cookie
(ii)HttpSession
(i)Cookie:
=>Cookie is a Class from [Link] and which is used session tracking
process.
=>Cookie is created by Server-Application,but stored in WebBrowser to track the
user
=>Cookie Applications are Client dependent Application.
(ii)HttpSession:
=>HttpSession is an interface from [Link] and which is also used in
Session tracking process.
=>HttpSession object is created by Server-application and which is available in
Server only.
=>HttpSession Applications are Sever dependent applications
===========================================================================
======
faq:
wt is the diff b/w
(i)getSession()
(ii)getSession(false)
(iii)getSession(true)
(i)getSession():
=>getSession() method will search for existing session,if not available creates
new-session.
(ii)getSession(false):
=>getSession(false) method will also search for existing session,if available use
the session and if not available new session is not created.
(iii)getSession(true)
=>getSession(true) method also search for existing session,if available use the
session and if not available create a new session.
*imp ServletContext:
=>ServletContext is an interface from [Link] package and which is instantiated
automatically when Web Application is deployed into Server.
=>This ServletContext object is loaded with Server information.
=>we use getServletContext() method from ServletRequest to access the reference of
ServletContext Object.
syntax:
ServletContext sct = [Link]();
=>we use <context-param> tag part of [Link] to initialize parameter-values to
ServletContext object.
syntax:
<web-app>
<context-param>
<param-name> name </param-name>
<param-value> value </param-value>
</context-param>
...
</web-app>
=>we use getInitParameter() method to access initialized parameter-value from the
ServletContext Object.
Method signature of getInitParameter():
public abstract [Link] getInitParameter([Link]);
syntax:
String var = [Link]("para_name");
Dt : 16/12/2023
*imp
ServletConfig:
=>ServletConfig is an interface from [Link] package and which is instantiated
automatically when the Servlet-program loaded for execution.
=>This ServletConfig Object is loaded with Servlet-name.
=>we use getServletConfig() method from 'GenericServlet' to access the reference of
ServletConfig Object
syntax:
ServletConfig scf = [Link]();
=>we use <init-param> subtag of <servlet> tag to initialize parameter-values in
ServletConfig object.
syntax:
<web-app>
...
<servlet>
<servlet-name> name </servlet-name>
<servlet-class> class </servlet-class>
<init-param>
<param-name> name </param-name>
<param-value> value </param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name> name </servlet-name>
<url-pattern> /url </url-pattern>
</servlet-mapping>
...
</web-app>
=>we use getInitParameter() method to get the initialized parameter from ServletConfig
Object
Ex-Application:
Layout:
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="dis" method="post">
UserName:<input type="text" name="uname"><br>
<input type="submit" value="Display">
</form>
</body>
</html>
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
public class DisplayServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException{
ServletContext sct = [Link]();
ServletConfig scf = [Link]();
[Link]("sn", [Link]());
[Link]("c", [Link]("c"));
[Link]("a","NIT");
[Link]("[Link]").forward(req, res);
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String uName = [Link]("uname");
[Link]("Welcome User : "+uName+"<br>");
[Link]("====ServletContext=====");
[Link]("<br>ServerInfo:"+[Link]());
String a = (String)[Link]("a");
[Link]("<br>Attribute in Context:"+a);
int b = [Link]([Link]("b"));
[Link]("<br>Context-InitParameter:"+b);
[Link]("<br>====ServletConfig=====");
[Link]("<br>ServletName :"+[Link]("sn"));
[Link]("<br>Config-
InitParameter:"+[Link]("c"));
[Link]("<br>JSP Config:"+[Link]());
%>
</body>
</html>
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<context-param>
<param-name>b</param-name>
<param-value>200</param-value>
</context-param>
<servlet>
<servlet-name>DisplayServlet</servlet-name>
<servlet-class>[Link]</servlet-class>
<init-param>
<param-name>c</param-name>
<param-value>500</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DisplayServlet</servlet-name>
<url-pattern>/dis</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
===========================================================================
====
Note:
(i)Only one ServletContext object is created for WebApplication and the information
in ServletContext object can be used by all the Servlet-programs and JSP-Programs
of Web Application.
(ii)Every Servlet-program and JSP-program in applications will have its own
ServletConfig objects.
(iii)when we want to send data to WebApplication then we send data to ServletContext
object.
(iv)when we want to send data to individual Servlet-program then we send data to
ServletConfig object
===========================================================================
====
Note:
=>To execute Servlet-program we need servlet-url-pattern and this Servlet-url-pattern
is holded by any one of the following:
[Link]
@WebServlet("/url")
[Link]
<servlet></servlet>
<servlet-mapping></servlet-mapping)
===========================================================================
=========
Dt : 18/12/2023
*imp
Filters in Servlet Programming:
=>Filter is a pre-processing component which is executed before Servlet Program.
=>Filter is executed with same url-pattern of Servlet-program,which means Filter
and Servlet will have same url-pattern.
=>Filter-program will have highest priority in execution than Servlet-program.
=>In realtime Filter-program will hold security related code,which means Filter is
a Security layer of Servlet-program.
=>we use the following components to construct Filters:
[Link]
[Link]
[Link]
[Link]:
=>'Filter' is an interface from [Link] package and which is implemented to
construct Filter-programs.
=>The following are some important methods from Filter:
public void init([Link])
throws [Link];
public abstract void doFilter([Link],
[Link], [Link])
throws [Link], [Link];
public void destroy();
[Link]:
=>FilterChain is an interface from [Link] package and which is instantiated
automatically while doFilter()-method execution.
=>This FilterChain will provide the following method to interlink Servlet-program
having same url-pattern:
public abstract void doFilter([Link],
[Link]) throws [Link],
[Link];
Ex-application:
Layout:
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="log" method="post">
UserName:<input type="text" name="uname"><br>
Password:<input type="password" name="pword"><br>
<input type="submit" value="Login">
</form>
</body>
</html>
[Link]
package test;
import [Link].*;
@SuppressWarnings("serial")
public class UserBean implements Serializable{
private String uName,pWord,fName,lName,addr,mId;
private long phNo;
public UserBean() {}
public String getuName() {
return uName;
}
public void setuName(String uName) {
[Link] = uName;
}
public String getpWord() {
return pWord;
}
public void setpWord(String pWord) {
[Link] = pWord;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
[Link] = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
[Link] = lName;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
[Link] = addr;
}
public String getmId() {
return mId;
}
public void setmId(String mId) {
[Link] = mId;
}
public long getPhNo() {
return phNo;
}
public void setPhNo(long phNo) {
[Link] = phNo;
}
[Link]
package test;
public interface DBInfo
{
public static final String
dbUrl="jdbc:oracle:thin:@localhost:1521:xe";
public static final String uName="system";
public static final String pWord="manager";
[Link]
package test;
import [Link].*;
import static [Link].*;
public class DBConnection
{
private static Connection con=null;
private DBConnection() {}
static
{
try {
[Link]("[Link]");
con = [Link](dbUrl,uName,pWord);
}catch(Exception e) {[Link]();}
}
public static Connection getCon()
{
return con;
}
}
[Link]
package test;
import [Link].*;
public class LoginDAO {
public UserBean ub = null;
public UserBean login(String uName,String pWord) {
try {
Connection con = [Link]();
PreparedStatement ps = [Link]
("select * from UserReg57 where uname=? and
pword=?");
[Link](1, uName);
[Link](2, pWord);
ResultSet rs = [Link]();
if([Link]()) {
ub = new UserBean();
[Link]([Link](1));
[Link]([Link](2));
[Link]([Link](3));
[Link]([Link](4));
[Link]([Link](5));
[Link]([Link](6));
[Link]([Link](7));
}
}catch(Exception e) {[Link]();}
return ub;
}
}
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
@WebFilter("/log")
public class LoginFilter implements Filter{
@Override
public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain)
throws ServletException,IOException{
UserBean ub = new LoginDAO().login([Link]("uname"),
[Link]("pword"));
if(ub==null) {
[Link]("msg","Invalid Login process...<br>");
[Link]("[Link]").forward(req, res);
}else {
[Link]("ubean", ub);
[Link](req, res);//linking Servlet_program
}
}
}
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/log")
public class WelcomeServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException{
[Link]("[Link]").forward(req, res);
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="test.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
UserBean ub = (UserBean)[Link]("ubean");
[Link]("Welcome User : "+[Link]()+"<br>");
[Link]([Link]()+"  "+[Link]()+" &nb
sp"+[Link]()+
"  "+[Link]()+"  "+[Link]()+"<br>")
;
%>
<jsp:include page="[Link]"/>
</body>
</html>
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String msg = (String)[Link]("msg");
[Link](msg);
%>
<jsp:include page="[Link]"/>
</body>
</html>
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
===========================================================================
=
Dt : 19/12/2023
[Link]:
=>FilterConfig is an interface from [Link] package and which is instantiated
automatically when filter-program is loaded for execution.
=>This FilterConfig Object is loaded with Filter_name.
=>To access FilterConfig object reference we must use init()-method
=>we use <init-param> subtag part of <filter> tag to initialize parameter-values
to FilterConfig Object.
syntax:
<web-app>
...
<filter>
<filter-name> name </filter-name>
<filter-class> class </filter-class>
<init-param>
<param-name> name </param-name>
<param-value> value </param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name> name </filter-name>
<url-pattern> /url </url-pattern>
</filter-mapping>
...
</web-app>
---------------------------------------------------------------------------
Ex-Application:(Demonstrating FilterConfig)
Layout:
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="dis" method="post">
UserName:<input type="text" name="uname"><br>
<input type="submit" value="Display">
</form>
</body>
</html>
[Link]
package test;
import [Link].*;
import [Link].*;
public class DisplayFilter implements Filter{
public FilterConfig fcf=null;
@Override
public void init(FilterConfig fcf)throws ServletException{
[Link]=fcf;
}
@Override
public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain)throws
ServletException,IOException{
[Link]("fn",[Link]());
[Link]("a", [Link]("a"));
[Link]("[Link]").forward(req, res);
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String uName = [Link]("uname");
String fn = (String)[Link]("fn");
[Link]("Welcome UserName : "+uName+"<br>");
[Link]("=====FilterConfig=====");
[Link]("<br>FilterName:"+fn);
[Link]("<br>FilterConfig
Val:"+[Link]("a"));
%>
</body>
</html>
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<filter>
<filter-name>DisplayFilter</filter-name>
<filter-class>[Link]</filter-class>
<init-param>
<param-name>a</param-name>
<param-value>1000</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>DisplayFilter</filter-name>
<url-pattern>/dis</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
===========================================================================
faq:
wt is the diff b/w
(i)ServletConfig
(ii)FilterConfig
(iii)JSP-Config
(i)ServletConfig:
=>ServletConfig is instantiated automatically when Servlet-program loaded for
execution and which holds Servlet_name.
(ii)FilterConfig:
=>FilterConfig is instantiated automatically when Filter-program is loaded for
execution and which holds Filter_name
(iii)JSP-Config:
=>JSP-Config means ServletConfig and which is instantiated automatically when
JSP-program loaded for execution.
=>This JSP-Config is accessed with implicit name "config"
===========================================================================
===
*imp
Events and Listeners in Servlet Programming:
define Events?
=>The actions which are performed are known as Events.
define Listeners?
=>Listeners are executed background to Servlet-Objects and record the actions
performed on Servlet-Objects.
=>The Listeners in Servlet programming can be added to the following Servlet-Objects
[Link]
[Link]
[Link]
[Link]:
=>we add 'ServletContextListener' to ServletContext Object
Listener_name : ServletContextListener
public void contextInitialized([Link]);
public void contextDestroyed([Link]);
Event_name : ServletContextEvent
public [Link] getServletContext();
Attribute_Lisnter_name : ServletContextAttributeListener
public void attributeAdded([Link]);
public void attributeRemoved([Link]);
public void attributeReplaced([Link]);
Attribute_Event_name : ServletContextAttributeEvent
public [Link] getName();
public [Link] getValue();
--------------------------------------------------------------------------------
[Link]:
=>we add 'ServletRequestListener" to ServletRequest Object
Listener_name : ServletRequestListener
public void requestInitialized([Link]);
public void requestDestroyed([Link]);
Event_name : ServletRequestEvent
public [Link] getServletRequest();
public [Link] getServletContext();
Attribute_Listener_name : ServletRequestAttributeListener
public void attributeAdded([Link]);
public void attributeRemoved([Link]);
public void attributeReplaced([Link]);
Attribute_Event_name : ServletRequestAttributeEvent
public [Link] getName();
public [Link] getValue();
----------------------------------------------------------------------------
[Link]:
=>we add 'HttpSessionListenter' to HttpSession object
Listener_name : HttpSessionListener
public void sessionCreated([Link]);
public void sessionDestroyed([Link]);
Event_name : HttpSessionEvent
public [Link] getSession();
Attribute_Listener_name : HttpSessionAttributeListener
public void attributeAdded([Link]);
public void attributeRemoved([Link]);
public void attributeReplaced([Link]);
Attribute_Event_name : HttpSessionBindingEvent
public [Link] getName();
public [Link] getValue();
===========================================================================
=
Dt : 20/12/2023
[Link]
package test;
import [Link].*;
import [Link].*;
@WebListener
public class ContextListener implements ServletContextListener,
ServletContextAttributeListener{
@Override
public void contextInitialized(ServletContextEvent sce) {
[Link]("Context Object initialized....");
ServletContext sct = [Link]();//Accessing Context Objec_ref
[Link]("Application deployed into : "+[Link]());
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
[Link]("Context Object destroyed...");
}
@Override
public void attributeAdded(ServletContextAttributeEvent scae) {
[Link]("Attribute added to Context Object");
String aName = [Link]();
[Link]("Attribute Name : "+aName);
}
@Override
public void attributeRemoved(ServletContextAttributeEvent scae) {
[Link]("Attribute removed from Context Object");
}
}
Note:
=>Add [Link] program into Cookie Session tracking Application.
===========================================================================
=====
[Link]
package test;
import [Link].*;
import [Link].*;
@WebListener
public class RequestListener implements ServletRequestListener,
ServletRequestAttributeListener{
@Override
public void requestInitialized(ServletRequestEvent sre) {
[Link]("Request Object initialized....");
}
@Override
public void requestDestroyed(ServletRequestEvent sre) {
[Link]("Request Object destroyed...");
}
@Override
public void attributeAdded(ServletRequestAttributeEvent srae) {
[Link]("Attribute added to Request Object...");
String aName = [Link]();
[Link]("Attribute Name:"+aName);
}
@Override
public void attributeRemoved(ServletRequestAttributeEvent srae) {
[Link]("Attribute removed from Request Object...");
}
}
[Link]
package test;
import [Link].*;
import [Link].*;
@WebListener
public class SessionListener implements HttpSessionListener,
HttpSessionAttributeListener{
@Override
public void sessionCreated(HttpSessionEvent hse) {
[Link]("Session Created...");
}
@Override
public void sessionDestroyed(HttpSessionEvent hse) {
[Link]("Session destroyed...");
}
@Override
public void attributeAdded(HttpSessionBindingEvent hsbe) {
[Link]("Attribute added to Session...");
String aName = [Link]();
[Link]("Attribute Name:"+aName);
}
@Override
public void attributeRemoved(HttpSessionBindingEvent hsbe) {
[Link]("Attribute removed from Session...");
}
}
Note:
=>Add [Link] and [Link] to HttpSession tracking
application.
===========================================================================
Dt : 21/12/2023
faq:
define Annotattion?
=>The tag-based-information which is added to the programming components like
Variable or method or Class or Interface is known as Annotation.
=>we use '@' symbol to represent annotations.
=>These annotations will give information to Compiler at compilation stage or
will give information to execution-control while execution process.
CoreJava Annotations:
@Override - will give information to compiler to check the method is
Overriding method or not
@SuppressWarnings - will give information to compiler to close the raised
warnings
@FunctionalInterface - will give information to check the interface is
Functional Interface or not
AdvJava Annotations:
@WebServlet - will hold Servlet-url-pattern to identify Servlet-program
for execution.
@WebFilter - will hold Servlet-url-pattern to identify Filter-program for
execution.
@WebListener - is used to identify Listener-program for execution.
===========================================================================
==
*imp
Servlet Life-Cycle:
=>Servlet Life-Cycle demonstrates different states of Servlet-program from
Starting of program to ending of program.
=>The following are the stages of Servlet Life-Cycle:
[Link] process
[Link] process
[Link] process
[Link] Handling Process
[Link] Process
[Link] process:
=>The process of identifying the servlet-program using url-pattern and loading
for execution is known as Loading Process.
[Link] process:
=>When Servlet-program loaded,it is instantiated automatically known as
Instantiation process.(Object creation process)
=>After Instantiation process,the execution-controls will identify the following
life-cycle methods:
GenericServlet
init()
service()
destroy()
HttpServlet
init()
service()/doPost()/doGet()
destroy()
Filter
init()
doFilter()
destroy()
[Link] process:
=>The process of making the programming components ready for service()-method
is known as Initialization process.
=>we use init()-method for initialization process.
Note:
=>init()-method is executed only once for Servlet-program,which means
Initialization process is performed only once.
[Link] Process:
=>The process of closing the resources which are opened part of Request Handling
process is known as destroying process.
=>we use destroy()-method to perform destroying process.
Note:
=>The destroy()-method is executed after service()-method execution completed.
==========================================================================
=
Ex-application:
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="dis" method="post">
UserName:<input type="text" name="uname"><br>
<input type="submit" value="Display">
</form>
</body>
</html>
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/dis")
public class DisplayServlet extends HttpServlet
{
public DisplayServlet()
{
[Link]("Instantiation process...");
}
@Override
public void init()throws ServletException
{
[Link]("Initialization process...");
}
@Override
protected void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException{
PrintWriter pw = [Link]();
[Link]("text/html");
[Link]("Welcome : "+[Link]("uname"));
[Link]("Request handling process...");
}
@Override
public void destroy()
{
[Link]("Destroying process....");
}
}
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
======================================================================
Dt : 22/12/2023
faq:
wt it the diff b/w
(i)JAR
(ii)WAR
(iii)EAR
(i)JAR:
=>JAR means 'Java Archeive' and which is compressed format of
class files.
(ii)WAR:
=>WAR means 'Web Archeive' and which is compressed format of
HTML files,XML file,UI-Files,Servlets,JSP and Jars.
=>WebApplications are converted into WAR files.
(iii)EAR:
=>EAR means 'Enterprise Archeive' and which is compressed format
of Enterprise Java Beans,WARs and JARs.
=>Enterprise Applications are converted into EAR files.
================================================================
Summary:
[Link] tags:
=>The Scripting tags are used to write JavaCode in JSP programs.
=>These Scripting tags are categorized into the following:
(a)Scriptlet tag
(b)Expression tag
(c)Declarative tag
(a)Scriptlet tag:
=>Scriptlet tag is used to write Normal JavaCode or ServletCode in JSP
programs.
syntax:
<% code %>
(b)Expression tag:
=>Expression tag is used to assign the value to variable or used to
display the data to WebBrowser directly.
syntax:
<%= value/Expression %>
(c)Declarative tag:
=>Declarative tag is used to declare variables and methods in JSP
Programs.
syntax:
<%! Variables;Methods %>
---------------------------------------------------------------
[Link] tags:
=>The tags which are used to specify the directions in translation
process of JSP Programs.
=>Directive tags are categorized into the following:
(a)@page
(b)@include
(c)@taglib
(a)@page:
=>'@page' will specify Langauge used in JSP,contextType,pageEncoding,
importing and so on...
(Specifications about the JSP page)
syntax:
<%@page ... %>
(b)@include:
=>'@include' will specify which page must be included to current running
JSP program
syntax:
<%@include file="File_name"/%>
(c)@taglib:
=>'@taglib' is used to link external libraries to current JSP program.
syntax:
<%@tablib ....%>
---------------------------------------------------------------------
[Link] tags:
=>Action tage used to perform some actions related to JSP programs while
execution process.
=>These Action tage are categorized into the following:
(a)<jsp:include>
(b)<jsp:forward>
(c)<jsp:param>
(d)<jsp:useBean>
(e)<jsp:setProperty>
(f)<jsp:getProperty>
======================================================================
Ex-program:(Demonstrating JSP-Application)
Layout:
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="[Link]" method="post">
Enter the Value:<input type="text" name="v"><br>
<input type="submit" value="Factorial">
</form>
</body>
</html>
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
errorPage="[Link]"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%!
int fact;
int factorial(int n)
{
fact=1;
for(int i=n;i>=1;i--)
{
fact=fact*i;
}
return fact;
}
%>
<%
int v = [Link]([Link]("v"));
int res = factorial(v);
[Link]("factorial="+res+"<br>");
%>
<%@include file="[Link]"%>
</body>
</html>
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
isErrorPage="true"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
[Link]("Invalid input...<br>");
%>
<%= exception %>
<br>
<%@include file="[Link]" %>
</body>
</html>
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
======================================================================
*imp
Implicit Objects of JSP:
[Link] - [Link]
[Link] - [Link]
[Link] - [Link]
[Link] - [Link]
[Link] - [Link]
[Link] - [Link]
[Link] - [Link]
[Link] - [Link]
[Link] - [Link]
=====================================================================
Ex-program:(Demonstrating <jsp:include>,<jsp:forwrad> and <jsp:param>)
Layout:
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="[Link]" method="post">
Enter the Value-1:<input type="text" name="v1"><br>
Enter the Value-2:<input type="text" name="v2"><br>
<input type="submit" value="Add" name="s1">
<input type="submit" value="Sub" name="s1">
</form>
</body>
</html>
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String s1 = [Link]("s1");
if([Link]("Add")){
%>
<jsp:forward page="[Link]">
<jsp:param value="<%= 200%>" name="nm"/>
</jsp:forward>
<%
}else{
%>
<jsp:forward page="[Link]">
<jsp:param value="<%= 300 %>" name="nm"/>
</jsp:forward>
<%
}
%>
</body>
</html>
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
errorPage="[Link]"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
int v1 = [Link]([Link]("v1"));
int v2 = [Link]([Link]("v2"));
int v3 = v1+v2;
[Link]("Name:"+[Link]("nm")+"<br>");
[Link]("Addition:"+v3+"<br>");
%>
<jsp:include page="[Link]"/>
</body>
</html>
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
errorPage="[Link]"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
int v1 = [Link]([Link]("v1"));
int v2 = [Link]([Link]("v2"));
int v3 = v1-v2;
[Link]("Name:"+[Link]("nm")+"<br>");
[Link]("Subtraction:"+v3+"<br>");
%>
<jsp:include page="[Link]"/>
</body>
</html>
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
isErrorPage="true"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
[Link]("Invalid input...<br>");
%>
<%= exception %>
<br>
<jsp:include page="[Link]"/>
</body>
</html>
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list> </web-app>
Dt : 26/12/2023
Ex-program(Demonstrating <jsp:useBean>,<jsp:setProperty> and <jsp:getProperty>)
Layout:
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="[Link]" method="post">
UserName:<input type="text" name="uname"><br>
MailId:<input type="text" name="mid"><br>
PhoneNo:<input type="text" name="phno"><br>
<input type="submit" value="LoadToBean">
</form>
</body>
</html>
[Link]
package test;
import [Link].*;
@SuppressWarnings("serial")
public class UserBean implements Serializable{
private String uName,mId;
private long phNo;
public UserBean() {}
public String getuName() {
return uName;
}
public void setuName(String uName) {
[Link] = uName;
}
public String getmId() {
return mId;
}
public void setmId(String mId) {
[Link] = mId;
}
public long getPhNo() {
return phNo;
}
public void setPhNo(long phNo) {
[Link] = phNo;
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="[Link]"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<jsp:useBean id="ub" class="[Link]" scope="session"/>
<jsp:setProperty property="uName" param="uname" name="ub"/>
<jsp:setProperty property="mId" param="mid" name="ub"/>
<jsp:setProperty property="phNo" param="phno" name="ub"/>
<h1>Details Added to Bean Successfully...</h1><br>
<a href="[Link]">ViewDetails</a>
</body>
</html>
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="[Link]"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<jsp:useBean id="ub" type="[Link]" scope="session"/>
UserName:<jsp:getProperty property="uName" name="ub"/><br>
MailID:<jsp:getProperty property="mId" name="ub"/><br>
PhoneNo:<jsp:getProperty property="phNo" name="ub"/><br>
</body>
</html>
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
======================================================================
(a)<jsp:include>:
=><jsp:include> tag is used to include the specified files into current running
JSP-page
syntax:
<jsp:include page="file"/>
(b)<jsp:forward>:
=><jsp:forward> tag is used to forward the request from one JSP-page to
another JSP-page.
syntax:
<jsp:forward page="file"/>
(c)<jsp:param>:
=><jsp:param> tag is a SubTag of <jsp:forward> and which is used to send
parameter from one JSP-page to another JSP-page.
syntax:
<jsp:forward page="file">
<jsp:param value="value" name="name"/>
</jsp:forward>
(d)<jsp:useBean>:
=><jsp:useBean> tag is used to instatiate bean-object or identify the existing
bean-object.
syntax-1:(Instantiating Bean-Object)
<jsp:useBean id="bean_name" class="Class_name" scope="scope"/>
Type of scope:
(i)application - Used in total Web Application
(ii)page - Used only in JSP-page
(iii)request - Used within the request
(iv)session - Used within the session
(e)<jsp:setProperty>:
=>jsp:setProperty> tag is used to set the data to Bean object.
=>This <jsp:setProperty> internally uses Setter-method based on property-name
syntax:
<jsp:setProperty property="" param="" name="bean_name"/>
(f)<jsp:getProperty>:
=><jsp:getProperty> tag is used to get the data from the Bean Objects.
=>This <jsp:getProperty> internally uses Getter-method based on Property-name
display the data directly through JspWriter.
syntax:
<jsp:getProperty property="" name="bean_name"/>
Dt : 27/12/2023
Expression Language(EL):
=>Expression Language will provide more flexibility to access the objects of
JSP like request,response,out,...
=>Expression Language is a newly added feature to JSP-Programming and which is
known as "JSP-EL".
syntax:
$(Expression)
=>The following are implicit objects of Expression Language(EL):
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]:
=>'appliactionScope' is used to access attribute from ServletContext Object.
[Link]:
=>'sessionScope' is used to access attribute from HttpSession Object.
[Link]:
=>'requestScope' is used to access attribute from jsp-request-Object.
[Link]:
=>'pageScope' is used to access attribute from jsp-pageContext-Object.
[Link]:
=>'param' is used to access single para-value from jsp-request-Object.
[Link]:
=>'paramValue' is used to multiple para-values from jsp-request-Object in the
form of String-Array
[Link]:
=>'header' is used to access single header value from jsp-request-Object.
[Link]:
=>'headerValues' is used to access multiple header values from jsp-request-Object
in the form of String-Array
[Link]:
=>'cookie' is used to access cookie from jsp-request-Object
[Link]:
=>'initParam' is used to access initialization para-value from jsp-config-Object
[Link]:
=>'pageContext' is an implicit object refering jsp-pageContext-Object
==========================================================================
==
*imp
Complete Summary of Objects Generated from CoreJava and AdvJava:
Advantages of JSTL:
(i)Fast Development
(ii)Code Reusability
(iii)No need to use scriptlet tag
(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)
syntax:
<%@ taglib uri="[Link]
prefix="c" %>
*imp
c:forEach-> It is the basic iteration tag.
syntax:
fn:trim(): It removes the blank spaces from both the ends of a string.
syntax:
*imp
fmt:formatDate : It formats the time and date using the
supplied pattern and styles.
===========================================================
(4)XML Tags:
=>The JSTL XML tags are used for providing a JSP-centric way of
manipulating and creating XML documents.
syntax:
<%@ taglib uri="[Link] prefix="x" %>
(5)SQL Tags:
=>The SQL tag library allows the tags to Interact with RDBMS
(Relational Databases) such as Microsoft SQL Server, mySQL,
or Oracle.
syntax:
<%@ taglib uri="[Link] prefix="sql" %>
Note:
=>In realtime we must not have JSP Centric XML and DB
Connections,because of this reason XML tags and SQL Tags are
less used when compared to other tags.
================================================================
Dt : 28/12/2023
Ex-application:(Demonstrating EL-JSTL)
Layout:
[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title> </head>
<body>
<form action="dis" method="post">
Enter the name:<input type="text" name="name"><br>
<input type="submit" value="Display">
</form>
</body>
</html>
[Link]
package test;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
@SuppressWarnings("serial")
@WebServlet("/dis")
public class ControllerServlet extends HttpServlet{
@ Override
public void doPost(HttpServletRequest req,
HttpServletResponse res)
throws ServletException,IOException{
ServletContext sct = [Link]();
HttpSession hs = [Link]();
[Link]("a",100);
[Link]("b",200);
[Link]("c", 300);
RequestDispatcher rd = [Link]("[Link]");
[Link](req,res);
}
}
[Link]
<%@ page language="java"
contentType="text/html; charset=ISO- 8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib prefix="c"
uri="[Link] %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body> <% [Link]("fName","Raju"); %>
<c:set var="name" value="${[Link]} "/>
WELCOME : <c:out value="${name}"/><br>
<c:set var="a" value="${applicationScope.a}" />
<c:set var="b" value="${sessionScope.b}" />
<c:set var="c" value="${requestScope.c}" />
<c:set var="d" value="${[Link]}" />
ContextVal:<c:out value="${a}"/><br>
SessionVal:<c:out value="${b}"/><br>
RequestVal:<c:out value="${c}"/><br>
PageVal:<c:out value="${d}"/><br> </body>
</html>
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>
===========================================================================
faq:
define pageContext?
=>pageContext is an implicit object generated for
[Link] AbstractClass and which is extended
from [Link] AbstractClass.
=>using pageContext object we can access remaining implicit
objects of JSP.
The following are some important methods:
Note:
=>page implicit object is used part of JSP,when we want to
perform Cloning process or Thread communication process.
=========================================================
1. Model-1 Architecture
2. Model-2 Architecture
1. Model-1 Architecture:
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.
Diagram:
THE END```