Advanced Java Full Notes Till 20 June
Advanced Java Full Notes Till 20 June
dt : 27/4/2022(day-1)
part-1 : CoreJava
=>Alphabets(Programming Components)
(a)Variables
(b)Methods
(c)Blocks
ii
(d)Constructors
ath
(e)Classes
(f)Interfaces
ip
(g)AbstractClasses
=>Programming Concepts
Application.
nk
as Web Application.
construct WebApplications:
1.JDBC
2.Servlet
3.JSP
1.JDBC:
ii
Connectivity' and which is used to establish
ath
connection b/w JavaProgram and DB product.
ip
2.Servlet:
Ma
=>Servlet means 'Server program' and which
the response.
sh
3.JSP:
ate
(a)Field Storage
(b)Object Storage
Ve
(c)File Storage
(d)DataBase Storage
(a)Field Storage:
field Storage.
*imp
(b)Object Storage:
ii
=>The memory generated to hold group members
ath
is known as Object Storage.
ip
class Addition
int a,b,c;
Ma
void add()
sh
{
c = a+b;
ate
Sop(c);
}
nk
}
Ve
ip
faq:
(ii)Object reference
sh
(iii)Object reference Variable
ate
(i)Object:
is known as Object.
Ve
(ii)Object reference:
as Object reference.
--------------------------------------------------
Summary:
ii
(ii)NonPrimitive DataType Variable
ath
(Reference DataType Variable)
ip
NonPrimitive DataType variables will hold Object references.
Ma
=========================================================
Note:
=>File Storage
=>DataBase Storage
Ve
ii
ip ath
Ma
============================================================
faq:
sh
define API?
JavaLib:
CoreJava:
AdvJava:
ii
(iii)javax.servlet.jsp - JSP parogramming
ath
============================================================
*imp
ip
(c)File Storage:
Ma
=>The smallest permanent storage of computer System,which is
File Storage.
sh
Note:
Diagram:
Ve
ii
ip ath
faq: Ma
define output stream?
output stream.
sh
ate
faq:
=>The Java program reading the data from the file storage is
nk
----------------------------------------------------------
Dt : 29/4/2022
faq:
define Stream?
1.Byte Stream
2.Character Stream
1.Byte Stream:
ii
=>The contineous flow of data in the form of 8-bits is known as
ath
ByteStream or Binary Stream.
ip
2.Character Stream:
Ma
=>The contineous flow of data in the form of 16-bits is known as
===========================================================
1.Data Redundancy
2.Data Inconsistency
5.Integrity Problems
6.Atomicity Problems
8.Security problems
===================================================================
Note:
ii
for JavaApplications.
ath
===============================================================
*imp
ip
(d)DataBase Storage:
Ma
=>The largest Permanent Storage which is installed from
Note:
sh
=>In the process of establishing communication b/w JavaProgram
Diagram:
Ve
ii
ip ath
=======================================================
Ma
define "driver"?
Audio driver
Video driver
nk
N/W driver
...
Ve
ii
4.Thin driver(Type-4)
ath
Note:
ip
=>In realtime we use 'Thin driver' for application development.
Ma
==================================================================
Dt : 30/4/2022
*imp
sh
Making System Environment ready to construct JDBC Application:
ate
ii
---------- --------------- ---------- ----------
ath
A111 Mouse 1200 12
ip
A105 CDR 1300 13
A104
A100
FDD
CDR
700
1200
3
45
Ma
sh
SQL>
ate
step-5 : Find DB-Jar file and copy into one User defined folder.
nk
C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib
*imp
ojdbc10.jar
ii
Oracle10 - ojdbc14.jar
ath
Oracle11 - ojdbc6.jar
oracle12 - ojdbc7.jar,ojdbc8.jar
ip
other - ojdbc10.jar
MySQL
Ma
- mysql-connector-java-VERSION.jar
SQLite - sqlite-jdbc-VERSION.jar
C:\oraclexe\app\oracle\product\11.2.0\server\network\ADMIN
PortNo : 1521
ServiceName : XE
=====================================================
*imp
JDBC API:
ii
and Interfaces' used in JDBC application development.
ath
=>'java.sql.Connection' interface is the root of JDBC API.
ip
interface:
1.createStatement()
Ma
- this method will create implementation object Statement
interface.
sh
2.prepareStatement()
3.prepareCall()
ate
4.setAutoCommit()
5.getAutoCommit()
nk
6.setSavepoint()
7.removeSavepoint()
Ve
8.commit()
9.rollback()
JavaProgram.
Hierarchy of 'Connection' interface:
ii
ath
===========================================================
ip
Dt : 2/5/2022
Note:
Ma
=>we use getConnection() method from 'java.sql.DriverManager' class
throws java.sql.SQLException;
Ve
syntax:
("DB-url","uname","pword");
Diagram:
ii
ip ath
Ma
sh
ate
nk
Ve
==========================================================
*imp
Types of JDBC-statements:
=>JDBC statements are used to perform operations on DataBase
product.
1.Statement
2.PreparedStatement
3.CallableStatement
ii
ath
1.Statement:
ip
used to execute normal queries without IN parameters.
Ma
=>The fllowing are some important methods from 'Statement'
interface:
(i)executeQuery()
sh
(ii)executeUpdate()
ate
(i)executeQuery():
Method Signature:
throws java.sql.SQLException;
(ii)executeUpdate():
throws java.sql.SQLException;
---------------------------------------------------------
Note:
ii
create the implementation object of 'Statement' interface.
ath
Method Signature of createStatement():
ip
throws java.sql.SQLException;
syntax:
Ma
Statement stm = con.createStatement();
sh
--------------------------------------------------------------
*imp
ate
step-1 : open IDE Eclipse,while opening name the WorkSpace and click
nk
'Launch'
ii
step-5 : Create class in Package and type the code
ath
RightClick on package->new->Class,name the class and click 'finish'
Program No :: 01
ip
package test;
import java.sql.*;
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
while(rs.next()) {
Ve
System.out.println(rs.getString(1)+"\t"
+rs.getString(2)+"\t"
+rs.getFloat(3)+"\t"
+rs.getInt(4));
}//end of loop
con.close();
}catch(Exception e) {e.printStackTrace();}
ii
ath
step-6 : Execute the program
====================================================
ip
Dt : 4/5/2022
faq:
define ResultSet?
Ma
=>ResultSet is an interface from java.sql package and which hold result
sh
of select query.
of 'ResultSet' interface.
first row.
=>we use next() method to move the cursor row-by-row and which is boolean
return type.
Diagram:
ii
ip ath
Ma
================================================================
Ex_Application-2: ( Program No :: 02 )
sh
write JDBC application to read Product details from Console and insert into
DB Table product45.
ate
package test;
import java.sql.*;
import java.util.*;
public class DBCon2 {
nk
ii
}
ip ath
==============================================================
Assignment-1:
Ma
DB Table : Book45(bcode,bname,bauthor,bprice,bqty)
sh
Prog-1 : JDBC Application to read book details from Cosole and insert into
Prog-3 : JDBC Application to display book details based on book code. ( Program No :: 05 )
nk
==============================================================
Assignment-2:
Ve
DB Table : Employee45(eid,ename,edesg,bsal,totsal)
Prog-1 : JDBC Application to read employee details from Cosole and insert into
Note:
Calculate totSal based on bSal using the following formula:
totSal = bSal+HRA+DA;
DA = 63% of bSal
ii
Prog-2 : JDBC Application to display all Employee details ( Program No :: 07 )
ath
Prog-3 : JDBC Application to display Employee details based on eId.
( Program No :: 08 )
=====================================================================
ip
Ma
sh
ate
nk
Ve
Dt : 5/5/2022
Ex_Application :
Program : DBCon3.java
package test;
ii
import java.sql.*;
ath
import java.util.*;;
ip
public static void main(String[] args) {
try {
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
ResultSet rs = stm.executeQuery
if(rs.next()) {
System.out.println(rs.getString(1)+"\t"+
rs.getString(2)+"\t"+rs.getFloat(3)+
"\t"+rs.getInt(4));
}else {
System.out.println("Invalid ProdCode...");
con.close();
s.close();
}catch(Exception e) {e.printStackTrace();}
ii
}
ath
o/p:
ip
A222
A222 KB 1300.0 13
Ma
================================================================
*imp
sh
2.PreparedStatement:
(i)executeQuery()
(ii)executeUpdate()
Ve
(i)executeQuery():
Method Signature:
Method Signature:
----------------------------------------------------------------
ii
=>we use prepareStatement() method from 'Connection' interface to create the
ath
implementation object of 'PreparedStatement' interface.
ip
public abstract java.sql.PreparedStatement prepareStatement(java.sql.String)
syntax:
Ma
throws java.sql.SQLException;
PreparedStatement ps = con.prepareStatement("query-structure");
sh
========================================================================
Prog-1 : JDBC Application to read employee details from Console and insert into
ate
Note:
nk
totSal = bSal+HRA+DA;
DA = 63% of bSal
DB Table : Employee45(eid,ename,edesg,bsal,totsal)
create table Employee45(eid varchar2(10),ename varchar2(15),edesg varchar2(10),
Program : DBCon4.java
package test;
ii
import java.util.*;
ath
import java.sql.*;
ip
public static void main(String[] args) {
try {
Ma
Scanner s = new Scanner(System.in);
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
PreparedStatement ps = con.prepareStatement
ps.setString(1,eId);
ps.setString(2,eName);
ps.setString(3,eDesg);
ii
ps.setInt(4, bSal);
ath
ps.setFloat(5, totSal);
ip
int k = ps.executeUpdate();//Execution process
if(k>0) {
Ma
System.out.println("Employee Details inserted Successfully...");
sh
}
con.close();
ate
s.close();
}catch(Exception e) {e.printStackTrace();}
nk
}
Ve
o/p:
A121
Raj
Enter the EmpDesg:
SE
12000
ii
ip ath
Ma
============================================================
faq:
Note:
Ve
=>we use setter methods to set the data to the fields based on parameter index
==============================================================
faq:
=>In PreparedStatement the query is compiled once and can be executed any
number of times by setting the values.
================================================================
Assignment:
DB Table : UserReg45(uname,pword,fname,lname,addr,mid,phno)
ii
Construct JDBC Application to perform the following operations based on User
ath
Choice:(Using PreparedStatement)
1.Register
ip
2.Login
1.Register:
Ma
=>read user details from console and insert in to DBtable UserReg45.
sh
2.Login:
ate
=>read uname and pword from the console and display the following msg:
Login Successfull...
nk
===========================================================================
Ve
Dt : 7/5/2022
DB Table : UserReg45
ii
( Program No :: 09 )
ath
Program : DBCon5.java
package test;
ip
import java.sql.Connection;
import java.sql.*;
import java.util.*;
Ma
public class DBCon5 {
sh
public static void main(String[] args) {
try {
ate
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
while(true) {
System.out.println("====Choice====");
System.out.println("1.Register\n2.Login\n3.exit");
switch(choice)
case 1:
ii
System.out.println("Enter the UserName:");
ath
String uName = s.nextLine();
ip
String pWord = s.nextLine();
Ma
System.out.println("Enter the FirstName:");
ps1.setString(1,uName);
ps1.setString(2,pWord);
ps1.setString(3,fName);
ps1.setString(4,lName);
ps1.setString(5,addr);
ps1.setString(6,mId);
ps1.setLong(7,phNo);
int k = ps1.executeUpdate();
ii
if(k>0) {
ath
System.out.println("User Registered Successfully");
ip
break;
case 2:
Ma
System.out.println("Enter the UserName:");
String uN = s.nextLine();
sh
System.out.println("Enter the PassWord:");
String pW = s.nextLine();
ate
ps2.setString(1,uN);
nk
ps2.setString(2, pW);
Ve
ResultSet rs = ps2.executeQuery();
if(rs.next()) {
System.out.println("Login Successfull...");
}else {
System.out.println("Invalid Login Process...");
break;
case 3:
System.out.println("Program terminated...");
System.exit(0);
ii
default:
ath
System.out.println("Invalid Choice...");
}//end of switch;
ip
}//end of loop
//s.close();
}catch(Exception e) {e.printStackTrace();}
Ma
}
sh
}
============================================================
ate
Ex_Application:
Program : DBCon6.java
Ve
package test;
import java.sql.*;
import java.util.*;
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
ii
PreparedStatement ps1 = con.prepareStatement
ath
("select * from Product45 where pcode=?");
ip
("update Product45 set pprice=?,pqty=pqty+? where pcode=?");
ps1.setString(1,pCode);
Ma
ResultSet rs = ps1.executeQuery();
sh
if(rs.next()) {
System.out.println("Old price:"+rs.getFloat(3));
ate
System.out.println("Available qty:"+rs.getInt(4));
ps2.setFloat(1,newPrice);
ps2.setInt(2,newQty);
ps2.setString(3, pCode);
int k = ps2.executeUpdate();
if(k>0) {
}else {
System.out.println("Invalid ProdCode...");
ii
}
ath
s.close();
}catch(Exception e) {e.printStackTrace();}
ip
}
}
Ma
===========================================================
Ex_Application:
sh
JDBC Application to delete Product on pCode?
ate
Program : DBCon7.java
package test;
nk
import java.sql.*;
import java.util.*;
Ve
try {
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
ii
("delete from Product45 where pcode=?");
ath
ps1.setString(1,pCode);
ip
ResultSet rs = ps1.executeQuery();
if(rs.next()) {
ps2.setString(1,pCode);
Ma
int k = ps2.executeUpdate();
sh
if(k>0) {
}else {
nk
System.out.println("Invalid ProdCode...");
}
Ve
s.close();
}catch(Exception e) {e.printStackTrace();}
=========================================================
Assignment: ( Program No :: 10 )
1.AddBook
2.ViewAllBooks
3.ViewBookByBookCode
ii
4.UpdateBookByBookCode(price and qty)
ath
5.DeleteBookByBookCode
ip
Dt : 9/5/2020
*imp
3.CallableStatement:
Ma
=>CallableStatement is an interface from java.sql package and
sh
which is used to execute Procedures and Functions on DB-Product.
(java.lang.String)throws java.sql.SQLException;
Ve
syntax
CallableStatement cs = con.prepareCall("Proc/Func");
define Procedure?
structure of procedure:
ii
(para_list) is
ath
begin
query1;
ip
query2;
end;
...
Ma
/
sh
define Function?
ate
Note:
structure of Function:
begin
query1;
query2;
....
return var;
ii
end;
ath
/
========================================================================
ip
*imp
Bank45(accno,custname,balance,acctype)
ate
CustDetails45(accno,addr,mid,phno)
nk
begin
ii
insert into CustDetails45 values(accno,addr,mid,phno);
ath
end;
ip
Ma
step-3 : construct JDBC application to execute procedure
( Program NO :: 11 )
Program : DBCon8.java
sh
package test;
import java.util.*;
ate
import java.sql.*;
try {
Ve
ii
System.out.println("Enter the MailId:");
ath
String mId = s.nextLine();
ip
long phNo = s.nextLong();
Ma
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
sh
CallableStatement cs = con.prepareCall
("{call CreateAccount45(?,?,?,?,?,?,?)}");
ate
cs.setLong(1,accNo);
cs.setString(2,custName);
nk
cs.setFloat(3,bal);
cs.setString(4,accType);
Ve
cs.setString(5,addr);
cs.setString(6, mId);
cs.setLong(7, phNo);
cs.execute();
System.out.println("Procedure executed Successfully...");
con.close();;
s.close();
}catch(Exception e) {e.printStackTrace();}
ii
}
ath
o/p:
ip
6123456
Raj
Ma
Enter the Balance:
sh
12000
savings
SrNagar
7878781234
---------------------------------------------------------
Diagram:
ii
ath
=========================================================
Assignment:
ip
Create and execute procedure
Ma
Step-1 : Construct DB Tables
sh
EmpData45(eid,ename,edesg)
ate
EmpAddress45(eid,hno,sname,city,pincode)
EmpContact45(eid,mid,phno)
EmpSalary45(eid,bsal,totsal)
nk
=========================================================
Dt : 10/5/2022
Types of Procedures:
(i)IN-Parameter Procedures
(ii)OUT-Parameter Procedures
(i)IN-Parameter Procedures:
=>The procedures which take the data from JavaProgram and update
Ex:
above program(DBCon8.java)
ii
ath
(ii)OUT-Parameter Procedures:
=>The procedures which take the data from DB-Tables and sent to
ip
JavaProgram are known as OUT-Parameter Procedures.
Ex:
Ma
Construct Procedure to display the Complete details of
sh
Customer based on accno.
ate
accno.
nk
begin
( Program No :: 12 )
Program : DBCon9.java
ii
package test;
ath
import java.util.*;
import java.sql.*;
ip
public class DBCon9 {
Ma
public static void main(String[] args) {
try {
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
nk
CallableStatement cs = con.prepareCall
("{call RetrieveDetails45(?,?,?,?,?,?,?)}");
Ve
cs.setLong(1, accNo);
cs.registerOutParameter(2,Types.VARCHAR);
cs.registerOutParameter(3,Types.FLOAT);
cs.registerOutParameter(4,Types.VARCHAR);
cs.registerOutParameter(5,Types.VARCHAR);
cs.registerOutParameter(6,Types.VARCHAR);
cs.registerOutParameter(7,Types.BIGINT);
cs.execute();
System.out.println("AccNo:"+accNo);
System.out.println("CustName:"+cs.getString(2));
System.out.println("Balance:"+cs.getFloat(3));
ii
System.out.println("AccType:"+cs.getString(4));
ath
System.out.println("Address:"+cs.getString(5));
System.out.println("MailId:"+cs.getString(6));
ip
System.out.println("PhoneNO:"+cs.getLong(7));;
s.close();
Ma
}catch(Exception e) {e.printStackTrace();}
}
sh
}
ate
o/p:
6123456
AccNo:6123456
Ve
CustName:Raj
Balance:12000.0
AccType:savings
Address:SrNagar
MailId:[email protected]
PhoneNO:7878781234
-----------------------------------------------------------
faq:
ii
OUT-Parameter procedure.
ath
------------------------------------------------------------
faq:
ip
wt is the advantage of Procedures?
Ma
=>Using Procedures we can execute multiple queries at-a-time and
application.
sh
-----------------------------------------------------------
Assignment:
ate
based on eId.
nk
=================================================================
*imp
Ve
begin
return bal;
end;
ii
ath
step-2 : JDBC Application to execute function
( Program No :: 13 )
ip
Program : DBCon10.java
package test;
import java.util.*;
Ma
import java.sql.*;
sh
public class DBCon10 {
try {
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
CallableStatement cs = con.prepareCall
("{call ? := RetrieveBalance45(?)}");
cs.registerOutParameter(1,Types.FLOAT);
cs.setLong(2,accNo);
cs.execute();
System.out.println("AccNo:"+accNo);
System.out.println("Balance:"+cs.getFloat(1));
con.close();
s.close();
ii
}catch(Exception e) {e.printStackTrace();}
ath
}
ip
o/p:
6123456
Ma
AccNo:6123456
sh
Balance:12000.0
=========================================================
ate
Assignment:
=========================================================
Ve
=========================================================
Dt : 12/5/2022
process'.
ii
Behaviour:
ath
(i)User picks the DataBase connection from the Pool.
ip
(iii)After usage returns the Connection back to the pool.
Note:
Ma
=>we take the support of Vector<E> to construct Connection
sh
Pooling Process.
Hierarchy of Vector<E>:
Ve
ii
ath
-------------------------------------------------------
ip
Ex_program: ( Program No :: 14 )
ConnectionPool.java
Ma
package test;
import java.sql.*;
sh
import java.util.*;
ate
this.url=url;
Ve
this.uname=uname;
this.pword=pword;
{
try {
while(v.size()<5)
Connection con=DriverManager.getConnection
(url,uname,pword);
ii
v.add(con);//Adding the connection to Pool
ath
System.out.println(con);
}//end of loop
ip
if(v.size()==5)
{
Ma
System.out.println("Connection Pool is full...");
}
sh
}catch(Exception e) {e.printStackTrace();}
}//end of method
ate
{
nk
return con;
}//end of method
DBCon12.java
ii
package test;
ath
import java.util.*;
import java.sql.*;
public class DBCon12 {
public static void main(String[] args) {
ConnectionPool cp = new ConnectionPool
ip
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
Ma
cp.createConnections();
System.out.println("Pool Size:"+cp.v.size());
Connection con = cp.useConnection();
System.out.println("User using : "+con);
System.out.println("Pool Size:"+cp.v.size());
cp.returnConnection(con);
sh
System.out.println("Pool Size:"+cp.v.size());
System.out.println("====Display the Connection from
Pool====");
ate
cp.v.forEach((k)->
{
System.out.println(k);
});
nk
}
}
Ve
Ve
nk
ate
sh
Ma
ip ath
ii
Dt : 13/5/2022
*imp
ii
(a)addBatch()
ath
(b)executeBatch()
(c)clearBatch()
ip
(a)addBatch():
Ma
=>This addBatch() method is used to add query to the batch.
Method Signature:
sh
public abstract void addBatch(java.lang.String)
throws java.sql.SQLException;
ate
(b)executeBatch():
nk
Method Signature:
(c)clearBatch():
Method Signature:
-----------------------------------------------------
ii
package test;
ath
import java.sql.*;
public class DBCon13 {
public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection
ip
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
Statement stm = con.createStatement(); Ma
stm.addBatch
("insert into Product45 values('B123','ER',123,12)");
stm.addBatch
("insert into Bank45
values(456,'Alex',234,'savings')");
sh
stm.addBatch
("insert into CustDetails45
values(456,'SRN','a@..',7878)");
ate
System.out.println("Data updated...");
}//end of loop
stm.clearBatch();
con.close();
Ve
}catch(Exception e) {e.printStackTrace();}
}
}
Note:
DBCon14.java
package test;
import java.sql.*;
public class DBCon14 {
public static void main(String[] args) {
ii
try {
ath
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
PreparedStatement ps = con.prepareStatement
("insert into Product45 values(?,?,?,?)");
ip
ps.setString(1,"C111");
ps.setString(2,"TRY"); Ma
ps.setFloat(3,234);
ps.setInt(4,12);
ps.addBatch();
ps.setString(1,"C222");
ps.setString(2,"Catch");
sh
ps.setFloat(3,244);
ps.setInt(4,11);
ps.addBatch();
ate
System.out.println("Data Updated...");
}
ps.clearBatch();
con.close();
Ve
}catch(Exception e) {e.printStackTrace();}
}
}
Note:
faq:
DataBase only once and executes all the queries from the batch
ii
HighPerformance of an application.
ath
==========================================================
faq:
ip
wt is the diff b/w
(i)Batch Processing
(ii)Procedures
Ma
=>using Batch Processing we can execute only Non-Select queries
sh
on DataBase product,which means it is Batch Update processing.
===========================================================
*imp
nk
Bottom-of-table-data.
Ex:
ii
ath
*imp
ip
=>In Scrollable ResultSet object the cursor can be moved in two
Ma
directions,which means down the table data and upward the table data.
PreparedStatement ps = con.prepareStatement("query-S",type,mode);
nk
Type:
Mode:
Note:
'type' specifies the direction of the cursor and 'mode' specifies the
ii
ath
The following are some Methods used to control cursor on Scrollable
ip
ResultSet object:
Ma
afterLast() =>Moves the cursor after the Last row
sh
beforeFirst() =>Moves the cursor before the First row
ate
---------------------------------------------------------
Dt : 16/5/2022
ii
ath
Program : DBCon15.java
package test;
import java.sql.*;;
ip
public class DBCon15 {
public static void main(String[] args) { Ma
try {
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
Statement stm = con.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
sh
ResultSet rs = stm.executeQuery("select * from
Product45");
System.out.println("====Display Product in
ate
reverse====");
rs.afterLast();//Cursor pointing after last row
while(rs.previous()) {
System.out.println(rs.getString(1)+"\t"+rs.getString(2)+
nk
"\t"+rs.getFloat(3)+"\t"+rs.getInt(4));
}//end of loop
con.close();;
Ve
}catch(Exception e) {e.printStackTrace();}
}
}
o/p:
A545 ER 123.0 12
ii
B123 ER 123.0 12
ath
-------------------------------------------------------
ip
package test;
import java.sql.*;
public class DBCon16 {
public static void main(String[] args) {
try {
Ma
Connection con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
PreparedStatement ps = con.prepareStatement
sh
("select * from Product45",
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ate
ResultSet rs = ps.executeQuery();
System.out.println("====Display Product in
reverse====");
rs.afterLast();//Cursor pointing after last row
while(rs.previous()) {
nk
System.out.println(rs.getString(1)+"\t"+rs.getString(2)+
"\t"+rs.getFloat(3)+"\t"+rs.getInt(4));
Ve
}//end of loop
System.out.println("====Display Last row====");
rs.last();//Cursor pointing to last row
System.out.println(rs.getString(1)+"\t"+rs.getString(2)+
"\t"+rs.getFloat(3)+"\t"+rs.getInt(4));
System.out.println("====Display First row====");
rs.first();//Cursor pointing to first row
System.out.println(rs.getString(1)+"\t"+rs.getString(2)+
"\t"+rs.getFloat(3)+"\t"+rs.getInt(4));
System.out.println("====Display row number 4====");
rs.absolute(4);//Cursor pointing to 4th row
System.out.println(rs.getString(1)+"\t"+rs.getString(2)+
"\t"+rs.getFloat(3)+"\t"+rs.getInt(4));
System.out.println("====Display relative(+1)====");
rs.relative(+1);//Cursor moved forward by one row
System.out.println(rs.getString(1)+"\t"+rs.getString(2)+
"\t"+rs.getFloat(3)+"\t"+rs.getInt(4));
ii
con.close();
}catch(Exception e) {e.printStackTrace();}
ath
}
}
ip
o/p:
A545 ER 123.0 12
ate
B123 ER 123.0 12
B123 ER 123.0 12
====Display row number 4====
====Display relative(+1)====
=============================================================
*imp
ii
define 'RowSet'?
ath
=>RowSet object will encapsulate the rows generated from ResultSets
ip
=>RowSet is an interface from javax.sql package and which is
(a)JDBCRowSet
sh
(b)CachedRowSet
=>WebRowSet
ate
(i)FilteredRowSet
(ii)JoinRowSet
nk
Hierarchy of RowSet:
Ve
-----------------------------------------------------
faq:
(i)JdbcRowSet
(ii)CachedRowSet
(i)JdbcRowSet:
active.
(ii)CachedRowSet:
ii
=>cachedRowSet will hold ResultSet,but connection to DataBase is
ath
Dis-Connected automatically.
--------------------------------------------------------------
ip
Note:
Ma
=>WebRowSet is used to transfer the data from one layer to another
=========================================================
ate
*imp
define RowSetFactory?
nk
RowSet:
(a)createJdbcRowSet()
(b)createCachedRowSet()
(c)createWebRowSet()
(d)createFilteredRowSet()
(e)createJoinRowSet()
(a)createJdbcRowSet():
'JdbcRowSet'.
Method Signature:
ii
public abstract javax.sql.rowset.JdbcRowSet createJdbcRowSet()
ath
throws java.sql.SQLException;
ip
(b)createCachedRowSet():
Ma
=>This method is used to create the implementation object of
'CachedRowSet'.
Method Signature:
sh
public abstract javax.sql.rowset.CachedRowSet createCachedRowSet()
throws java.sql.SQLException;
ate
(c)createWebRowSet():
nk
'WebRowSet'.
Ve
Method Signature:
throws java.sql.SQLException;
(d)createFilteredRowSet():
=>This method is used to create the implementation object of
'FilteredRowSet'.
Method Signature:
throws java.sql.SQLException;
ii
(e)createJoinRowSet():
ath
=>This method is used to create the implementation object of 'JoinRowSet'.
Method Signature:
ip
public abstract javax.sql.rowset.JoinRowSet createJoinRowSet()
throws java.sql.SQLException;
Ma
Note:
sh
=>we use the following methods from 'javax.sql.rowset.RowSetProvider'
interface.
nk
throws java.sql.SQLException;
Ve
(java.lang.String, java.lang.ClassLoader)
throws java.sql.SQLException;
===================================================================
Dt : 17/5/2022 (JDBC APP_17)
Ex_Program : DBCon17.java
package test;
import java.util.*;
import javax.sql.rowset.*;
ii
public static void main(String[] args) {
ath
try {
ip
Class.forName("oracle.jdbc.driver.OracleDriver");
Ma
RowSetFactory rsf = RowSetProvider.newFactory();
System.out.println("===Choice====");
sh
System.out.println("1.JdbcRowSet\n2.CachedRRowSet");
switch(choice)
nk
case 1:
Ve
jrs.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
jrs.setUsername("system");
jrs.setPassword("manager");
while(jrs.next()) {
System.out.println(jrs.getString(1)+"\t"+
jrs.getString(2)+"\t"+jrs.getFloat(3)+"\t"+
jrs.getInt(4));
}//end of loop
ii
break;
ath
case 2:
ip
crs.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
crs.setUsername("system");
crs.setPassword("manager");
Ma
crs.setCommand("select * from Bank45");
sh
crs.execute();
while(crs.next()) {
ate
System.out.println(crs.getLong(1)+"\t"+
crs.getString(2)+"\t"+crs.getFloat(3)+"\t"+
nk
crs.getString(4));
}//end of loop
Ve
break;
default:
System.out.println("Invalid Choice...");
}//end of switch;
s.close();
}catch(Exception e) {e.printStackTrace();}
o/p:
===Choice====
1.JdbcRowSet
ii
2.CachedRRowSet
ath
Enter the Choice:
ip
6123456 Raj 9000.0 savings
313131
56565 Alex
Ram 3500.0 Savings
234.0 savings
Ma
456 Alex 234.0 savings
sh
=============================================================
2.String Objects
nk
3.WrapperClass Objects
4.Array objects
Ve
5.Collection<E> objects
6.Map<K,V> objects
7.Enum<E> object
2.Statement Object
3.PreparedStatement Object
4.CallableStatement Object
ii
7.RowSet Object
ath
(i)JdbcRowSet Object
(ii)CachedRowSet Object
ip
=>WebRowSet Object
(i)FiltertedRowSet Object
(ii)JoinRowSet Object
Ma
8.Metadata Objects
sh
(i)DatabaseMetaData object
(ii)ParameterMetaData Object
ate
(iii)ResultSetMetaData Object
(iv)RowSetMetaData Object
nk
Diagram:
Ve
ii
ath
===================================================================
ip
define Metadata in JDBC?
is known as Metadata.
Ma
=>According to Object Oriented proggramming,Metadata means one object
sh
holding information about another object.
1.DatabaseMetaData
2.ParameterMetaData
nk
3.ResultSetMetaData
4.RowSetMetaData
Ve
1.DatabaseMetaData:
syntax:
DatabaseMetaData dmd = con.getMetaData();
2.ParameterMetaData:
syntax:
ii
ParameterMetaData pmd = ps.getParameterMetaData();
ath
3.ResultSetMetaData :
ip
=>ResultSetMetaData is an interface from java.sql package and
Ma
which is used to hold the information about ResultSet Object.
syntax:
4.RowSetMetaData:
ate
syntax:
Ve
Ex:
package test;
import java.sql.*;
import javax.sql.rowset.*;
import javax.sql.*;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
ii
Connection con = DriverManager.getConnection
ath
("jdbc:oracle:thin:@localhost:1521:XE","system","manager");
ip
System.out.println("DriverVersion:"+dmd.getDriverMajorVersion());
Ma
PreparedStatement ps = con.prepareStatement
ps.setString(1,"");
sh
ParameterMetaData pmd = ps.getParameterMetaData();
System.out.println("Count:"+pmd.getParameterCount());
ate
ResultSet rs = ps.executeQuery();
System.out.println("Column count:"+rsmd.getColumnCount());
Ve
jrs.setUrl("jdbc:oracle:thin:@localhost:1521:XE");
jrs.setUsername("system");
jrs.setPassword("manager");
System.out.println(rsmd2.getColumnCount());
con.close();
jrs.close();
}catch(Exception e) {System.out.print(e.getMessage());}
ii
}
ath
}
============================================================
ip
faq:
define Stream?
Ma
=>The Continuous flow of data is known as Stream.
sh
Types of Streams:
2.Character Stream
nk
Stream.
=>Character Stream is preferable for Text data and not preferable for
----------------------------------------------------------
faq:
ii
wt is the diff b/w
ath
(i)input stream
(ii)output stream
ip
(i)input stream:
Ma
=>The stream into JavaProgram is known as input stream.
Ex:
sh
JavaProgram reading stream from file
(ii)output stream:
ate
Ex:
nk
=====================================================================
Ve
Note:
1.BLOB
2.CLOB
1.BLOB:
=>BLOB stands for 'Binary Large OBjects' and which is used to store binary
2.CLOB:
=>CLOB stands for 'Character Large OBjects' and which is used to store
ii
Character Stream data.(Text data)
ath
=======================================================================
*imp
ip
Servlet Programming:(Unit-2)
Diagram:
Ve
ii
ip ath
Ma
=========================================================
sh
ate
nk
Ve
Dt : 18/5/2022
Types of Applications:
(a)StandAlone Applications
(b)Web Applications
(c)Enterprise Applications
ii
(d)Mobile Applications
ath
(a)StandAlone Applications:
ip
=>The applications which are installed in one computer
Ma
and performs actions in the same computer are known as
StandAlone Applications.
Note:
ate
No HTML input
nk
No Server Environment
No DataBase Storage
Ve
(i)CUI Applications
(ii)GUI Applications
(i)CUI Applications:
ii
(ii)GUI Applications:
ath
=>The applications in which the user interacts through
ip
(GUI - Graphical User Interface)
Note:
Ma
=>we use AWT(Abstract Window Toolkit) and Swings to design
sh
GUI components
--------------------------------------------------
ate
(b)Web Applications:
Note:
Application Servers.
------------------------------------------------------
(c)Enterprise Applications:
ii
-------------------------------------------------------
ath
(d)Mobile Applications:
ip
are known as Mobile Applications.
==========================================================
faq:
Ma
define Server?
sh
=>Server means service provider,which means accepting the
define Client?
nk
Client.
Ve
imp
Types of Servers:
(i)WebServers
(ii)Application Servers
(i)WebServer:
html pages.
ii
=>Web server consumes less resources like CPU, Memory etc. as
ath
compared to application server.
ip
applications.
enterprise applications.
------------------------------------------------------------------
*imp
ii
ath
webserver - Tomcat 9.x
ip
vendor - Apache org
default port no
download
- 8080
- www.apache.org(Open source)
Ma
sh
Note:
(i)Servlet container
(ii)JSP Container
nk
ii
User Name : Venkatesh
ath
Password : nit
(click next)
ip
step-3 : Start the Tomcat Server
Ma
=>To start Tomcat server click on 'startup' or 'Tomcat9w'
sh
from 'bin' of Tomcat
C:\Tomcat 9.0\bin
ate
nk
following URL:
Ve
http://localhost:8081
C:\Tomcat 9.0\bin
===========================================================
Dt : 19/5/2022
*imp
Servlet API:
ii
=>'javax.servlet' package is known as Servlet API and which
ath
provide classes and interfaces used in Servlet application
development.
ip
=>'javax.servlet.Servlet' interface is the root of Servlet API.
-------------------------------------------------------
Note:
(a)GenericServlet
(b)HttpServlet
(a)GenericServlet:
ii
the following Life-Cycle methods are available
ath
(i)init()
(ii)service()
ip
(iii)destroy()
Ma
=>These methods are automatically executed in the same order.
(i)init()
(ii)service()/doPost()/doGet()
nk
(iii)destroy()
==================================================
*imp
click finish
ii
Add External Jars'->Browse and select 'servlet-api.jar' file
ath
from 'lib' of Tomcat->open-Apply->Apply and Close.
ip
step-4 : Add Tomcat Server to IDE environment
Ma
Click Servers->click 'click this link to create new server'->
input.html
<!DOCTYPE html>
Ve
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="dis" method="post">
UserName:<input type="text" name="uname"><br>
MailId:<input type="text" name="mid"><br>
<input type="submit" value="Display">
</form>
</body>
</html>
DisplayServlet.java
package test;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
ii
ath
@SuppressWarnings("serial")
@WebServlet("/dis")
ip
public void init()throws ServletException{
Ma
//NoCode
IOException{
PrintWriter pw = res.getWriter();
Ve
res.setContentType("text/html");
pw.println("====UserDetails===");
pw.println("<br>UserName:"+uName);
pw.println("<br>MailId:"+mId);
web.xml
ii
</welcome-file-list>
ath
</web-app>
ip
select the server and click finish. Ma
=====================================================
sh
ate
nk
Ve
Dt:21/5/2022
Assignment-1:(Solution)
product.html
<!DOCTYPE html>
<html>
ii
<head>
ath
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="dis" method="post">
ip
ProductCode:<input type="text" name="pcode"><br>
ProductName:<input type="text" name="pname"><br>
Ma
ProductPrice:<input type="text" name="pprice"><br>
ProductQty:<input type="text" name="pqty"><br>
<input type="submit" value="Display">
</form>
</body>
</html>
sh
DisplayServlet.java
ate
package test;
import java.io.*;
nk
import javax.servlet.*;
import javax.servlet.annotation.*;
Ve
@SuppressWarnings("serial")
@WebServlet("/dis")
//NoCode
}
public void service(ServletRequest req,ServletResponse res)
throws ServletException,IOException{
String pC = req.getParameter("pcode");
String pN = req.getParameter("pname");
float pP = Float.parseFloat(req.getParameter("pprice"));
int pQ = Integer.parseInt(req.getParameter("pqty"));
ii
PrintWriter pw = res.getWriter();
ath
res.setContentType("text/html");
pw.println("ProdCode:"+pC);
ip
pw.println("<br>ProdName:"+pN);
pw.println("<br>ProdPrice:"+pP);
pw.println("<br>ProdQty:"+pQ);
Ma
}
sh
public void destroy() {
//NoCode
ate
}
nk
web.xml
<web-app>
<welcome-file-list>
<welcome-file>product.html</welcome-file>
</welcome-file-list>
</web-app>
===============================================================
Note:
syntax:
RequestDispatcher rd = req.getRequestDispatcher("url-pattern/HTML/JSP");
rd.forward(req,res);
ii
rd.include(req,res);
ath
Ex:
ip
input.html
<!DOCTYPE html>
<html>
<head>
Ma
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
sh
<body>
<form action="choice" method="post">
Enter the Value1:<input type="text" name="v1"><br>
ate
</html>
ChoiceServlet.java
Ve
package test;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
@SuppressWarnings("serial")
@WebServlet("/choice")
//NoCode
ii
throws ServletException,IOException{
ath
String s1 = req.getParameter("s1");
if(s1.equals("Add")) {
ip
RequestDispatcher rd=req.getRequestDispatcher("ad");
}else {
rd.forward(req, res);
Ma
RequestDispatcher rd=req.getRequestDispatcher("sb");
sh
rd.forward(req, res);
}
ate
//NoCode
}
Ve
AdditionServlet.java
package test;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
@SuppressWarnings("serial")
@WebServlet("/ad")
//NoCode
ii
}
ath
public void service(ServletRequest req,ServletResponse res)
throws ServletException,IOException{
ip
int v1 = Integer.parseInt(req.getParameter("v1"));
Ma
int v2 = Integer.parseInt(req.getParameter("v2"));
int v3 = v1+v2;
PrintWriter pw = res.getWriter();
sh
res.setContentType("text/html");
pw.println("Sum:"+v3+"<br>");
ate
RequestDispatcher rd = req.getRequestDispatcher("input.html");
rd.include(req, res);
nk
//NoCode
SubtractionServlet.java
package test;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
@SuppressWarnings("serial")
@WebServlet("/sb")
ii
public void init()throws ServletException{
ath
//NoCode
ip
public void service(ServletRequest req,ServletResponse res)
throws ServletException,IOException{
Ma
int v1 = Integer.parseInt(req.getParameter("v1"));
int v2 = Integer.parseInt(req.getParameter("v2"));
sh
int v3 = v1-v2;
PrintWriter pw = res.getWriter();
ate
res.setContentType("text/html");
pw.println("Sub:"+v3+"<br>");
nk
RequestDispatcher rd = req.getRequestDispatcher("input.html");
rd.include(req, res);
Ve
//NoCode
}
web.xml
Diagram:
ii
ip ath
Ma
sh
-----------------------------------------------------------------
Assignment-1:
ate
=>MultiplicationServlet
nk
=>DivisionServlet
=>ModuloDivisionServlet
Ve
-------------------------------------------------------------
Assignment-2:
ip
Ma
sh
ate
nk
Ve
Dt : 23/5/2022
Assignment-2:(Solution)
input.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
ii
<title>Insert title here</title>
ath
</head>
<body>
<form action="choice" method="post">
<input type="submit" value="Book" name="s1">
<input type="submit" value="Product" name="s1">
ip
</form> Ma
</body>
</html>
book.html
<!DOCTYPE html>
sh
<html>
<head>
<meta charset="ISO-8859-1">
ate
product.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="product" method="post">
ProdCode:<input type="text" name="pcode"><br>
ProdName:<input type="text" name="pname"><br>
ProdPrice:<input type="text" name="pprice"><br>
ProdQty:<input type="text" name="pqty"><br>
<input type="submit" value="DisplayProductDetails">
</form>
ii
</body>
</html>
ath
ChoiceServlet.java
package test;
ip
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
Ma
@SuppressWarnings("serial")
sh
@WebServlet("/choice")
//NoCode
nk
throws ServletException,IOException{
String s1 = req.getParameter("s1");
if(s1.equals("Book")) {
RequestDispatcher rd = req.getRequestDispatcher("book.html");
rd.forward(req, res);
}else {
RequestDispatcher rd = req.getRequestDispatcher("product.html");
rd.forward(req, res);
ii
//NoCode
ath
}
ip
BookServlet.java
package test;
import java.io.*;
Ma
import javax.servlet.*;
sh
import javax.servlet.annotation.*;
@SuppressWarnings("serial")
ate
@WebServlet("/book")
//NoCode
Ve
throws ServletException,IOException{
PrintWriter pw = res.getWriter();
res.setContentType("text/html");
pw.println("====BookDetails====");
pw.println("<br>BookCode:"+req.getParameter("bcode"));
pw.println("<br>BookName:"+req.getParameter("bname"));
pw.println("<br>BookAuthor:"+req.getParameter("bauthor"));
pw.println("<br>BookPrice:"+req.getParameter("bprice"));
pw.println("<br>BookQty:"+req.getParameter("bqty"));
ii
pw.println("<br>");
ath
RequestDispatcher rd=req.getRequestDispatcher("input.html");
rd.include(req, res);
ip
}
//NoCode
Ma
}
sh
}
ProductServlet.java
ate
package test;
import java.io.*;
nk
import javax.servlet.*;
import javax.servlet.annotation.*;
Ve
@SuppressWarnings("serial")
@WebServlet("/product")
//NoCode
}
throws ServletException,IOException{
PrintWriter pw = res.getWriter();
res.setContentType("text/html");
pw.println("====ProductDetails=====");
ii
pw.println("<br>ProdCode:"+req.getParameter("pcode"));
ath
pw.println("<br>ProdName:"+req.getParameter("pname"));
pw.println("<br>ProdPrice:"+req.getParameter("pprice"));
ip
pw.println("<br>ProdQty:"+req.getParameter("pqty"));
pw.println("<br>");
Ma
RequestDispatcher rd = req.getRequestDispatcher("input.html");
rd.include(req, res);
sh
}
//NoCode
}
nk
web.xml
Ve
=====================================================================
*imp
define Java Bean Class?
=>The classes which are constructed with the following rules are known as
ii
Rule-3 : The class must be declared with 0-argument constructor or 0-parameter
ath
Constructor.
Rule-4 : The class must be declared with 'Setter' and 'Getter' methods.
ip
define Setter methods?
Ma
=>The methods which are used to load the data to object are known as 'Setter'
methods.
sh
=>The methods which are used to get the data from the object are known as
Getter methods.
nk
=>Every Variable in Class must have its own Setter method and Getter method.
Note:
=>These Java Bean Classes will generate bean objects and these bean objects
will hold data going on to DataBase or bean Objects will hold data coming from
DataBase.
-----------------------------------------------------------------
(i)Serializable objects
(ii)NonSerializable Objects
ii
(i)Serializable objects:
ath
=>The objects which support Serialization process are known as Serializable
ip
=>These Serializable objects can travel on N/W.
Ma
=>To generate Serializable objects the classes must be implemented from
java.io.Serializable interface.
sh
(ii)NonSerializable Objects:
=>The Objects which will not support Serialization process are known as
ate
NonSerializable objects.
Ex:
nk
-----------------------------------------------------------------
Ve
*imp
==============================================================
ii
ip ath
Ma
sh
ate
nk
Ve
Dt : 24/5/2022
*imp
ii
(i)setAttribute()
ath
(ii)getAttribute()
(iii)removeAttribute()
ip
(iv)getAttributeNames()
(i)setAttribute():
Ma
=>setAttribute() method is used to add 'attribute' to the objects.
sh
Method Signature:
(ii)getAttribute():
nk
=>This getAttribute() method is used to get the attribute from the Objects.
Method Signature:
Ve
(iii)removeAttribute():
Method Signature:
public abstract void removeAttribute(java.lang.String);
(iv)getAttributeNames():
the objects.
Method Signature:
ii
------------------------------------------------
ath
Scope of 'attribute':
ip
of WebApplication.
Ma
=>'attribute' in ServletRequest object can be accessed by Second Servlet
==========================================================================
faq:
define DAO?
=>DAO stands for 'Data Access Object' and which is separate layer in MVC(Model
Diagram:
ii
ip ath
Note:
Ma
=>In the process of establishing communiation b/w Servlet Program and DataBase
ServletApplication : ProductApp
choice.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
ii
<title>Insert title here</title>
ath
</head>
<body>
<a href="product.html">AddProduct</a>
<a href="view">ViewProducts</a>
</body>
ip
</html>
product.html
<!DOCTYPE html>
Ma
<html>
<head>
<meta charset="ISO-8859-1">
sh
<title>Insert title here</title>
</head>
<body>
ate
</html>
ProductBean.java
package test;
import java.io.*;
@SuppressWarnings("serial")
public class ProductBean implements Serializable{
private String code,name;
private float price;
private int qty;
public ProductBean() {}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
ii
this.name = name;
}
ath
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
ip
}
public int getQty() { Ma
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
sh
}
ate
AddProductServlet.java
package test;
nk
import java.io.*;
import javax.servlet.*;
Ve
import javax.servlet.annotation.*;
@SuppressWarnings("serial")
@WebServlet("/add")
throws ServletException,IOException{
pb.setCode(req.getParameter("pcode"));
ii
pb.setName(req.getParameter("pname"));
ath
pb.setPrice(Float.parseFloat(req.getParameter("pprice")));
pb.setQty(Integer.parseInt(req.getParameter("pqty")));
ip
PrintWriter pw = res.getWriter();
res.setContentType("text/html");
Ma
sh
int k = new InsertDAO().insert(pb);
if(k>0) {
ate
RequestDispatcher rd=
nk
req.getRequestDispatcher("choice.html");
rd.include(req, res);
Ve
//NoCode
}
}
DBConnection.java
package test;
import java.sql.*;
public class DBConnection {
private static Connection con=null;//reference variable
private DBConnection() {}
static
{
try {
ii
Class.forName("oracle.jdbc.driver.OracleDriver");
ath
con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
}catch(Exception e) {e.printStackTrace();}
}
ip
public static Connection getCon()
{ Ma
return con;
}
}
InsertDAO.java
sh
package test;
import java.sql.*;
ate
try {
Connection con = DBConnection.getCon();
//Accessing the Connection
PreparedStatement ps = con.prepareStatement
Ve
package test;
import java.sql.*;
import java.util.*;
ii
public ArrayList<ProductBean> al = new ArrayList<ProductBean>();
ath
public ArrayList<ProductBean> retrieve()
ip
try {
Ma
Connection con = DBConnection.getCon();
PreparedStatement ps = con.prepareStatement
sh
("select * from Product45");
ResultSet rs = ps.executeQuery();
ate
while(rs.next())
{
nk
pb.setCode(rs.getString(1));
Ve
pb.setName(rs.getString(2));
pb.setPrice(rs.getFloat(3));
pb.setQty(rs.getInt(4));
}//end of loop
}catch(Exception e) {e.printStackTrace();}
return al;
ViewProductsServlet.java
package test;
ii
import java.io.*;
ath
import java.util.*;
import javax.servlet.*;
ip
import javax.servlet.annotation.*;
@SuppressWarnings("serial")
@WebServlet("/view")
Ma
public class ViewProductsServlet extends GenericServlet{
sh
public void init()throws ServletException{
//NoCode
ate
throws ServletException,IOException{
PrintWriter pw = res.getWriter();
res.setContentType("text/html");
if(al.size()==0) {
}else {
Iterator<ProductBean> it = al.iterator();
while(it.hasNext())
ProductBean pb = (ProductBean)it.next();
pw.println(pb.getCode()+"  "+
pb.getName()+"  "+pb.getPrice()+
ii
"  "+pb.getQty()+"<br>");
ath
}//end of loop
}//end of else
ip
RequestDispatcher rd = req.getRequestDispatcher("choice.html");
}
rd.include(req, res);
Ma
public void destroy() {
sh
//NoCode
}
ate
web.xml
nk
<welcome-file>choice.html</welcome-file>
</welcome-file-list>
</web-app>
Diagram:
ii
ath
===============================================================
ip
Ma
sh
ate
nk
Ve
Dt:26/5/2022
define Iterator<E>?
(a)hasNext()
ii
(b)next()
ath
(c)remove()
(d)forEachRemaining()
ip
(a)hasNext():
Ma
=>hasNext() method will check the element is available or not,and generate
boolean result.
sh
Method Signature:
(b)next():
nk
=>This next() method is used to take the element from Collection<E> object.
Method Signature:
Ve
(c)remove():
Method Signature:
public default void remove();
(d)forEachRemaining():
Method Signature:
ii
public default void forEachRemaining(java.util.function.Consumer<? super E>);
ip ath
define iterator() method?
Ma
=>iterator() method is used to create the implementation object of Iterator<E>
interface and the object will hold the reference of Collection<E> object,in this
process the iterator() method also generate cursor pointing before the first
sh
element of Collection<E> object.
ate
syntax:
Iterator<ProductBean> it = al.iterator();
nk
=======================================================================
Assignment:
Ve
=>AddBook
=>ViewBooks
=>EditBookDetails(based on BookCode)
=>DeleteBook(based on BookCode)
==========================================================================
faq:
define request?
=>The query generated from user or client through WebBrowser is known as request.
Diagram:
ii
ath
Types of requests:
ip
=>Requests are categorized into two types:
1.POST request
2.GET request
Ma
sh
1.POST request :
=>The request generated to send the data to Server is known as POST request.
ate
=>Through POST request we can send all types of data like Text,Audio,Video,
=>The data which is sent through POST request is secured because the data is
Ve
...
</form>
=>we use doPost() method from HttpServlet to accept POST request.
Method Signature:
javax.servlet.http.HttpServletResponse)throws javax.servlet.ServletException,
java.io.IOException;
ii
ath
2.GET request"
=>The request generated to get the data from the Server is known as GET request.
ip
=>Through GET request we can send only text data.
Ma
=>Through GET request we can send only limited data,which means up to 4kb or 8kb.
=>The data which is sent through GET request is not secured,because the data is
...
</form>
Ve
<form action="url">
...
</form>
Method Signature:
javax.servlet.http.HttpServletResponse)throws javax.servlet.ServletException,
java.io.IOException;
ii
=============================================================
ip ath
Ma
sh
ate
nk
Ve
Dt : 27/5/2022
*imp
define Session?
ii
ath
define Session Tracking process?
=>The process of tracking the 'user state' from login to logout is known as
ip
Session Tracking process.
Ma
=>We use the following four techniques to perform Session Tracking process:
(a)Cookie
(b)HttpSession
sh
(c)URL re-write
(a)Cookie:
nk
cookie.
Ve
(i)Persistent Cookies
(ii)Non-Persistent Cookies
(i)Persistent Cookies:
=>The Cookies which are available in WebBrowser until user logs out are
(ii)Non-Persistent Cookies:
=>The Cookies which are destroyed automatically when the WebBrowser is closed
ii
are known as Non-Persistent Cookies.
ath
---------------------------------------------------------------------
ip
process.
Hierarchy of Cookie:
Ma
sh
ate
nk
-----------------------------------------------------------
ii
=>we use the following process to construct Cookie Session Tracking:
ath
step-1 : When the Login process is Successfull then construct the Cookie.
ip
syntax:
res.addCookie(ck);
ate
systax:
syntax:
c.setMaxAge(0);
-----------------------------------------------------------------------
Ex:
ii
ath
DBConnection.java
package test;
ip
import java.sql.*;
public class DBConnection {
private static Connection con=null;//reference variable
Ma
private DBConnection() {}
static
{
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
sh
con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
ate
}catch(Exception e) {e.printStackTrace();}
}
public static Connection getCon()
{
return con;
nk
}
}
Ve
UserBean.java
package test;
import java.io.*;
@SuppressWarnings("serial")
public class UserBean implements Serializable{
private String uName,pWord,fName,lName,addr,mId;
private long phNo;
public UserBean() {}
public String getuName() {
return uName;
}
public void setuName(String uName) {
this.uName = uName;
}
public String getpWord() {
return pWord;
}
public void setpWord(String pWord) {
this.pWord = pWord;
}
ii
public String getfName() {
return fName;
ath
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
ip
return lName;
} Ma
public void setlName(String lName) {
this.lName = lName;
}
public String getAddr() {
return addr;
}
sh
public void setAddr(String addr) {
this.addr = addr;
}
ate
this.mId = mId;
}
public long getPhNo() {
return phNo;
Ve
}
public void setPhNo(long phNo) {
this.phNo = phNo;
}
login.html
package test;
import java.io.*;
@SuppressWarnings("serial")
public class UserBean implements Serializable{
private String uName,pWord,fName,lName,addr,mId;
private long phNo;
public UserBean() {}
public String getuName() {
return uName;
}
public void setuName(String uName) {
ii
this.uName = uName;
}
ath
public String getpWord() {
return pWord;
}
public void setpWord(String pWord) {
this.pWord = pWord;
ip
}
public String getfName() { Ma
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
sh
return lName;
}
public void setlName(String lName) {
ate
this.lName = lName;
}
public String getAddr() {
return addr;
nk
}
public void setAddr(String addr) {
this.addr = addr;
}
Ve
register.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
ii
<title>Insert title here</title>
ath
</head>
<body>
<form action="reg" method="post">
UserName:<input type="text" name="uname"><br>
PassWord:<input type="text" name="pword"><br>
ip
FirstName:<input type="text" name="fname"><br>
LastName:<input type="text" name="lname"><br>
Ma
Address:<input type="text" name="addr"><br>
MailId:<input type="text" name="mid"><br>
PhoneNo:<input type="text" name="phno"><br>
<input type="submit" value="Register">
</form>
</body>
sh
</html>
RegisterDAO.java
ate
package test;
import java.sql.*;
public class RegisterDAO {
public int k=0;
nk
RegisterServlet.java
package test;
ii
import java.io.*;
ath
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
ip
@SuppressWarnings("serial") Ma
@WebServlet("/reg")
ub.setuName(req.getParameter("uname"));
nk
ub.setpWord(req.getParameter("pword"));
ub.setfName(req.getParameter("fname"));
Ve
ub.setlName(req.getParameter("lname"));
ub.setAddr(req.getParameter("addr"));
ub.setmId(req.getParameter("mid"));
ub.setPhNo(Long.parseLong(req.getParameter("phno")));
PrintWriter pw = res.getWriter();
res.setContentType("text/html");
if(k>0) {
RequestDispatcher rd=
req.getRequestDispatcher("login.html");
rd.include(req, res);
ii
}
ath
}
ip
Web.xml
link.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="view">ViewProducts</a>
ii
<a href="logout">Logout</a>
ath
</body>
</html>
LoginDAO.java
ip
package test;
import java.sql.*;
import javax.servlet.http.*;
Ma
public class LoginDAO {
sh
public UserBean ub=null;
try {
PreparedStatement ps = con.prepareStatement
ps.setString(1,req.getParameter("uname"));
ps.setString(2,req.getParameter("pword"));
ResultSet rs = ps.executeQuery();
if(rs.next()) {
ub.setpWord(rs.getString(2));
ub.setfName(rs.getString(3));
ub.setlName(rs.getString(4));
ub.setAddr(rs.getString(5));
ub.setmId(rs.getString(6));
ii
ub.setPhNo(rs.getLong(7));
ath
}
}catch(Exception e) {e.printStackTrace();}
ip
return ub;
}
}
Ma
LoginServlet.java
sh
package test;
import java.io.*;
ate
import javax.servlet.*;
import javax.servlet.http.*;
nk
import javax.servlet.annotation.*;
@SuppressWarnings("serial")
Ve
@WebServlet("/log")
res.setContentType("text/html");
if(ub==null) {
RequestDispatcher rd=
req.getRequestDispatcher("login.html");
ii
rd.include(req, res);
ath
}else {
ip
//Creating Cookie
Ma
res.addCookie(ck);//Adding Cookie to response
RequestDispatcher rd =
sh
req.getRequestDispatcher("link.html");
rd.include(req, res);
ate
}
nk
ProductBean.java
Ve
package test;
import java.io.*;
@SuppressWarnings("serial")
public class ProductBean implements Serializable{
private String code,name;
private float price;
private int qty;
public ProductBean() {}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPrice() {
ii
return price;
}
ath
public void setPrice(float price) {
this.price = price;
}
public int getQty() {
return qty;
ip
}
public void setQty(int qty) { Ma
this.qty = qty;
}
}
sh
RetrieveDAO.java
package test;
ate
import java.sql.*;
import java.util.*;
nk
try {
ResultSet rs = ps.executeQuery();
while(rs.next())
ii
pb.setCode(rs.getString(1));
ath
pb.setName(rs.getString(2));
pb.setPrice(rs.getFloat(3));
ip
pb.setQty(rs.getInt(4));
Ma
al.add(pb);//Adding bean to ArrayList
}//end of loop
}catch(Exception e) {e.printStackTrace();}
sh
return al;
}
ate
ViewProductsServlet.java
nk
package test;
import java.io.*;
Ve
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
@SuppressWarnings("serial")
@WebServlet("/view")
throws ServletException,IOException{
PrintWriter pw = res.getWriter();
res.setContentType("text/html");
ii
Cookie c[] = req.getCookies();//Getting the Cookies
ath
if(c==null) {
pw.println("Session Expired...<br>");
ip
RequestDispatcher rd=
Ma
req.getRequestDispatcher("login.html");
rd.include(req, res);
}else {
sh
String fName = c[0].getValue();
pw.println("page of "+fName+"<br>");
ate
RequestDispatcher rd=
req.getRequestDispatcher("link.html");
nk
rd.include(req, res);
if(al.size()==0) {
}else {
Iterator<ProductBean> it = al.iterator();
while(it.hasNext())
{
ProductBean pb = (ProductBean)it.next();
pw.println("<br>"+pb.getCode()+"  "+
pb.getName()+"  "+pb.getPrice()+
"  "+pb.getQty()+"<br>");
}//end of loop
ii
}//end of else
ath
}
ip
}
LogoutServlet.java
package test;
Ma
import java.io.*;
sh
import javax.servlet.*;
import javax.servlet.http.*;
ate
import javax.servlet.annotation.*;
@SuppressWarnings("serial")
nk
@WebServlet("/logout")
PrintWriter pw = res.getWriter();
res.setContentType("text/html");
pw.println("Session Expired....<br>");
}else {
c[0].setMaxAge(0);//Cookie destroyed
ii
RequestDispatcher rd=
ath
req.getRequestDispatcher("login.html");
rd.include(req, res);
ip
}
Layout:
Ma
sh
ate
nk
Ve
=================================================================
Assignment:
DB Tables:
UserReg45(uname,pword,fname,lname,addr,mid,phno)
ii
AdminReg45(uname,pword,fname,lname,addr,mid,phno)
ath
BookDetails45(bcode,bname,bauthor,bprice,bqty)
ip
Ma
sh
ate
nk
Ve
Dt : 2/6/2022
Diagram:
ii
ip ath
Ma
=========================================================================
=>Cookies are stored in WebBrowser to track the user,which means Cookies are
sh
browser dependent or Client dependent.
ate
=====================================================================
*imp
Ve
(b)HttpSession:
ii
ath
public abstract void putValue(java.lang.String, java.lang.Object);
ip
public abstract java.lang.String[] getValueNames();
Ma
public abstract void removeValue(java.lang.String);
Note:
ii
ip ath
Ma
sh
ate
nk
Ve
Dt : 3/6/2022
Layout:
ii
ip ath
Ma
sh
login.html
<!DOCTYPE html>
ate
<html>
<head>
<meta charset="ISO-8859-1">
nk
<body>
<form action="log" method="post">
UserName:<input type="text"
name="uname"><br>
PassWord:<input type="password"
name="pword"><br>
<input type="submit" value="Login">
<a href="register.html">NewUser?</a>
</form>
</body>
</html>
link.html
<!DOCTYPE html>
<html>
ii
<head>
ath
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
ip
<body>
<a href="view">ViewProfile</a>
Ma
<a href="">EditProfile</a>
<a href="logout">Logout</a>
</body>
sh
</html>
DBConnection.java
ate
package test;
import java.sql.*;
nk
con=null;//reference variable
private DBConnection() {}
static
{
try {
Class.forName("oracle.jdbc.driver.Orac
leDriver");
con =
DriverManager.getConnection
ii
("jdbc:oracle:thin:@localhost:1521:xe"
ath
,"system","manager");
}catch(Exception e)
{e.printStackTrace();}
ip
} Ma
public static Connection getCon()
{
return con;
}
sh
}
ate
LoginDAO.java
package test;
nk
import java.sql.*;
import javax.servlet.http.*;
Ve
try {
ps.setString(1,req.getParameter("uname"));
ps.setString(2,req.getParameter("pword"));
ResultSet rs = ps.executeQuery();
if(rs.next()) {
ii
ub = new UserBean();//Bean Object
ath
ub.setuName(rs.getString(1));
ub.setpWord(rs.getString(2));
ub.setfName(rs.getString(3));
ip
ub.setlName(rs.getString(4));
Ma
ub.setAddr(rs.getString(5));
ub.setmId(rs.getString(6));
ub.setPhNo(rs.getLong(7));
sh
}
}catch(Exception e) {e.printStackTrace();}
ate
return ub;
}
nk
UserBean.java
Ve
package test;
import java.io.*;
@SuppressWarnings("serial")
public class UserBean implements
Serializable{
private String
uName,pWord,fName,lName,addr,mId;
private long phNo;
public UserBean() {}
public String getuName() {
return uName;
}
ii
public void setuName(String uName) {
ath
this.uName = uName;
}
public String getpWord() {
ip
return pWord; Ma
}
public void setpWord(String pWord) {
this.pWord = pWord;
}
sh
public String getfName() {
ate
return fName;
}
public void setfName(String fName) {
nk
this.fName = fName;
}
Ve
ii
return mId;
ath
}
public void setmId(String mId) {
this.mId = mId;
ip
} Ma
public long getPhNo() {
return phNo;
}
public void setPhNo(long phNo) {
sh
this.phNo = phNo;
ate
}
nk
LoginServlet.java
Ve
package test;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
@SuppressWarnings("serial")
@WebServlet("/log")
PrintWriter pw = res.getWriter();
ii
res.setContentType("text/html");
ath
if(ub==null) {
RequestDispatcher rd=
ip
req.getRequestDispatcher("login.html");
Ma
rd.include(req, res);
}else {
RequestDispatcher rd =
req.getRequestDispatcher("link.html");
nk
rd.include(req, res);
}
Ve
web.xml
package test;
import java.io.*;
ii
ath
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
ip
@SuppressWarnings("serial")
@WebServlet("/view")
Ma
public class ViewProfileServlet extends HttpServlet{
PrintWriter pw = res.getWriter();
ate
res.setContentType("text/html");
HttpSession hs = req.getSession(false);
nk
if(hs==null) {
Ve
pw.println("Session Expired...<br>");
RequestDispatcher rd =
req.getRequestDispatcher("login.html");
rd.include(req, res);
}else {
UserBean ub = (UserBean)hs.getAttribute("ubean");
pw.println("Page of "+ub.getfName()+"<br>");
RequestDispatcher rd=
req.getRequestDispatcher("link.html");
rd.include(req, res);
pw.println("<br>"+ub.getfName()+"  "+
ub.getlName()+"  "+ub.getAddr()+"  "+
ii
ub.getmId()+"  "+ub.getPhNo());
ath
}
ip
LogoutServlet.java Ma
package test;
import java.io.*;
import javax.servlet.*;
sh
import javax.servlet.http.*;
import javax.servlet.annotation.*;
ate
@SuppressWarnings("serial")
@WebServlet("/logout")
nk
throws ServletException,IOException{
PrintWriter pw = res.getWriter();
res.setContentType("text/html");
HttpSession hs = req.getSession(false);
if(hs==null) {
pw.println("Session Expired...<br>");
}else {
hs.invalidate();//Session destroyed
RequestDispatcher rd=
ii
req.getRequestDispatcher("login.html");
ath
rd.include(req, res);
ip
=========================================================================
Ma
Assignment:
=======================================================================
sh
ate
nk
Ve
Dt:4/6/2022
faq:
(i)getSession()
(ii)getSession(false)
(iii)getSession(true)
ii
ath
(i)getSession():
ip
Session Object is not available.
Ma
=>If available then getSession() method will access the existing session
object.
sh
(ii)getSession(false):
(iii)getSession(true):
=>If available then getSession(true) method will access the existing session
object.
===========================================================================
(c)URL re-write:
=>The process of adding parameter-values to url-pattern is known as URL re-write.
=>using URL re-write process we pass information from one Servlet program to
syntax:
url-pattern?para=value¶=value&...
ii
ath
Note:
ip
=>"&" symbol is the separator b/w parameters.
Ex Application:
Ma
DBConnection.java
sh
package test;
import java.sql.*;
public class DBConnection {
ate
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection
Ve
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
}catch(Exception e) {e.printStackTrace();}
}
public static Connection getCon()
{
return con;
}
}
RetrieveDAO.java
package test;
import java.sql.*;
import javax.servlet.http.*;
ii
ProductBean retrieve(HttpServletRequest req)
ath
{
try {
ip
Connection con = DBConnection.getCon();
Ma
//Accessing the Connection
PreparedStatement ps = con.prepareStatement
ResultSet rs = ps.executeQuery();
ate
while(rs.next())
{
nk
pb = new ProductBean();
pb.setCode(rs.getString(1));
Ve
pb.setName(rs.getString(2));
pb.setPrice(rs.getFloat(3));
pb.setQty(rs.getInt(4));
}//end of loop
}catch(Exception e) {e.printStackTrace();}
return pb;
ProductBean.java
package test;
import java.io.*;
@SuppressWarnings("serial")
public class ProductBean implements Serializable{
ii
private String code,name;
ath
private float price;
private int qty;
public ProductBean() {}
public String getCode() {
return code;
ip
}
public void setCode(String code) {
Ma
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
sh
this.name = name;
}
public float getPrice() {
ate
return price;
}
public void setPrice(float price) {
this.price = price;
nk
}
public int getQty() {
return qty;
}
Ve
input.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="first" method="post">
Enter the ProdCode:<input type="text" name="pcode"><br>
<input type="submit" value="RetrieveProduct">
</form>
</body>
ii
</html>
ath
FirstServlet.java
package test;
import java.io.*;
ip
import javax.servlet.*; Ma
import javax.servlet.http.*;
import javax.servlet.annotation.*;
@SuppressWarnings("serial")
sh
@WebServlet("/first")
ate
throws ServletException,IOException{
nk
PrintWriter pw = res.getWriter();
Ve
res.setContentType("text/html");
if(pb==null) {
pw.println("Invalid ProductCode...<br>");
RequestDispatcher rd=
req.getRequestDispatcher("input.html");
rd.include(req, res);
}else {
pw.println("<a href='second?code="+pb.getCode()
+"&name="+pb.getName()
+"&price="+pb.getPrice()
+"&qty="+pb.getQty()+"'>ViewProductDetails</a>");
ii
}
ath
}
ip
SecondServlet.java
package test;
import java.io.*;
Ma
import javax.servlet.*;
sh
import javax.servlet.http.*;
import javax.servlet.annotation.*;
ate
@SuppressWarnings("serial")
@WebServlet("/second")
nk
throws ServletException,IOException{
PrintWriter pw = res.getWriter();
res.setContentType("text/html");
pw.println("====ProductDetails====");
pw.println("<br>PCode:"+req.getParameter("code"));
pw.println("<br>PName:"+req.getParameter("name"));
pw.println("<br>PPrice:"+req.getParameter("price"));
pw.println("<br>PQty:"+req.getParameter("qty"));
web.xml
ii
<?xml version="1.0" encoding="UTF-8"?>
ath
<web-app>
<welcome-file-list>
<welcome-file>input.html</welcome-file>
</welcome-file-list>
</web-app>
ip
Diagram: Ma
sh
ate
nk
Ve
http://localhost:8082/Servlet_App8_URL_Re_Write/second?
code=A111
&name=Mouse
&price=1200.0
&qty=12
https://www.google.com/search?
ii
q=gmail
ath
&oq=
&aqs=chrome.0.35i39i362l8.1558847477j0j7
ip
&sourceid=chrome
&ie=UTF-8
Ma
=====================================================================
sh
Assignment:
Construct Servlet Application to send Book details from one Servlet program to
ate
=======================================================================
nk
Ve
Dt : 6/6/2022
=>The data which is available in hidden form filds are not visible to the
end user.
ii
=>In Session tracking process we can also take the support hidden form fields
ath
to transfer the information from one Servlet program to another Servlet program.
ip
syntax:
<form action="url-pattern"...>
Ma
<input type="hidden" value="alex" name="n">
...
sh
</form>
ate
Ex_program:
DBConnection.java
nk
package test;
import java.sql.*;
public class DBConnection {
Ve
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
}catch(Exception e) {e.printStackTrace();}
}
public static Connection getCon()
{
return con;
}
}
RetrieveDAO.java
package test;
ii
import java.sql.*;
ath
import javax.servlet.http.*;
ip
ProductBean retrieve(HttpServletRequest req)
Ma
{
try {
PreparedStatement ps = con.prepareStatement
ps.setString(1,req.getParameter("pcode"));
ResultSet rs = ps.executeQuery();
Ve
while(rs.next())
pb = new ProductBean();
pb.setCode(rs.getString(1));
pb.setName(rs.getString(2));
pb.setPrice(rs.getFloat(3));
pb.setQty(rs.getInt(4));
}//end of loop
}catch(Exception e) {e.printStackTrace();}
return pb;
ii
ProductBean.java
ath
package test;
import java.io.*;
@SuppressWarnings("serial")
public class ProductBean implements Serializable{
ip
private String code,name;
private float price; Ma
private int qty;
public ProductBean() {}
public String getCode() {
return code;
}
public void setCode(String code) {
sh
this.code = code;
}
public String getName() {
ate
return name;
}
public void setName(String name) {
this.name = name;
}
nk
input.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
ii
<form action="first" method="post">
ath
Enter the ProdCode:<input type="text" name="pcode"><br>
<input type="submit" value="RetrieveProduct">
</form>
</body>
</html>
ip
FirstServlet.java Ma
package test;
import java.io.*;
import javax.servlet.*;
sh
import javax.servlet.http.*;
ate
import javax.servlet.annotation.*;
@SuppressWarnings("serial")
nk
@WebServlet("/first")
throws ServletException,IOException{
PrintWriter pw = res.getWriter();
res.setContentType("text/html");
if(pb==null) {
pw.println("Invalid ProductCode...<br>");
RequestDispatcher rd=
req.getRequestDispatcher("input.html");
rd.include(req, res);
}else {
ii
pw.println
ath
("<input type='hidden' value='"+pb.getCode()+"' name='code'>");
pw.println
ip
("<input type='hidden' value='"+pb.getName()+"' name='name'>");
pw.println
Ma
("<input type='hidden' value='"+pb.getPrice()+"' name='price'>");
pw.println
sh
("<input type='hidden' value='"+pb.getQty()+"' name='qty'>");
pw.println
ate
pw.println("</form>");
nk
}
Ve
SecondServlet.java
package test;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
@SuppressWarnings("serial")
@WebServlet("/second")
ii
throws ServletException,IOException{
ath
PrintWriter pw = res.getWriter();
res.setContentType("text/html");
ip
pw.println("====ProductDetails====");
Ma
pw.println("<br>PCode:"+req.getParameter("code"));
pw.println("<br>PName:"+req.getParameter("name"));
pw.println("<br>PPrice:"+req.getParameter("price"));
sh
pw.println("<br>PQty:"+req.getParameter("qty"));
}
ate
web.xml
nk
<welcome-file>input.html</welcome-file>
</welcome-file-list>
</web-app>
=======================================================================
Assignment:
Construct Servlet Application to send Book details from one Servlet program to
ii
ip ath
Ma
sh
ate
nk
Ve
Dt : 7/6/2022
*imp
ServletContext:
ii
=>we use getServletContext() method to access the reference of ServletContext
ath
object.
ip
GenericServlet,HttpSession and ServletConfig.
syntax:
Ma
ServletContext sct = req.getServletContext();
sh
ServletContext object.
nk
syntax:
<web-app>
Ve
<context-param>
</context-param>
.
.
</web-app>
ii
Note:
ath
=>Total WebApplication will have only one ServletContext object and the
ip
WebApplication.
Ma
-------------------------------------------------------------------
*imp
ServletConfig:
sh
=>ServletConfig is an interface from javax.servlet package and which is
object.
nk
object.
syntax:
ServletConfig sc = this.getServletConfig();
=>we use <init-param> tag part of <servlet> to initialize parameters to
ServletConfig object.
syntax:
<web-app>
ii
<servlet>
ath
.
<init-param>
ip
<param-name> name </param-name>
Ma
<param-value> value </param-value>
</init-param>
</servlet>
sh
<servlet-mapping>
.
ate
</servlet-mapping>
.
nk
</web-app>
Ve
Ex Application:
input.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="dis" method="post">
Name:<input type="text" name="name"><br>
<input type="submit" value="Display">
</form>
</body>
</html>
web.xml
ii
<context-param>
ath
<param-name>a</param-name>
<param-value>2000</param-value>
</context-param>
<servlet>
ip
<servlet-name>DisplayServlet</servlet-name>
<servlet-class>test.DisplayServlet</servlet-class>
Ma
<init-param>
<param-name>b</param-name>
<param-value>3000</param-value>
</init-param>
</servlet>
<servlet-mapping>
sh
<servlet-name>DisplayServlet</servlet-name>
<url-pattern>/dis</url-pattern>
</servlet-mapping>
ate
<welcome-file-list>
<welcome-file>input.html</welcome-file>
</welcome-file-list>
nk
</web-app>
DisplayServlet.java
Ve
package test;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
@SuppressWarnings("serial")
public class DisplayServlet extends HttpServlet{
throws ServletException,IOException{
PrintWriter pw = res.getWriter();
res.setContentType("text/html");
pw.println("User : "+req.getParameter("name"));
ii
pw.println("<br>====ServletContext=====");
ath
ServletContext sct = req.getServletContext();
ip
pw.println("<br>ServerInfo:"+sct.getServerInfo());
Ma
pw.println("<br>ContextValue:"+sct.getInitParameter("a"));
pw.println("<br>====ServletConfig====");
ServletConfig sc = this.getServletConfig();
sh
//Accessing Config Object
pw.println("<br>ServletName:"+sc.getServletName());
ate
pw.println("<br>ConfigValue:"+sc.getInitParameter("b"));
}
nk
ip
Ma
sh
ate
nk
Ve
Dt : 8/6/2022
1.ServletContext
2.ServletConfig
3.ServletRequest/HttpServletRequest
4.ServletResponse/HttpServletResponse
ii
5.PrintWriter
ath
6.HttpSession
7.Cookie
ip
8.Java Beans
(i)ServletContext
(ii)ServletConfig
nk
(i)ServletContext:
Ve
(ii)ServletConfig:
=>ServletConfig is instantiated automatically when Servlet program is loaded
=========================================================================
faq:
ii
(i)<contex-param>
ath
(ii)<init-param>
ip
(i)<contex-param>:
Ma
<context-param> tag is used to initialize parameters to ServletContext object.
(ii)<init-param>:
sh
<init-param> tag is the Sub-tag of <servlet> tag and which is used to
============================================================================
faq:
nk
(i)getParameter()
Ve
(ii)getInitParameter()
(i)getParameter():
============================================================================
*imp
ii
=>Filter is a Pre-Processing component before Servlet program.
ath
=>Filter and Servlet programs are executed with same url-pattern.
=>In the process of execution Filter programs will have highest priority in
ip
execution than Servlet programs
Diagram:
Ma
sh
ate
nk
Ve
Advantage of Filters:
=======================================================================
Note:
ii
1.Filter
ath
2.FilterChain
3.FilterConfig
ip
1.Filter:
Ma
=>Filter is an interface from javax.servlet package and which is implemented
to filter program.
sh
=>The following are the Life-Cycle methods from 'Filter':
ate
throws javax.servlet.ServletException;
nk
javax.servlet.ServletResponse, javax.servlet.FilterChain)
Ve
2.FilterChain:
=>FilterChain is an interface from javax.servlet package and which is
=>This FilterChain will have the following doFilter() method to link the
ii
javax.servlet.ServletResponse) throws java.io.IOException,
ath
javax.servlet.ServletException;
ip
3.FilterConfig:
Ma
=>FilterConfig is an interface from javax.servlet package and which is
getInitParameterNames();
-------------------------------------------------------------------------
Dt : 9/6/2022
Note:
=>we use the following tags part of web.xml to execute filter program:
<web-app>
ii
<filter>
ath
<filter-name> name </filter-name>
ip
<init-param>
<param-name>name</param-name>
<param-value>value</param-value>
Ma
</init-param>
sh
</filter>
<filter-mapping>
ate
<filter-name>name</filter-name>
<url-pattern>/url-pattern</url-pattern>
nk
</filter-mapping>
</web-app>
Ve
=========================================================================
Ex_Application-1:
login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="log" method="post">
UserName:<input type="text" name="uname"><br>
PassWord:<input type="password" name="pword"><br>
<input type="submit" value="Login">
<a href="register.html">NewUser?</a>
</form>
ii
</body>
</html>
ath
DBConnection.java
package test;
import java.sql.*;
ip
public class DBConnection {
private static Connection con=null;//reference variable
Ma
private DBConnection() {}
static
{
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection
sh
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
}catch(Exception e) {e.printStackTrace();}
ate
}
public static Connection getCon()
{
return con;
nk
}
}
Ve
LoginDAO.java
package test;
import java.sql.*;
import javax.servlet.*;
try {
PreparedStatement ps = con.prepareStatement
ii
ps.setString(1,req.getParameter("uname"));
ath
ps.setString(2,req.getParameter("pword"));
ResultSet rs = ps.executeQuery();
ip
if(rs.next()) {
Ma
fName = rs.getString(3);
}catch(Exception e) {e.printStackTrace();}
}
return fName;
sh
}
}
ate
LoginFilter.java
package test;
nk
import java.io.*;
import javax.servlet.*;
Ve
import javax.servlet.annotation.*;
@WebFilter("/log")
res.setContentType("text/html");
if(fName==null) {
RequestDispatcher rd =
ii
req.getRequestDispatcher("login.html");
ath
rd.include(req, res);
}else {
ip
req.setAttribute("fname", fName);
}
Ma
chain.doFilter(req, res);//linking Servlet_program
}
sh
}
WelcomeServlet.java
ate
package test;
import java.io.*;
nk
import javax.servlet.*;
import javax.servlet.http.*;
Ve
import javax.servlet.annotation.*;
@SuppressWarnings("serial")
@WebServlet("/log")
PrintWriter pw = res.getWriter();
res.setContentType("text/html");
pw.println("Login Successfull...<br>");
ii
}
ath
}
web.xml
ip
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
Ma
</web-app>
Diagram:
sh
ate
nk
Ve
========================================================================
Dt : 11/6/2022
Filter_program-2:
Application to demonstrate FilterConfig.
input.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="dis" method="post">
ii
UserName:<input type="text" name="uname"><br>
ath
<input type="submit" value="Display">
</form>
</body>
</html>
ip
web.xml
</filter>
<filter-mapping>
<filter-name>DisplayFilter</filter-name>
<url-pattern>/dis</url-pattern>
</filter-mapping>
nk
<welcome-file-list>
<welcome-file>input.html</welcome-file>
</welcome-file-list>
Ve
</web-app>
DisplayFilter.java
package test;
import java.io.*;
import javax.servlet.*;
public class DisplayFilter implements Filter{
this.fc=fc;
ii
FilterChain chain)throws ServletException,IOException{
ath
PrintWriter pw = res.getWriter();
res.setContentType("text/html");
ip
pw.println("UserName:"+req.getParameter("uname"));
Ma
pw.println("<br>====FilterConfig====");
pw.println("<br>FilterName:"+fc.getFilterName());
pw.println("<br>FilterValue:"+fc.getInitParameter("a"));
sh
}
}
ate
Diagram:
nk
Ve
ii
ip ath
Ma
========================================================================
sh
faq:
ate
(i)ServletConfig
(ii)FilterConfig
nk
Ve
(i)ServletConfig:
(ii)FilterConfig:
=>FilterConfig is instantiated automatically when the Filter program loaded
for execution.
================================================================
Note:
ii
================================================================
ip ath
Ma
sh
ate
nk
Ve
Dt : 14/6/2022
*imp
ii
Note:
ath
=>when event(action) is performed on Servlet object deligated to Listener and
the Listener will execute related method to handle the event,is known as
ip
Event-Delegation-Model.
Diagram:
Ma
sh
ate
nk
Ve
------------------------------------------------------------------
1.ServletContext
2.ServletRequest
3.HttpSession
1.ServletContext:
Event_Class : ServletContextEvent
Event_Listener : ServletContextListener
ii
methods :
ath
public void contextInitialized(javax.servlet.ServletContextEvent)
ip
2.ServletRequest:
Ma
Event_Class : ServletRequestEvent
sh
Event_Listener : ServletRequestListener
methods :
ate
3.HttpSession:
Ve
Event_Class : HttpSessionEvent
Event_Listener : HttpSessionListener
methods :
============================================================================
ContextListener.java
ii
package test;
ath
import javax.servlet.*;
import javax.servlet.annotation.*;
ip
@WebListener
Ma
public class ContextListener implements ServletContextListener
}
ate
}
Ve
RequestListener.java
package test;
import javax.servlet.*;
import javax.servlet.annotation.*;
@WebListener
public class RequestListener implements ServletRequestListener{
ii
}
ath
}
SessionListener.java
ip
package test;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
Ma
@WebListener
sh
public class SessionListener implements HttpSessionListener,
HttpSessionAttributeListener{
ate
System.out.println("Session Created....");
nk
System.out.println("Session Destroyed...");
}
public void attributeRemoved(HttpSessionBindingEvent hsbe) {
========================================================================
faq:
ii
Types of Listeners in Servlet Programming"
ath
=>Listeners in Servlet programming are categorized into three types:
ip
2.Request Level Listener
======================================================
structure of web.xml from Servlet Programming:
<web-app>
<context-param></context-param>
<listener>
Listener_Class_name
ii
</listener>
ath
<servlet>
<servlet-name></servlet-name>
ip
<servlet-class></servlet-class>
<init-param></init-param>
</servlet>
Ma
<servlet-mapping>
sh
<servlet-name></servlet-name>
<url-pattern></url-pattern>
ate
</servlet-mapping>
<filter>
nk
<filter-name></filter-name>
<filter-class></filter-class>
Ve
<init-param></init-param>
</filter>
<filter-mapping>
<filter-name></filter-name>
<url-pattern></url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file></welcome-file>
</welcome-file-list>
</web-app>
ii
ip ath
Ma
sh
*imp
ate
define Annotation?
nk
annotation.
@ Override
@ SuppressWarnings("unchecked")
@ SuppressWarnings("rawtypes")
ii
ath
=>The following are some important annotations used in Servlet
programming:
ip
(a)@ WebServlet
(b)@ WebFilter
(c)@ WebInitParam
Ma
(d)@ WebListener
sh
(a)@ WebServlet:
ate
(b)@ WebFilter:
Ve
(c)@ WebInitParam:
(d)@ WebListener:
--------------------------------------
ii
Note:
ath
=>When we use annotations in Servlet programming,the Servlet programs
ip
=>All the annotations related to ServletProgramming are available
Dt : 15/6/2022
sh
faq:
Servlet Collaboration.
nk
(i)Using 'RequestDispatcher'
=>forward()
=>include()
=>In this process another Servlet program may be in same WebApp or diff WebAppl.
ii
Method Signature:
ath
public abstract void sendRedirect(java.lang.String) throws java.io.IOException;
ip
Ex:
WebApp-1 : TestApp1
Ma
input.html
sh
<!DOCTYPE html>
<html>
<head>
ate
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="first" method="post">
nk
</form>
</body>
</html>
FirstServlet.java
package test;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
@SuppressWarnings("serial")
@WebServlet("/first")
ii
throws ServletException,IOException{
ath
String uName = req.getParameter("uname");
ip
res.sendRedirect("http://localhost:8082/TestApp2/second?uname="+
}
uName+"&mid="+mId);
Ma
}
sh
web.xml
<web-app>
<welcome-file-list>
<welcome-file>input.html</welcome-file>
</welcome-file-list>
</web-app>
nk
WebApp-2 : TestApp2
Ve
SecondServlet.java
package test;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
@SuppressWarnings("serial")
@WebServlet("/second")
throws ServletException,IOException{
PrintWriter pw = res.getWriter();
ii
res.setContentType("text/html");
ath
pw.println("====SecondServlet====");
pw.println("<br>Name:"+req.getParameter("uname"));
ip
pw.println("<br>MailId:"+req.getParameter("mid"));
}
Ma
}
sh
http://localhost:8082/TestApp2/second?uname=Alex&[email protected]
-----------------------------------------------------------------------
ate
faq:
(i)forward() method
(ii)sendRedirect() method
Ve
servlet program.
=>when we use sendRedirect() method then new requset is generated from the
faq:
1.Loading process
ii
2.Instantiation proccess
ath
3.Initialization process
ip
5.Destroying process
1.Loading process:
Ma
=>The process of identifying the servlet program based on url-pattern and
sh
loading onto WebContatiner is known as Loading prrocess.
Note:
ate
(i)Annotation
nk
(ii)web.xml
Ve
2.Instantiation proccess:
Genericservlet
(a)init()
(b)service()
(c)destroy()
HttpServlet
(a)init()
(b)doPost()/doGet()/service()
ii
(c)destroy()
ath
Filter
(a)init()
ip
(b)doFilter()
faq:
(c)destroy()
Ma
define Life-Cycle methods?
sh
=>The methods which are executed automatically in same order are known as
Life-Cycle methods.
ate
3.Initialization process:
nk
=>The process of making the programming components ready for execution is known as
Initialization process.
Ve
Note:
=>Through Initialization process we can make Bean objects and DAO objects ready
for execution.
=>The process of taking the request and providing the response is known as
Handling process.
Note:
ii
=>In Multi-User Applications,
ath
=>init() method is executed only once,but doPost()/doGet()/service() methods
ip
5.Destroying process:
Ma
=>The process of closing or destroying the resources after execution is known
as Destroying process.
sh
=>we use destroy() method to perform destroying process.
=============================================================================
ate
1.Connection Object
nk
2.Statement Object
3.PreparedStatement Object
Ve
4.CallableStatement Object
7.DatabaseMetaData object
8.ParameterMetaData object
9.ResultSetMetaData object
10.RowSet Object
(a)JdbcRowSet
(b)CachedRowSet
=>WebRowSet
(i)FilteredRowSet
ii
(ii)JoinRowset
ath
*
ip
=>Vector<E> Object
Ma
Summary of Objects from Servlet Programming:
sh
1.ServletContext object
2.ServletConfig object
ate
3.ServletRequest/HttpServletRequest object
4.ServletResponse/HttpServletResponse object
nk
5.PrintWriter object
6.Cookie object
Ve
7.HttpSession object
10.JCF object
==============================================================================
==
*imp
JSP Programming:(Unit-3)
=>JSP Stands for 'Java Server Page' and which is response from
WebApplication.
ii
=>JSP is tag based programming language and which is more easy when
ath
compared to Servlet programming.
ip
=>JSP programs are combination of both HTML code and Java Code.
1.Scripting tags
=>Scriptlet tag
sh
=>Expression tag
ate
=>Declarative tag
2.Directive tags
nk
=>page
=>include
Ve
=>taglib
3.Action tags
=>jsp:include
=>jsp:forward
=>jsp:param
=>jsp:useBean
=>jsp:setProperty
=>jsp:getProperty
Dt : 16/6/2022
1.Scripting tags:
ii
=>Scripting tags are used to write JavaCode part of JSP programs.
ath
=>Scripting tags are categorized into the following:
(a)Scriptlet tag
ip
(b)Expression tag
(c)Declarative tag
Ma
(a)Scriptlet tag:
sh
=>Scriptlet tag is used to write normal JavaCode part of JSP programs
ate
syntax:
(b)Expression tag:
syntax:
<%= expression %>
(c)Declarative tag:
ii
syntax:
ath
<%! variables;methods %>
ip
=======================================================================
2.Directive tags:
Ma
=>The tags which are used to specify the directions in translation
(a)page
(b)include
nk
(c)taglib
Ve
(a)page:
exp:
ii
List of attributes:
ath
1.import
ip
2.contentType
3.extends
4.info
Ma
5.buffer
sh
6.language
7.isELIgnored
ate
8.isThreadSafe
9.autoFlush
nk
10.session
11.pageEncoding
Ve
12.errorPage
13.isErrorPage
-----------------------------------------------------
(b)include:
syntax:
Exp:
ii
<%@ include file="input.html" %>
ath
-----------------------------------------------------
ip
(c)taglib:
Ma
=>'taglib' directive tag specifies to add specified url to current
JSP page and which is used part of EL(Expression Lang) and JSTL
syntax:
ate
===============================================
nk
Exp program1:
Note:
input.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="Display.jsp" method="post">
Enter the Value:<input type="text" name="v"><br>
<input type="submit" value="Factorial">
</form>
</body>
</html>
ii
Display.jsp
ath
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
errorPage="Error.jsp"%>
ip
<!DOCTYPE html>
<html> Ma
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%!
sh
int fact;
int factorial(int n)
{
ate
fact=1;
for(int i=n;i>=1;i--)
{
fact=fact*i;
nk
}
return fact;
}
%>
Ve
<%
int val = Integer.parseInt(request.getParameter("v"));
int result = factorial(val);
out.println("Factorial : "+result+"<br>");
%>
<%@include file="input.html"%>
</body>
</html>
Errorr.jsp
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
isErrorPage="true"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
ii
<%
out.println("Enter only Integer value...<br>");
ath
%>
<%= exception %>
<br>
<%@include file="input.html"%>
</body>
ip
</html>
web.xml
http://localhost:8082/JSPApp1
nk
Diagram:
Ve
ii
ath
=======================================================================
ip
=>The following are the implicit objects of JSP:
Ma
application - javax.servlet.ServletContext
config - javax.servlet.ServletConfig
sh
request - javax.servlet.http.HttpServletRequest
ate
response - javax.servlet.http.HttpServletResponse
out - javax.servlet.jsp.JspWriter
session - javax.servlet.http.HttpSession
nk
exception - java.lang.Throwable
Ve
page - java.lang.Object
pageContext - javax.servlet.jsp.PageContext
=============================================================
3.Action tags:
=>Action Tags are used to include some basic actions like inserting
some other page resources ,forwarding the request to another page,
Note:
ii
------------------------------------------------------
ath
=>The following are some Important action tags available in JSP:
ip
1.<jsp:include>
2.<jsp:forward>
3.<jsp:param>
Ma
4.<jsp:useBean>
sh
5.<jsp:setProperty>
6.<jsp:getProperty>
ate
nk
1.<jsp:include> :
Ve
=>If the resource is static then its content is included in the JSP
page.
=>If the resource is dynamic then its result is included in the JSP
page.
syntax:
<jsp:include attributes>
ii
</jsp:include>
ath
attributes of include tag:
ip
*imp
Ma
page : Takes a relative URL,which locates the resource
<jsp:include page="<%=mypath%>"/>
ate
2.<jsp:forward>:
=> This action tag forwards a JSP request to another resource and
=>If the resource is dynamic then we can use a jsp:param tag to pass
name and value of the parameter to the resource.
sntax:
<jsp:forward attributes>
</jsp:forward>
ii
Exp:
ath
<jsp:forward page="/Header.html"/>
<jsp:forward page="<%=mypath%>"/>
ip
3.<jsp:param>:
Ma
This action tag is used to hold the parameter with value and which
syntax:
ate
====================================================
nk
4.<jsp:useBean>:
Ve
syntax:
<jsp:useBean attributes>
</jsp:useBean>
(a)id
ii
(b)scope
ath
(c)class
(d)beanName
ip
(e)type
(a)id:
Ma
=>which represents the variable name assigned to id attribute of
sh
<jsp:useBean> tag and which holds the reference of JavaBean instance.
ate
(b)scope:
created or located.
Ve
(i)page scope : within the JSP page,until the page sends response.
(ii)request scope : JSP page processing the same request until a JSP sends response.
(c)class :
bean instance.
ii
(d)beanName :
ath
=>The beanName attribute takes a qualified class name.
ip
(e)type :
Ma
=>The "type" attribute takes a qualified className or interfaceName,
5.<jsp:setProperty>:
ate
Types of attributes:
Ve
(a)name
(b)property
(c)value
(d)param
(a)name:
(b)property:
ii
specifies the setter method that has to be invoked.
ath
(c)value:
ip
=>The value attribute takes the value that has to be set to the
6.<jsp:getProperty>:
nk
the bean's getter method and writes the value to the current JspWriter.
Ve
Types of attributes:
(a)name
(b)property
(a)name:
(b)property:
=>which gets the value of a bean property and invokes the getter
ii
method of the bean property.
ath
-------------------------------------
ip
The following are some rare used Actions tags:
Syntax:
nk
<jsp:plugin attributes>
</jsp:plugin>
be displayed if the required plug-in cannot run and this action tag
must be used as a child tag with the <jsp:plugin> action tag.
Syntax:
<jsp:fallback>
</jsp:fallback>
ii
ath
9. < jsp:params >
ip
pass to an applet.
Syntax:
Ma
<jsp:params>
sh
<!-one or more jsp:param tags---
</jsp:params>
ate
=======================================================================
nk
Exp application_2:
DBConnection.java
package test;
import java.sql.*;
public class DBConnection {
private static Connection con=null;//reference variable
private DBConnection() {}
static
{
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
}catch(Exception e) {e.printStackTrace();}
}
public static Connection getCon()
ii
{
return con;
ath
}
}
LoginDAO.java
ip
package test; Ma
import java.sql.*;
import javax.servlet.http.*;
try {
nk
PreparedStatement ps = con.prepareStatement
Ve
ps.setString(1,req.getParameter("uname"));
ps.setString(2,req.getParameter("pword"));
ResultSet rs = ps.executeQuery();
if(rs.next()) {
fName = rs.getString(3);
}catch(Exception e) {e.printStackTrace();}
return fName;
ii
login.html
ath
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
ip
<title>Insert title here</title>
</head> Ma
<body>
<form action="LoginJSP.jsp" method="post">
UserName:<input type="text" name="uname"><br>
PassWord:<input type="password" name="pword"><br>
<input type="submit" value="Login">
<a href="register.html">NewUser?</a>
sh
</form>
</body>
</html>
ate
LoginJSP.jsp
pageEncoding="ISO-8859-1"
import="test.*"%>
<!DOCTYPE html>
Ve
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String fName = new LoginDAO().login(request);
if(fName==null){
out.println("Invalid Login process...<br>");
%>
<jsp:include page="login.html"/>
<%
}else{
%>
<jsp:forward page="WelcomeJSP.jsp">
<jsp:param value="<%=fName %>" name="fname"/>
</jsp:forward>
<%
}
%>
ii
</body>
</html>
ath
WelcomeJSP.jsp
ip
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html> Ma
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
sh
<%
String fName = request.getParameter("fname");
out.println("Wlcome User : "+fName+"<br>");
ate
%>
</body>
</html>
nk
web.xml
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
</web-app>
diagram:
ii
ip ath
Ma
----------------------------------------------------------------------
Assignment:
Dt : 17/6/2022
Exp program_3:
ii
ProductBean.java(Bean class)
ath
package test;
import java.io.*;
@SuppressWarnings("serial")
public class ProductBean implements Serializable{
ip
private String code,name;
private float price; Ma
private int qty;
public ProductBean() {}
public String getCode() {
return code;
}
public void setCode(String code) {
sh
this.code = code;
}
public String getName() {
ate
return name;
}
public void setName(String name) {
this.name = name;
}
nk
input.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
ii
<form action="LoadJSP.jsp" method="post">
ath
Enter the PCode:<input type="text" name="pcode"><br>
<input type="submit" value="Display">
</form>
</body>
</html>
ip
LoadJSP.jsp Ma
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"
import="java.sql.*,test.*"%>
<!DOCTYPE html>
sh
<html>
<head>
<meta charset="ISO-8859-1">
ate
ii
</html>
ath
ViewJSP.jsp
ip
import="test.*"%>
<!DOCTYPE html> Ma
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
sh
<jsp:useBean id="ob" type="test.ProductBean" scope="session"/>
ProductCode:<jsp:getProperty property="code" name="ob"/><br>
ProductName:<jsp:getProperty property="name" name="ob"/><br>
ate
</body>
nk
</html>
web.xml
Ve
DBConnection.java
package test;
import java.sql.*;
public class DBConnection {
private static Connection con=null;//reference variable
private DBConnection() {}
static
{
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection
ii
("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
}catch(Exception e) {e.printStackTrace();}
ath
}
public static Connection getCon()
{
return con;
}
ip
}
RetrieveDAO.java Ma
package test;
import java.sql.*;
import javax.servlet.http.*;
sh
public class RetrieveDAO {
ate
try {
Ve
PreparedStatement ps = con.prepareStatement
ps.setString(1,req.getParameter("pcode"));
rs = ps.executeQuery();
}catch(Exception e) {e.printStackTrace();}
return rs;
=====================================================================
ii
Dt : 18/6/2022
ath
*imp
ip
Ma
Two types of development models are used in Java,for Web applications
1. Model-1 Architecture
2. Model-2 Architecture(MVC)
nk
1. Model-1 Architecture:
Ve
develop Web applications and this model uses JSP to design applications
A single change in one page may cause changes in other pages, leading
to unpredictable results.
ii
ath
(ii).Involves the developer at both the page development and the
ip
Ma
(iii).Increases the complexity of a program with the increase in the
===========================================================
2. Model-2 Architecture:
ii
and this Model-2 architecture is based on the MVC design model.
ath
=>MVC Stands for Model View Controller.
ip
Ma
Model: Represents enterprise data and business rules that specify how
using JavaBeans.
sh
enterprise data through the Model component and specifies how that
and delegates the responsibility for producing the next phase of the
complete control over each view, implying that any change in the Model
ii
business logic of other applications.
ath
(ii)Offers great flexibility to the presentation logic, which can be
ip
modified without effecting the business logic.
Ma
sh
ate
nk
Ve
=====================================================================
Dt : 20/6/2022
ii
Note:
ath
It is newly added feature in JSP technology.
ip
syntax of EL:
$(expression)
Ma
sh
The following are the implicit objects of EL:
ate
pageScope : It maps the given attribute name with the value,set in the vxvc v
page scope
nk
requestScope : It maps the given attribute name with the value set
Ve
sessionScope : It maps the given attribute name with the value set
paramValues :
ii
It maps the request parameters to the array of values
ath
header : It maps the request header name to the single value
ip
Ma
headerValues : It maps the request header names to the array of values
===============================================================
CoreJava Objects:
2.WrapperClass objects
(i)Byte Object
(ii)Short Object
(iii)Integer object
(iv)Long Object
(v)Float Object
(vi)Double Object
(vii)Character object
(viii)Boolean Object
ii
3.String Objects
ath
(i)String Object
(ii)StringBuffer object
ip
(iii)StringBuilder object
4.Array Objects
(iv)Object Array
ate
(v)Jagged Array
5.Collection<E> Objects
nk
(a)Set<E>
(i)HashSet<E> object
Ve
(ii)LinkedHashSet<E> Object
(iii)TreeSet<E> Object
(b)List<E>
(i)ArrayList<E> Object
(ii)Vector<E> Object
|->Stack<E> Object
(iii)LinkedList<E> Object
(c)Queue<E>
(i)PriorityQueue<E> Object
|->Deque<E>
(ii)ArrayDeque<E> Object
ii
6.Map<K,V> Objects
ath
(i)HashMap<K,V> Object
(ii)LinkedHashMap<K,V> Object
ip
(iii)TreeMap<K,V> Object
(iv)Hashtable<K,V> Object
7.Enum<E> objects
Ma
--------------------------
sh
JDBC Objects:
1.Connection Object
ate
2.Statement Object
3.PreparedStatement Object
nk
4.CallableStatement object
7.DatabaseMetaData object
8.ParameterMetaData object
9.ResultSetMetaData object
10.RowSet Object
------------
Servlet Objects:
1.ServletContext object
2.ServletConfig Object
ii
3.ServletRequest object/HttpServletRequest object
ath
4.ServletResponse object/HttpServletResponse object
5.PrintWriter object
ip
6.HttpSession object
7.Cookie object
JSP objects:
1.application
nk
2.config
3.request
Ve
4.response
5.out
6.session
7.exception
8.page
9.pageContext
----------
JSP EL objects:
1.pageScope
2.sessionScope
ii
3.requestScope
ath
4.applicationScope
5.param
ip
6.paramValues
7.cookie
8.pageContext
Ma
9.header
sh
10.headerValues
11.initParam
ate
--------------------------
Note:
nk
Advantages of JSTL:
(i)Fast Development
Ve
(ii)Code Reusability
(2)Function Tags
(3)Formatting Tags
(4)XML Tags
(5)SQL Tags
ii
ath
Note:
ip
=>To Execute JSTL Tags we use the following steps:
Ma
sh
(i)Download the following Jar files to execute JSTL tags
ate
javax.servlet.jsp.jstl-1.2.1.jar
javax.servlet.jsp.jstl-api-1.2.1.jar
nk
------------------------------------------------------------
(1)Core Tags:
syntax:
prefix="c" %>
ii
ath
The following are the List of JSTL Core Tags:
ip
c:out ->It displays the result of an expression, similar to
<%=...%> tag.
Ma
c:import->It Retrives relative or an absolute URL.
sh
in the body.
*imp
ii
c:forTokens-> It iterates over tokens which is separated by the
ath
supplied delimeters.
ip
c:param-> It adds a parameter in a containing 'import' tag's URL.
Ma
c:redirect-> It redirects the browser to a new URL and supports the
context-relative URLs.
sh
-----------------------------------------------------
(2)Function Tags:
nk
functions.
syntax:
ii
fn:containsIgnoreCase(): It is used to test if an input string
ath
contains the specified substring as a case insensitive way.
ip
fn:endsWith() : It is used to test if an input string ends with the
specified suffix.
Ma
fn:indexOf(): It returns an index within a string of first occurrence
sh
of a specified substring.
ate
fn:trim(): It removes the blank spaces from both the ends of a string.
nk
case.
fn:toUpperCase(): It converts all the characters of a string to
uppercase.
ii
ath
fn:length(): It returns the number of characters inside a string, or
ip
Ma
fn:replace(): It replaces all the occurrence of a string with
---------------------------------------------------------------
sh
(3)Formatting Tags:
syntax:
prefix="fmt" %>
List of some Formatting tags:
ii
specific format or precision.
ath
fmt:parseDate : It parses the string representation of a time and
ip
date.
fmt:setTimeZone
Ma
: It stores the time zone inside a time zone
configuration variable.
sh
*imp
ate
-------------------------------------------------------------
Ve
(4)XML Tags:
=>The JSTL XML tags are used for providing a JSP-centric way of
syntax:
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>
(5)SQL Tags:
=>The SQL tag library allows the tags to Interact with RDBMS
or Oracle.
ii
ath
syntax:
ip
Note:
Ma
=>In realtime we must not have JSP Centric XML and DB Connections,
because of this reason XML tags and SQL Tags are less used when
sh
compared to other tags.
================================================================
ate
nk
Ve