You are on page 1of 553

Unit 1 – Java Networking

Q1. What is Server Socket? Discuss the difference between the Socket and
ServerSocket class.
Ans.  The ServerSocket class (java.net) can be used to create a server socket.
 This object is used to establish communication with the clients.
 A server socket waits for requests to come in over the network. It performs some operation based
on that request, and then possibly returns a result to the requester.
 The actual work of the server socket is performed by an instance of the SocketImpl class.
 An application can change the socket factory that creates the socket implementation to configure
itself to create sockets appropriate to the local firewall.
Constructor
ServerSocket(int port) Creates a server socket, bound to the specified port.
Method
public Socket accept() Returns the socket and establish a connection between
server and client.
Syntax
ServerSocket ss=new ServerSocket(Port_no);
Difference between the Socket and ServerSocket class.
ServerSocket Socket
It is placed in server side, which sends request It is placed in client side, which sends request
to client side socket (Socket) and wait for the to server side socket (ServerSocket) and wait
response from client. for the response from serve.
ServerSocket ss=new ServerSocket Socket s = new
(1111); Socket("localhost",1111);

Q2. What is Datagram Socket and Datagram Packet? Explain in detail with
example.
Ans. Java DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
Datagram Socket
 DatagramSocket class represents a connection-less socket for sending and receiving datagram
packets.
 A datagram is basically an information but there is no guarantee of its content, arrival or arrival time.
Constructor
DatagramSocket() It creates a datagram socket and binds it with the available Port
Number on the localhost machine.

DatagramSocket(int port) It creates a datagram socket and binds it with the given Port
Number.

DatagramSocket(int port, It creates a datagram socket and binds it with the specified port
InetAddress address) number and host address.

Swati Sharma, CE Department | 2160707 – Advanced Java 1


Unit 1 – Java Networking
Datagram Packet
 Java DatagramPacket is a message that can be sent or received.
 Additionally, packet delivery is not guaranteed.
 Datagram packets are used to implement a connectionless packet delivery service.
 Each message is routed from one machine to another based solely on information contained within
that packet.
 Multiple packets sent from one machine to another might be routed differently, and might arrive in
any order.
Constructor
DatagramPacket(byte[] barr, int length) It creates a datagram packet. This constructor is used to
receive the packets.
DatagramPacket(byte[] barr, int length, It creates a datagram packet. This constructor is used to
InetAddress address, int port) send the packets.

Example of Sending DatagramPacket by DatagramSocket


DSender.java
import java.net.*; //required for Datagram Class
public class DSender{
public static void main(String[] args)
throws Exception
{
DatagramSocket ds = new DatagramSocket();
String str = "Message sent by Datagram socket";
InetAddress ip = InetAddress.getByName("127.0.0.1");
DatagramPacket dp = new DatagramPacket
(str.getBytes(), str.length(), ip, 3000);
ds.send(dp);
ds.close();
}
}

DReceiver.java
import java.net.*;
public class DReceiver{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0,dp.getLength());
System.out.println(str);
ds.close();
}
}

Swati Sharma, CE Department | 2160707 – Advanced Java 2


Unit 1 – Java Networking

Q3. Explain InetAddress methods with appropriate example.


Ans.  This class represents an Internet Protocol (IP) address.
 The java.net.InetAddress class provides methods to get an IP of host name.
 It is the superclass of Inet6Address and Inet4Address classes.
 There are no constructors for this class but static methods which returns instances of InetAddress
class for general use.
Methods
Method Description
public static InetAddress Determines the IP address of a given host's name.
getByName(String host) InetAddress ip
throws UnknownHostException =InetAddress.getByName("www.darshan.ac.in");
System.out.println(“ip:“+ ip);
public static InetAddress Returns the address of the local host.
getLocalHost() InetAddress ip=InetAddress.getLocalHost();
throws UnknownHostException System.out.println(“LocalHost:“+ip);

public String getHostName() It returns the host name of the IP address.


InetAddress ip
=InetAddress.getByName("10.254.3.34");
System.out.println(“Hostname:”+ip.getHostName()
);
public String getHostAddress() It returns the IP address in string format.
InetAddress ip
=InetAddress.getByName("www.darshan.ac.in");
System.out.println(“HostAddress:”+ip.getHostAdd
ress());

Q4. Explain URL and URLConnection class with example


Ans. URL Class
 The Java URL class represents an URL.
 This class is pointer to “resource” on the World Wide Web.
Example
URL url=new URL("http://www.darshan.ac.in");
Method
public URLConnection This method of URL class returns the object of URLConnection class
openConnection() URLConnection urlcon=url.openConnection();
throws IOException

URLConnection class
 URLConnection is the superclass of all classes that represent a communications link between the
application and a URL.
 Instances of this class can be used both to read from and to write to the resource referenced by the
URL.

Swati Sharma, CE Department | 2160707 – Advanced Java 3


Unit 1 – Java Networking
Method
public InputStream getInputStream() Returns an input stream that reads from this open
throws IOException connection.

public OutputStream getOutputStream() Returns an output stream that writes to this connection.
throws IOException

Example
import java.io.*; //required for input stream
import java.net.*; //required for URL & URLConnection
public class URLConnectionDemo {
public static void main(String[] args){
try{
URL url=new URL("http://www.darshan.ac.in");
URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getInputStream();
int i;
while((i=stream.read())!=-1){
System.out.print((char)i);
}
}catch(Exception e){System.out.println(e);}
}
}

Q5. How to display IP address and host name for local machine.
Ans. import java.net.InetAddress;
public class Main {
public static void main(String[] args)throws Exception {
InetAddress addr = InetAddress.getLocalHost();
System.out.println("Local HostAddress: "+addr.getHostAddress());
String hostname = addr.getHostName();
System.out.println("Local host name: "+hostname);
}
}

Swati Sharma, CE Department | 2160707 – Advanced Java 4


Unit 1 – Java Networking

Q6. Write TCP and UDP program for two way communication.
Ans. TCP
-Server-
import java.io.*;
import java.net.*;
class Server1
{
public static void main(String ar[])throws Exception
{
ServerSocket ss=new ServerSocket(777);
Socket s=ss.accept();
System.out.println("Connection Established");
OutputStream obj=s.getOutputStream();
PrintStream ps=new PrintStream(obj);

String str="Hello Client";


ps.println(str);
ps.println("Bye");

ps.close();
ss.close();
s.close();
}
}
-TCPClient-
import java.io.*;
import java.net.*;
class Client1
{
public static void main(String ar[])throws Exception
{
Socket s=new Socket("localhost",777);
InputStream obj=s.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(obj));
String str;
while((str=br.readLine())!=null)
{
System.out.println("From Server: "+str);
}
br.close();
s.close();
}
}

Swati Sharma, CE Department | 2160707 – Advanced Java 5


Unit 1 – Java Networking
UDP
-Server-
import java.io.*;
import java.net.*;
class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}

-UDPClient-
import java.io.*;
import java.net.*;

class UDPClient
{
public static void main(String args[]) throws Exception
{
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();

InetAddress IPAddress = InetAddress.getByName("localhost");

byte[] sendData = new byte[1024];


byte[] receiveData = new byte[1024];

String sentence = inFromUser.readLine();


sendData = sentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, 9876);

Swati Sharma, CE Department | 2160707 – Advanced Java 6


Unit 1 – Java Networking
clientSocket.send(sendPacket);

DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}

Q7. Write a client-server program using UDP socket. Client send the list of N
strings and server responds the concatenation of those strings.
Ans. Dsender.java
import java.net.*;
import java.util.Scanner;
public class Dsender{
public static void main(String[] args) throws Exception{
DatagramSocket ds=new DatagramSocket();
DatagramPacket dp;
InetAddress ip=InetAddress.getByName("localhost");
String str;
Scanner sc=new Scanner(System.in);
while(true){
System.out.print("Enter Msg:");
str=sc.nextLine();
dp=new DatagramPacket(str.getBytes(),str.length(),ip,3000);
ds.send(dp);
}
}}
Dreceiver.java
import java.net.*;
public class Dreceiver{
public static void main(String[] args)throws Exception{
String str="",concat="";
DatagramSocket ds=new DatagramSocket(3000);
byte[] buf;
DatagramPacket dp;
while(true){
buf=new byte[1024];
dp=new DatagramPacket(buf, 1024);
ds.receive(dp);
str=new String(dp.getData(),0,dp.getLength());
if( !str.equals("exit"))
{ concat+=str; }
else{break;}
}
System.out.println(concat);
ds.close();}}

Swati Sharma, CE Department | 2160707 – Advanced Java 7


Unit 1 – Java Networking

Q8. Write a client server program using TCP where client sends a string and
server checks whether that string is palindrome or not and responds with
appropriate message.
Ans. -Server-
import java.net.*;
import java.io.*;
public class Server {

public static void main(String args[]) throws Exception


{
ServerSocket ss=new ServerSocket(777);
Socket s=ss.accept();
System.out.println("Connection Established");
OutputStream obj=s.getOutputStream();
PrintStream ps=new PrintStream(obj);
InputStream obj1=s.getInputStream();
BufferedReader br=new BufferedReader(new outStreamReader(obj1));
String str = br.readLine();
String newstr = "";
for(int i = str.length()- 1;i>=0;i-- )
{
char c = str.charAt(i);
newstr = newstr + c;

}
if(str.equalsIgnoreCase(newstr))
{
ps.println("string is palindrome ");
}
else
{
ps.println("string is not palindrome ");
}
ps.close();
ss.close();
s.close();
}
}

-Client-
import java.net.*;
import java.io.*;
public class Client {
public static void main(String args[]) throws Exception
{
Socket s=new Socket("localhost",777);
BufferedReader kbr=new BufferedReader(new InputStreamReader(System.in));
InputStream obj=s.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(obj));
OutputStream os = s.getOutputStream();
PrintStream ps = new PrintStream(os);
System.out.println("Enter text");
String str = kbr.readLine();
ps.println(str);
Swati Sharma, CE Department | 2160707 – Advanced Java 8
Unit 1 – Java Networking
String newStr = br.readLine();
System.out.println("Response from server=" + newStr);
br.close();
s.close();
}
}

Q9. Write a client-server program using TCP or UDP where the client sends 10
numbers and server responds with the numbers in sorted order.
Ans. Server-
import java.net.*;
import java.io.*;
import java.util.*;
public class Server {
public static void main(String args[]) throws Exception
{
ServerSocket ss=new ServerSocket(7777);
Socket s=ss.accept();
System.out.println("connected..........");
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
int r,i=0;
int n=din.readInt();
int a[]=new int[n];
System.out.println("data:");
int count=0;
System.out.println("Receiving Data....");
for(i=0;i<n;i++)
{
a[i]=din.readInt();
}
System.out.println("Data Received");
System.out.println("Sorting Data........");
Arrays.sort(a);
System.out.println("Data Sorted");
System.out.println("Sending Data........");
for(i=0;i<n;i++)
{
dout.writeInt(a[i]);
}
System.out.println("\nData Sent Successfully");
s.close();
ss.close();
}
}

Swati Sharma, CE Department | 2160707 – Advanced Java 9


Unit 1 – Java Networking
-Client-
import java.net.*;
import java.io.*;
import java.util.*;
public class Client {
public static void main(String[] args) throws Exception
{ Socket s=new Socket("127.0.0.1",7777);
if(s.isConnected())
{ System.out.println("Connected to server");
}
System.out.println("Enter size of array:");
Scanner scanner=new Scanner(System.in);
int n=scanner.nextInt();
int a[]=new int[n];
System.out.println("Enter element to array:");
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeInt(n);
for(int i=0;i<n;i++)
{
int r=scanner.nextInt();;
dout.writeInt(r);
}
System.out.println("Data Sent");
DataInputStream din=new DataInputStream(s.getInputStream());
int r;
System.out.println("Receiving Sorted Data....");
for(int i=0;i<n;i++)
{ r=din.readInt();
System.out.print(r+" ");
}
s.close();
}
}

Q10. Write a TCP Client-Server program to get the Date & Time details from
Server on the Client request.
Ans. -Server-
import java.net.*;
import java.io.*;
import java.util.Date;
public class Server {
public static void main(String args[]) throws Exception
{ ServerSocket ss=new ServerSocket(777);
while(true)
{ System.out.println("Waiting For Connection ...");
Socket soc=ss.accept();
DataOutputStream out=new DataOutputStream(soc.getOutputStream());
out.writeBytes("Server Date " + (new Date()).toString() + "\n");
out.close();
soc.close();
}}}

Swati Sharma, CE Department | 2160707 – Advanced Java 10


Unit 1 – Java Networking

-Client-
import java.net.*;
import java.io.*;
public class Client {
public static void main(String args[]) throws Exception
{
Socket s=new Socket("localhost",777);
BufferedReader in=
new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println(in.readLine());
}
}

Swati Sharma, CE Department | 2160707 – Advanced Java 11


Unit 1: Java Networking
Write a program in which client sends string from its standard input to the server.

The server reads the string, finds number of words, characters and digits of received

string and sends result back to client. Use connection-oriented communication.

Ans:

Server.java
import java.net.*;
import java.io.*;
public class Server {
public static void main(String args[]) throws Exception
{
ServerSocket ss=new ServerSocket(777);
Socket s=ss.accept();
System.out.println("Connection Established");

DataInputStream dis=new DataInputStream(s.getInputStream());


String str=(String)dis.readUTF();
System.out.println(str);

//count no. of character,digits


int count = 0;
int digits = 0;

// Count Word of string


str = str.trim();
String[] words = str.split("\\s+");
int wordcount = words.length;

//Counts no. digits and counts


for(int i = 0; i < str.length(); i++) {
if(str.charAt(i) >= 48 && str.charAt(i) <= 57)
digits++;
else
count++;
}

DataOutputStream dout=new DataOutputStream(s.getOutputStream());


dout.writeInt(wordcount);
dout.writeInt(digits);
dout.writeInt(count);

ss.close();
s.close();
}
}

Client.java

import java.net.*;
import java.io.*;
public class Client {
public static void main(String args[]) throws IOException
{
Socket s=new Socket("localhost",777);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

DataOutputStream dout=new DataOutputStream(s.getOutputStream());

System.out.println("Enter text");
String str = br.readLine();
dout.writeUTF(str);

//Data Receving
DataInputStream din=new DataInputStream(s.getInputStream());
int r=din.readInt();
System.out.println("Total number of words in a string: " + r);
int p=din.readInt();
System.out.println("Total number of Digits in a string: " + p);
int q=din.readInt();
System.out.println("Total number of character in a string: " + q);

s.close();
}
}
3160707
Advanced Java

Unit-2
JDBC
Programming
Subject Overview
Sr. No. Unit % Weightage
1 Java Networking 5
2 JDBC Programming 10
3 Servlet API and Overview 25
4 Java Server Pages 25
5 Java Server Faces 10
6 Hibernate 15
7 Java Web Frameworks: Spring MVC 10

Reference Book:
Complete Reference J2EE by James Keogh mcgraw publication
Chapter : 6 and 7
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC

3
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC

4
Introduction
• Database
– Collection of data
• DBMS
– Database Management System
– Storing and organizing data
• SQL
– Relational database
– Structured Query Language
• JDBC
– Java Database Connectivity
– JDBC driver

5
Introduction: JDBC
JDBC (Java Database Connectivity) is used to It provides classes and interfaces
connect java application with database. to connect or communicate Java
application with database.

JDBC is an API used to


communicate Java application to
database in database independent
and platform independent
manner.

Example
Oracle
MS Access
My SQL
SQL Server
..
.

6
Introduction: JDBC
• JDBC (Java Database Connection) is the standard
method of accessing databases from Java
application.
• JDBC is a specification from Sun Microsystem
that provides a standard API for java application
to communicate with different database.
• JDBC is a platform independent interface
between relational database and java
applications.

7
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC

8
What is an API?
• Application Program Interface
• A set of routines, protocols, and tools for building
software applications.
• JDBC is an API, which is used in java programming
for interacting with database.

9
Introduction: JDBC API
• JDBC API allows java programs to
i. Make a connection with database
ii. Creating SQL statements
iii. Execute SQL statement
Java Application

iv. Viewing & Modifying the resulting records


Java DB API
1. Open a Connection
2. Send a statement
DBMS Engine
3. Retrieve results
4. Close a connection 1. Create a connection
Session
2. Execute statement
3. Send results
4. Close the session

10
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC

11
The JDBC Connectivity Model
JDBC API

JAVA
JDBC Driver
Application Database

12
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC

13
JDBC Architecture
It provides classes & interfaces A Java program that runs stand
Java Application alone in a client or server.
to connect or communicate
Java application with database.

JDBC API This class manages a list of


This interface handles the database drivers.
communications with the It ensures that the correct
database driver is used to access each
JDBC Driver data source.
Manager

JDBC Driver JDBC Driver JDBC Driver


Database is a
collection of
organized
information
ODBC Data
Oracle SQL Server Source
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC

15
JDBC Driver
• API: Set of interfaces independent of the RDBMS
• Driver: RDBMS-specific implementation of API
interfaces e.g. Oracle, DB2, MySQL, etc.

Just like Java aims for “Write once, Run anywhere",


JDBC strives for “Write once, Run with any database".

16
JDBC Driver: Type1 (JDBC-ODBC Driver)
• Depends on support for ODBC
• Not portable
• Translate JDBC calls into ODBC calls and use Windows
ODBC built in drivers
• ODBC must be set up on every client
– for server side servlets ODBC must be set up on web server
• driver sun.jdbc.odbc.JdbcOdbc provided by JavaSoft with
JDK
• No support from JDK 1.8 (Java 8)
E.g. MS Access

17
JDBC Driver: Type 1 (JDBC-ODBC Driver)
Local Computer

Java Application
DB Vendor
Application Code Driver

Type 1
ODBC Local
JDBC ODBC Bridge
Driver DBMS

Vendor Specific Protocol Network Communication

Database Server
18
JDBC Driver: Type 1 (JDBC-ODBC Driver)
Advantages :
• Allow to communicate with all database supported by
ODBC driver
• It is vendor independent driver
Disadvantages:
• Due to large number of translations, execution speed is
decreased
• Dependent on the ODBC driver
• ODBC binary code or ODBC client library to be installed in
every client machine
• Uses java native interface to make ODBC call
Because of listed disadvantage, type1 driver is not used in
production environment. It can only be used, when database
doesn’t have any other JDBC driver implementation.
19
JDBC Driver: Type 2 (Native Code Driver)
• JDBC API calls are converted into native API calls, which
are unique to the database.
• These drivers are typically provided by the database
vendors and used in the same manner as the JDBC-ODBC
Bridge.
• Native code Driver are usually written in C, C++.
• The vendor-specific driver must be installed on each
client machine.
• Type 2 Driver is suitable to use with server side
applications.
• E.g. Oracle OCI driver, Weblogic OCI driver, Type2 for
Sybase
20
JDBC Driver: Type 2 (Native Code Driver)
Local Computer

Java Application
DB Vendor Driver
Application Code

Type 2
Native API Local
DBMS

Vendor Specific Protocol Network Communication

Database Server
21
JDBC Driver: Type 2 (Native Code Driver)
Advantages
• As there is no implementation of JDBC-ODBC bridge,
it may be considerably faster than a Type 1 driver.
Disadvantages
• The vendor client library needs to be installed on the
client machine.
• This driver is platform dependent.
• This driver supports all java applications except
applets.
• It may increase cost of application, if it needs to run
on different platform (since we may require buying
the native libraries for all of the platform).

22
JDBC Driver: Type 3 (Java Protocol)
• Pure Java Driver
• Depends on Middleware server
• Can interface to multiple databases – Not vendor specific.
• Follows a three-tier communication approach.
• The JDBC clients use standard network sockets to communicate
with a middleware application server.
• The socket information is then translated by the middleware
application server into the call format required by the DBMS.
• This kind of driver is extremely flexible, since it requires no code
installed on the client and a single driver can actually provide
access to multiple databases.

23
JDBC Driver: Type 3 (Java Protocol)
Local Computer Middleware Server

Java Application
JDBC Type 1 Driver
Application Code
JDBC Type 2 Driver

Type 3
JDBC-Net pure Java JDBC Type 4 Driver

Vendor Specific Protocol Network Communication

Database Server
24
JDBC Driver: Type 3 (Java Protocol)
Advantages
• Since the communication between client and the
middleware server is database independent, there is
no need for the database vendor library on the client.
• A single driver can handle any database, provided the
middleware supports it.
• We can switch from one database to other without
changing the client-side driver class, by just changing
configurations of middleware server.
• E.g.: IDS Driver, Weblogic RMI Driver

25
JDBC Driver: Type 3 (Java Protocol)
Disadvantages
• Compared to Type 2 drivers, Type 3 drivers are
slow due to increased number of network calls.
• Requires database-specific coding to be done in
the middle tier.
• The middleware layer added may result in
additional latency, but is typically overcome by
using better middleware services.

26
JDBC Driver: Type 4 (Database Protocol)
• It is known as the Direct to Database Pure Java Driver
• Need to download a new driver for each database engine
e.g. Oracle, MySQL
• Type 4 driver, a pure Java-based driver communicates
directly with the vendor's database through socket
connection.
• This kind of driver is extremely flexible, you don't need to
install special software on the client or server.
• Such drivers are implemented by DBMS vendors.

27
JDBC Driver: Type 4 (Database Protocol)

Local Computer

Java Application

Application Code

Type 4
100% Pure Java Local
DBMS

Vendor Specific Protocol Network Communication

Database Server
28
JDBC Driver: Type 4 (Database Protocol)
Advantages
• Completely implemented in Java to achieve platform independence.
• No native libraries are required to be installed in client machine.
• These drivers don't translate the requests into an intermediary format
(such as ODBC).
• Secure to use since, it uses database server specific protocol.
• The client application connects directly to the database server.
• No translation or middleware layers are used, improving performance.
• The JVM manages all the aspects of the application-to-database
connection.
Disadvantage
• This Driver uses database specific protocol and it is DBMS vendor
dependent.

29
JDBC Driver
Thin Driver You can connect to a database without the client installed on your
machine. E.g. Type 4.
Thick Driver Thick client would need the client installation.
E.g. Type 1 and Type 2.

30
Comparison between JDBC Drivers
Type: Type 1 Type 2 Type 3 Type 4
Name: JDBC-ODBC Native Code Java Protocol/ Database Protocol
Bridge Driver/ JNI Middleware
Vendor No Yes No Yes
Specific:
Portable No No Yes Yes

Pure No No Yes Yes


Java
Driver
Working JDBC-> ODBC JDBC call -> native JDBC call -> JDBC call ->DB
call specific call middleware specific call
ODBC -> native specific.
call Middleware ->
native call
Multiple Yes NO Yes No
DB [only ODBC [DB Driver should
supported DB] be in middleware]
31
Comparison between JDBC Drivers
Type: Type 1 Type 2 Type 3 Type 4
Name: JDBC-ODBC Native Code Java Protocol/ Database Protocol
Bridge Driver/ JNI Middleware
Example MS Access Oracle OCI driver IDA Server MySQL
Executio Slowest among Faster Compared Slower Compared Fastest among all
n Speed all to Type1 to Type2
Driver Thick Driver Thick Driver Thin Driver Thin Driver

32
Which Driver should be Used?
• If you are accessing one type of database such as
MySql, Oracle, Sybase or IBM etc., the preferred
driver type is 4.
• If your Java application is accessing multiple types of
databases at the same time, type 3 is the preferred
driver.
• Type 2 drivers are useful in situations, where a type 3
or type 4 driver is not available yet for your database.
• The type 1 driver is not considered a
deployment-level driver, and is typically used for
development and testing purposes only.

33
JDBC with different RDBMS
RDBMS JDBC driver name URL format
MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/ databaseName
ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port
Number:databaseName
DB2 com.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port Number
/databaseName
Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:<host>:<port>
SQLite org.sqlite.JDBC jdbc:sqlite:C:/sqlite/db/databaseName
SQLServer com.microsoft.sqlserver.jdbc.SQLSer jdbc:microsoft:sqlserver:
verDriver //hostname:1433;DatabaseName

34
GTU Question : JDBC
1 What is JDBC? List out all various types of JDBC Driver. Explain Sum’16
Thick and Thin driver. Write code snippet for each type of JDBC
connection. Comment on selection of driver. [7 Marks]
2 What is JDBC? Explain the types of JDBC drivers? Write a code Win’16
snippet for each type of JDBC connection. [7 Marks]
3 Explain JDBC driver types in detail. [7 Marks] Sum’17

35
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC

36
JDBC Components
The JDBC API provides the following interfaces and classes
Package java.sql
Class

It acts as an interface between user and


DriverManager
drivers. It keeps track of the drivers that
are available
This and handles
interface establishingthe
handles a
Driver connection between
communications a database
with and the
the database
appropriate
server. Driverdriver. interface provides
vendor-specific implementations of the
Interface

Connection This Interface


abstract is the
classes session by
provided between java
the JDBC
application
API. and database. It contains all
methods for contacting a database.
Statement This interface is used to submit the SQL
statements to the database.
These objects hold data retrieved from a
ResultSet database after you execute an SQL query
using Statement objects. It acts as an
Exception

iterator to allow you to move through its


SQLException This
data.class handles any errors that occur in a
database application.
37
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC

38
JDBC Package
java.sql

• Contains core java objects of JDBC API.


• It includes java data objects, that provides basics
for connecting to DBMS and interacting with data
stored in DBMS.
• This package performs JDBC core operations such
as Creating and Executing query.

39
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC

40
JDBC Process
Step 1: Loading JDBC Driver
Step 2: Connection to DBMS
Step 3: Creating and executing statement
Step 4: Processing data returned by the DBMS
Step 5: Terminating Connection with DBMS

41
Step 1: Loading JDBC Driver
• Create an instance of the driver
• Register driver in the driver manager
• Loading the driver or drivers
for example, you want to use driver for mysql, the
following code will load it:
Returns the Class object associated with the
class or interface with the given string name.
Class.forName("com.mysql.jdbc.Driver");

Class that Sub-Pakage


represent classes Main Pakage
and interfaces in Class.forName() It is used to initiate
a running Java is used for loading Driver at runtime
application. class dynamically 42
Step 2: Connection to DBMS
• After you've loaded the driver, you can establish
a connection using the DriverManager class
(java.sql.DriverManager).
Method: DriverManager
public static Connection Attempts to establish a connection to the given
getConnection(String url) database URL. The DriverManager attempts to
throws SQLException select an appropriate driver from the set of
registered JDBC drivers.
public static Connection Attempts to establish a connection to the given
getConnection(String url, database URL.
String user, url - a database url of the
String password form jdbc:subprotocol:subname
) user - the database user on whose behalf the
throws SQLException connection is being made
password - the user's password
43
Step 2: Connection to DBMS
Syntax:
Interface of java.sql package

Connection conn=
DriverManager.getConnection(URL,USER_NM,PASS);

Class of java.sql package

Example:
Connection conn = DriverManager.getConnection
("jdbc:mysql://localhost:3306/gtu","root", "pwd");

Database Name

44
Step 3: Creating statement
• Once a connection is obtained, we can interact with the
database.
• The JDBC Statement interfaces define the methods and
properties that enable you to send SQL or PL/SQL
commands and receive data from your database.

Statement st=con.createStatement();

Interface is used for Statement createStatement()


general-purpose access to your throws SQLException
database, when using static SQL Creates a Statement object for sending
statements at runtime. SQL statements to the database.

45
Step 3:Executing Statement
• Once you've created a Statement object, you can
then use it to execute an SQL statement with one
of its three execute methods.
ResultSet executeQuery(String sql) Returns a ResultSet object. Use this method
throws SQLException when you expect to get a result set, as you
would with a SELECT statement.
Boolean execute(String sql) Returns a boolean value of true if a ResultSet
throws SQLException object can be retrieved; otherwise, it returns
false.
int executeUpdate(String sql) Returns the number of rows affected by the
throws SQLException execution of the SQL statement.
for example, an INSERT, UPDATE, or DELETE
statement.

46
Step 3: Executing Statement
Syntax:
ResultSet rs=st.executeQuery(“query”);

It holds data retrieved from a Returns a ResultSet object. Use this


database after you execute an SQL method when you expect to get a
query using Statement objects. It result set, as you would with a
acts as an iterator to allow you to SELECT statement.
move through its data.

Example
ResultSet rs = stmt.executeQuery
("SELECT * from student");

47
Step 3: Executing Statement
ResultSet rs = stmt.executeQuery
("SELECT * from student");
ResultSet rs
Enr_no Name Branch
601 abc ce
602 pqr me
Database
603 rst ec
604 def Ci

48
Step 3: Executing Statement
ResultSet rs = stmt.executeQuery
("SELECT * FROM student WHERE
Enr_no='601'OR Enr_no='602'");

ResultSet rs
Enr_no Name Branch
Database
601 abc ce
602 pqr me

49
Step 4:Processing data returned by the DBMS
• Method: Resultset
boolean next() Moves the cursor forward one row from its
Throws SQLException current position.
String getString Retrieves the value of the designated column in
(int col_Index) the current row of this ResultSet object as
throws SQLException a String
String getString Retrieves the value of the designated column in
(String col_Label) the current row of this ResultSet object as
throws SQLException a String in the Java programming language.
int getInt Returns the int in the current row in the
(int columnIndex) throws specified column index.
SQLException
int getInt Retrieves the value of the designated column in
(String columnLabel) the current row
throws SQLException

50
Processing data returned by the DBMS
• Example
while(rs.next()) Returns the value of
specified Column number
{
System.out.println(rs.getString(1));

System.out.println(rs.getInt(“emp_id”)
);
} Returns the value of specified Column name

51
Step 5:Terminating Connection with DBMS
• The connection of DBMS is terminated by using
close() method.
Example
Releases this ResultSet object's
rs.close(); database and JDBC resources
immediately

st.close();
Releases this Statement object's
database and JDBC resources
con.close(); immediately

Releases this Connection object's


database and JDBC resources
immediately

52
JDBC with different RDBMS
RDBMS JDBC driver name URL format
MySQL com.mysql.jdbc.Driver jdbc:mysql://hostname/databaseName
ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:port
Number:databaseName
DB2 com.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:port Number
/databaseName
Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:<host>:<port>
SQLite org.sqlite.JDBC jdbc:sqlite:C:/sqlite/db/databaseName
SQLServer com.microsoft.sqlserver.jdbc.SQLSer jdbc:microsoft:sqlserver:
verDriver //hostname:1433;DatabaseName

53
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC

54
JDBC Program
Class.forName("com.mysql.jdbc.Driver");

Connection conn=
DriverManager.getConnection
("jdbc:mysql://localhost:3306/gtu",
“root”, “pwd”);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery("SELECT
* from student");

while(rs.next())
System.out.print(rs.getString(1));

stmt.close();

conn.close();
55
First JDBC Program
1. import java.sql.*;
2. public class ConnDemo {
3. public static void main(String[] args) {
4. try {
5. Class.forName("com.mysql.jdbc.Driver"); Database name
6. Connection conn= DriverManager.getConnection
7. ("jdbc:mysql://localhost:3306/gtu","root",”pwd");
8. Statement stmt = conn.createStatement();
9. ResultSet rs = stmt.executeQuery("SELECT * from student");
10. while(rs.next()){
11. System.out.print(rs.getInt(1)+"\t");
Table name
12. System.out.print(rs.getString(“Name”)+"\t");
13. System.out.println(rs.getString(3));
14. }//while
15. stmt.close();
16. conn.close();
17. }catch(Exception e){System.out.println(e.toString());
18. }//PSVM }//class

56
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC

57
Types of Statement
• The JDBC Statement, PreparedStatement and
CallableStatement interface define the methods
and properties that enable you to send SQL or PL/SQL
commands and receive data from your database.
java.sql interface
Use the for general-purpose access to
your database.
Useful for static SQL statements.
Statement Cannot accept parameters.

Use the when you plan to use the SQL


statements multiple times. The
PreparedStatement PreparedStatement interface accepts
input parameters at runtime.
Use the when you want to access the
database stored procedures. The
CallableStatement CallableStatement interface can also
accept runtime input parameters. 58
Prepared Statement
• The PreparedStatement interface extends the Statement
interface.
• It represents a precompiled SQL statement.
• A SQL statement is precompiled and stored in a
Prepared Statement object.
• This object can then be used to efficiently execute this
statement multiple times.
Parameter 3
Example Parameter 1

String query="insert into student values(?,?,?)";

Table Name
Parameter 2
59
Methods of PreparedStatement interface
public void Sets the integer value to the given parameter
setInt(int paramIndex, int value) index.
public void Sets the String value to the given parameter
setString(int paramIndex, String value) index.

public void Sets the float value to the given parameter


setFloat(int paramIndex, float value) index.
public void Sets the double value to the given parameter
setDouble(int paramIndex, double value) index.

public int executeUpdate() Executes the query. It is used for create, drop,
insert, update, delete etc.
public ResultSet executeQuery() Executes the select query. It returns an instance
of ResultSet.

60
Prepared Statement
• Now to create table in mysql.
create table gtu.student2
(
Enr_no VARCHAR(10) not null
Name VARCHAR(20),
Branch VARCHAR(10),
Division VARCHAR(10),
primary key (Enr_no)
)

61
Example of PreparedStatement that inserts the record
1. import java.sql.*;
2. public class PreparedInsert {
3. public static void main(String[] args) {
4. try {
5. Class.forName("com.mysql.jdbc.Driver");
6. Connection conn= DriverManager.getConnection
7. ("jdbc:mysql://localhost:3306/gtu", "root",“pwd");
8. String query="insert into student2 values(?,?,?,?)";
9. PreparedStatement ps=conn.prepareStatement(query);
10. ps.setString(1, "14092"); //Enr_no
11. ps.setString(2, "abc_comp"); //Name
12. ps.setString(3, "computer"); //Branch
13. ps.setString(4, "cx"); //Division
14. int i=ps.executeUpdate();
15. System.out.println("no. of rows updated ="+i);
16. ps.close();
17. conn.close();
18. }catch(Exception e){System.out.println(e.toString());} }//PSVM
}//class

62
Why to use PreparedStatement?
Improves performance:
• The performance of the application will be faster, if you
use PreparedStatement interface because query is
compiled only once.
• This is because creating a PreparedStatement object by
explicitly giving the SQL statement causes the statement
to be precompiled within the database immediately.
• Thus, when the PreparedStatement is later executed, the
DBMS does not have to recompile the SQL statement.
• Late binding and compilation is done by DBMS.
• Provides the programmatic approach to set the values.

63
GTU Exam Question
1. Show the use of PreparedStatement object to run Sum’16
precompiled SQL statement. Also write example of
java snippet for PreparedStaement.[7]
2. Explain the use of PreparedStatement with Win’16
appropriate example.[7]
3. Explain role of Prepared Statement with example.[7] Sum’17
4. Write a program to insert student records to Win’17
database using prepared statement.[7]

64
Callable Statement
• CallableStatement interface is used to call
the stored procedures.
• We can have business logic on the database by
the use of stored procedures that will make the
performance better as they are precompiled.
Example
Suppose you need the get the age an employee
based on the date of birth, you may create a
procedure that receives date as the input and
returns age of the employee as the output.
65
Callable Statement
• Three types of parameters exist: IN, OUT, and
INOUT. The PreparedStatement object only uses the
IN parameter. The CallableStatement object can use
all the three.
Parameter Description
IN A parameter whose value is unknown when the SQL statement is
created. You bind values to IN parameters with the setXXX()
methods.

OUT A parameter whose value is supplied by the SQL statement it


returns. You retrieve values from the OUT parameters with the
getXXX() methods.

INOUT A parameter that provides both input and output values. You bind
variables with the setXXX() methods and retrieve values with the
getXXX() methods.
66
Callable Statement
• Create mysql procedure to get book title for given
ISBN number.
Table: book

DB Column Name

DB Column Name

67
Example CallableStatement
1. import java.sql.*;
2. public class CallableDemo {
3. public static void main(String[] args) {
4. try {
5. Class.forName("com.mysql.jdbc.Driver");
6. Connection conn= DriverManager.getConnection
7. ("jdbc:mysql://localhost:3306/gtu", "root",“pwd");

8. CallableStatement cs=conn.prepareCall("{call gettitle(?,?)}");


9. cs.setInt(1,1201);
10. cs.registerOutParameter(2,Types.VARCHAR); Procedure
11. cs.execute(); Name
12. System.out.println(cs.getString(2));

13. cs.close();
14. conn.close();
15. }catch(Exception e){System.out.println(e.toString());}
16. }//PSVM
17. }//class

68
GTU Exam Question
1. Explain role of Callable Statement with example[7] Sum’17
2. Discuss CallableStatement with example.[4] Win’17

69
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC

70
Method: ResultSet
Categories
1. Navigational methods Used to move the cursor around.

2. Get methods Used to view the data in the columns of the current row

being pointed by the cursor.

3. Update methods Used to update the data in the columns of the current

row. The updates can then be updated in the underlying

database as well.

71
ResultSet: Navigational methods
boolean first() Moves the cursor to the first row.
throws SQLException
boolean last() Moves the cursor to the last row.
throws SQLException
boolean next() Moves the cursor to the next row. This method
throws SQL Exception returns false if there are no more rows in the result
set.
boolean previous() Moves the cursor to the previous row. This method
throws SQLException returns false if the previous row is off the result set.
boolean absolute(int row) throws Moves the cursor to the specified row.
SQLException
boolean relative(int row) throws Moves the cursor the given number of rows forward
SQLException or backward, from where it is currently pointing.
int getRow() Returns the row number that the cursor is pointing to.
throws SQLException

72
ResultSet: Get methods
int getInt(String columnName) Returns the int in the current row in the column
throws SQLException named columnName.

int getInt(int columnIndex) throws Returns the int in the current row in the specified
SQLException column index. The column index starts at 1,
meaning the first column of a row is 1, the second
column of a row is 2, and so on.

String getString(String columnLabel) Retrieves the value of the designated column in


throws SQLException the current row of this ResultSet object as
a String in the Java programming language.

String getString(int columnIndex) Retrieves the value of the designated column in


throws SQLException the current row of this ResultSet object as
a String in the Java programming language.

73
ResultSet: Update methods
void updateString(int col_Index, String s) Changes the String in the specified column to
throws SQLException the value of s.

void updateInt(int col_Index, int x) Updates the designated column with


throws SQLException an int value.

void updateFloat(int col_Index, float x) Updates the designated column with


throws SQLException a float value.

void updateDouble(int col_Index,double x) Updates the designated column with


throws SQLException a double value.

74
Types of ResultSet
Type Description
ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the
result set. Default
Type

ResultSet.TYPE_SCROLL_INSENSITIVE The cursor can scroll forward and


backward, and the result set is not
sensitive to changes made by others to
the database that occur after the result
set was created.
ResultSet.TYPE_SCROLL_SENSITIVE The cursor can scroll forward and
backward, and the result set is sensitive
to changes made by others to the
database that occur after the result set
was created.

75
Concurrency of ResultSet
Concurrency Description
ResultSet.CONCUR_READ_ONL Creates a read-only result set. Default
Type
Y
ResultSet.CONCUR_UPDATABL Creates an updateable result set.
E

76
ResultSet
try {
Statement stmt =
conn.createStatement( ResultSet Type
ResultSet.TYPE_FORWARD_ONLY,

ResultSet.CONCUR_READ_ONLY);
}
catch(Exception ex)
{
.... ResultSet Concurrency

77
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC

78
ResultSetMetaData Interface
• The metadata means data about data.
• If you have to get metadata of a table like
i. total number of column
ii. column name
iii. column type etc.
• ResultSetMetaData interface is useful because it
provides methods to get metadata from the
ResultSet object.

79
Method: ResultSetMetaData
int getColumnCount() it returns the total number of columns in the
throws SQLException ResultSet object.

String getColumnName(int index) it returns the column name of the specified column
throws SQLException index.

String getColumnTypeName(int it returns the column type name for the specified
index) index.
throws SQLException

80
ResultSetMetaData
1. import java.sql.*;
2. public class MetadataDemo {
3. public static void main(String[] args) {
4. try {Class.forName("com.mysql.jdbc.Driver");
5. Connection conn= DriverManager.getConnection
6. ("jdbc:mysql://localhost:3306/gtu", "root",“pwd");
7. Statement stmt = conn.createStatement
(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
8. ResultSet rs = stmt.executeQuery("SELECT * from student");
9. ResultSetMetaData rsmd=rs.getMetaData();
10. System.out.println("Total columns: "+rsmd.getColumnCount());
11. System.out.println("Column Name of 1st column:
"+rsmd.getColumnName(1));
12. System.out.println("Column Type Name of 1st column:“
+rsmd.getColumnTypeName(1));
13. stmt.close();
14. conn.close();
15. }catch(Exception e)
16. {System.out.println(e.toString());}
17. }//PSVM
18. }//class

81
DatabaseMetadata
• DatabaseMetaData interface provides methods
to get meta data of a database such as
1. database product name,
2. database product version,
3. driver name,
4. name of total number of tables etc.

82
DatabaseMetadata
1. Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/temp6","root","root");
2. DatabaseMetaData dbmd=con.getMetaData();
3. System.out.println("getDatabaseProductName:“
+dbmd.getDatabaseProductName());
4. System.out.println("getDatabaseProductVersion():“
+dbmd.getDatabaseProductVersion());
1. System.out.println("getDriverName():"+dbmd.getDriverName());
2. System.out.println("getDriverVersion():“
+dbmd.getDriverVersion());
3. System.out.println("getURL():"+dbmd.getURL());
4. System.out.println("getUserName():"+dbmd.getUserName());

83
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC

84
Executing SQL updates
1. import java.sql.*;
2. class UpdateDemo{
3. public static void main(String args[]){
4. try{ Class.forName("com.mysql.jdbc.Driver");
5. Connection con=DriverManager.getConnection(
6. "jdbc:mysql://localhost:3306/GTU","root","root");
7. Statement stmt=con.createStatement();
8. String query="update student set Name='abc601' where
Enr_no=601";
9. int i=stmt.executeUpdate(query);
10. System.out.println("total no. of rows updated="+i);
11. stmt.close();
12. con.close();
13. }catch(Exception e){ System.out.println(e);}
14. } }

85
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC

86
Transaction Management
Transaction Succeed

it
m m
Co

Transaction
Initial State
Ro
llba
ck

Transaction Failed

87
Transaction Management
• In JDBC, Connection interface provides methods
to manage transaction.
void setAutoCommit(boolean status) It is true by default, means each
transaction is committed bydefault.
void commit() commits the transaction.
void rollback() cancels the transaction.

88
Transaction Management:commit
1. import java.sql.*;
2. class CommitDemo{
3. public static void main(String args[]){
4. try{
5. Class.forName("com.mysql.jdbc.Driver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:mysql://localhost:3306/GTU","root","root");
8. con.setAutoCommit(false);//bydefault it is true
9. Statement stmt=con.createStatement();
10. int i=stmt.executeUpdate("insert into student
values(605,'def','ci')");
11. System.out.println("no. of rows inserted="+i);
12. con.commit();//commit transaction
13. con.close();
14. }catch(Exception e){ System.out.println(e);}
15. }}

89
Transaction Management:rollback
1. import java.sql.*;
2. class RollbackDemo{
3. public static void main(String args[]){
4. try{ Class.forName("com.mysql.jdbc.Driver");
5. Connection con=DriverManager.getConnection(
6. "jdbc:mysql://localhost:3306/GTU","root","root");
7. con.setAutoCommit(false);//bydeafault it is true
8. Statement stmt=con.createStatement();
9. int i=stmt.executeUpdate("insert into student
values(606,'ghi','ee')");
10. con.commit(); //Commit Transaction
11. i+=stmt.executeUpdate("insert into student values(607,'mno','ch')");
12. System.out.println("no. of rows inserted="+i);
13. con.rollback(); //Rollback Transaction
14. con.close();
15. }catch(Exception e){ System.out.println(e);}
16. }}

90
Transaction Isolation Level
• JDBC isolation level represents that, how a
database maintains its interiority against the
problem such as
1. dirty reads
2. non-repeatable reads
3. phantom reads
that occurs during concurrent transactions.

91
Transaction Isolation Level
What is Phantom read?
• At the time of execution of a transaction, if two
queries that are identical are executed, and the
rows returned are different from other.
• If you execute a query at time T1 and re-execute
it at time T2, additional rows may have been
added to the database, which may affect your
results.
• It is stated that a phantom read occurred.

92
Transaction Isolation Level
What is Dirty read?
• Dirty read occurs when one transaction is changing the record,
and the other transaction can read this record before the first
transaction has been committed or rolled back.
• This is known as a dirty read scenario because there is always a
possibility that the first transaction may rollback the change,
resulting in the second transaction having read an invalid data.

Transaction A begins Transaction B begins


UPDATE EMPLOYEE SET SELECT * FROM EMPLOYEE;
SALARY = 10000 WHERE (Transaction B reflects data which is
EMP_ID= ‘123’; updated by transaction A. But, those
updates have not yet been
committed).

93
Transaction Isolation Level
What is Non-Repeatable Read?
• Non Repeatable Reads happen when in a same
transaction same query yields to a different
result.
• This occurs when one transaction repeatedly
retrieves the data, while a difference transactions
alters the underlying data.
• This causes the different or non-repeatable
results to be read by the first transaction.

94
Transaction Isolation Level
Int Val. Isolation Level Description
1 TRANSACTION_READ_UNCOMMITTED It allows non-repeatable reads, dirty
reads and phantom reads to occur
2 TRANSACTION_READ_COMMITTED It ensures only those data can be read
which is committed. Prevents dirty
reads.
4 TRANSACTION_REPEATABLE_READ It is closer to serializable, but phantom
reads are also possible.
Prevents dirty and non-repeatable
reads.
8 TRANSACTION_SERIALIZABLE In this level of isolation dirty reads,
non-repeatable reads, and phantom
reads are prevented.

One can get/set the current isolation level by using method:


1. getTransactionIsolation()
2. setTransactionIsolation(int isolationlevelconstant)

95
Unit-2: JDBC Programming
1. Introduction
2. JDBC API
3. The JDBC Connectivity Model
4. JDBC Architecture
5. JDBC Driver
6. JDBC Components
7. JDBC Package
8. JDBC Process
9. JDBC Program
10. Types of Statement
11. ResultSet Interface
12. ResultSetMetaData Interface
13. Executing SQL updates
14. Transaction Management
15. Batch Processing in JDBC

96
Batch Processing in JDBC
• Instead of executing a single query, we can
execute a batch (group) of queries.
• It makes the performance fast.
• The java.sql.Statement and
java.sql.PreparedStatement interfaces provide
methods for batch processing.
Methods of Statement interface
void addBatch(String query) It adds query into batch.
int[] executeBatch() It executes the batch of queries.

97
Batch Processing in JDBC
1. Class.forName("com.mysql.jdbc.Driver");
2. Connection con=DriverManager.getConnection(
3. "jdbc:mysql://localhost:3306/GTU","root","root");
4. con.setAutoCommit(false);
5. Statement stmt=con.createStatement();
Create table
6. String query1,query2,query3,query4,query5;
7. query1="create table student(enr INT PRIMARY KEY, name VARCHAR(20),sem
INT,branch VARCHAR(10))";
8. query2="insert into student values(6001,'java',6,'ce')"; Insert
record
9. query3="insert into student values(6002,'php',6,'ce')";
10. query4="update student set name='cg' where enr=6002";
Update record
11. query5="delete from student where name='java'";
12. stmt.addBatch(query1);
13. stmt.addBatch(query2); Delete record
14. stmt.addBatch(query3);
15. stmt.addBatch(query4);
16. stmt.addBatch(query5);
17. int[] i=stmt.executeBatch();
18. con.commit();

98
GTU Questions:
1. What is JDBC? [Win -14]
List out different types of JDBC driver and explain role of each. [Sum -15]
Write code snippet for each type of JDBC connection. [Win -15]
Explain Thick and Thin driver. [Sum -16]
Comment on selection of driver. [Win -16]
2. Explain Prepared statements with suitable example [Win -15]
[Sum -16]
[Win -16]
[Win -17]
3. Give the use of Statement, PreparedStatement and CallableStatement [Win -14]
object. Write code to insert three records into student table using
PreparedStatement (assume student table with Name, RollNo, and Branch
field).
4. What is phantom read in JDBC? Which isolation level prevents it? [Sum -16]
5. Discuss CallableStatement with example. [Win -17]

99
JDBC Interview Question
1. What is the difference between execute, executeQuery, executeUpdate?
2. What are the benefits of PreparedStatement over Statement?
3. What is JDBC Savepoint? How to use it?
4. What is JDBC Connection isolation levels?
5. What is CLOB and BLOB datatypes in JDBC?
6. What is difference between java.util.Date and java.sql.Date?
7. What is SQL Warning? How to retrieve SQL warnings in the JDBC program?
8. Which type of JDBC driver is the fastest one?
9. What does Class.forName return?
10. What happens if we call resultSet.getInt(0).

100
Unit 4: Java Server
Pages
Introduction
► JSP technology is used to create web application just like Servlet technology.

► It can be thought of as an extension to servlet because it provides more functionality than


servlet such as expression language, jstl etc.

► A JSP page consists of HTML tags and JSP tags.

► The jsp pages are easier to maintain than servlet because we can separate designing and
development. It provides some additional features such as Expression Language, Custom
Tag etc.
Advantage of JSP over Servlet
1) Extension to Servlet

► JSP technology is the extension to servlet technology.

► We can use all the features of servlet in JSP. In addition to, we can use implicit objects,
predefined tags, expression language and Custom tags in JSP, that makes JSP development easy.

2) Easy to maintain

► JSP can be easily managed because we can easily separate our business logic with presentation
logic. In servlet technology, we mix our business logic with the presentation logic.

3) Fast Development: No need to recompile and redeploy

► If JSP page is modified, we don't need to recompile and redeploy the project. The servlet code
needs to be updated and recompiled if we have to change the look and feel of the application.

4) Less code than Servlet

► In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that reduces the code.
Life cycle of a JSP Page
The JSP pages follows these phases:
► Compilation
► Initialization
► Execution
► Cleanup
Life cycle of a JSP Page
Life cycle of a JSP Page
1) JSP Compilation

► When a browser asks for a JSP, the JSP engine first checks to see whether it needs to
compile the page. If the page has never been compiled, or if the JSP has been modified
since it was last compiled, the JSP engine compiles the page.

► The compilation process involves three steps:

1. Parsing the JSP.

2. Turning the JSP into a servlet.

3. Compiling the servlet.


Life cycle of a JSP Page

2) JSP Initialization

► When a container loads a JSP it invokes the jspInit() method before servicing any requests.

► If you need to perform JSP-specific initialization, override the jspInit() method:

public void jspInit()

// Initialization code...

► Typically initialization is performed only once and as with the servlet init method, you
generally initialize database connections, open files, and create lookup tables in the jspInit
method.
Life cycle of a JSP Page
3) JSP Execution

► This phase of the JSP life cycle represents all interactions with requests until the JSP is
destroyed.

► Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP
engine invokes the _jspService() method in the JSP.

► The _jspService() method takes an HttpServletRequest and anHttpServletResponse as its


parameters as follows:

void _jspService(HttpServletRequest request, HttpServletResponse response)

{ // Service handling code...

}
► The _jspService() method of a JSP is invoked once per a request and is responsible for
generating the response for that request and this method is also responsible for generating
responses to all seven of the HTTP methods ie. GET, POST, DELETE etc.
Life cycle of a JSP Page

4) JSP Cleanup

► The destruction phase of the JSP life cycle represents when a JSP is being removed
from use by a container.

► The jspDestroy() method is the JSP equivalent of the destroy method for servlets.
Override jspDestroy when you need to perform any cleanup, such as releasing
database connections or closing open files.

► The jspDestroy() method has the following form:

public void jspDestroy()


{
// Your cleanup code goes here.
}
JSP Processing
JSP Processing
► Just as a web server needs a servlet container to provide an interface to servlets, the server needs a JSP
container to process JSP pages.

1. The JSP container is responsible for intercepting requests for JSP pages.

2. To process all JSP elements in the page, the container first turns the JSP page into a servlet (known as the JSP page
implementation class).

3. all JSP elements are converted to Java code that implements the corresponding dynamic behavior. The container
then compiles the servlet class.

► Converting the JSP page to a servlet and compiling the servlet form the translation phase.

► The JSP container initiates the translation phase for a page automatically when it receives the first request
for the page. Since the translation phase takes a bit of time, the first user to request a JSP page notices a
slight delay.

► The JSP container is also responsible for invoking the JSP page implementation class (the generated
servlet) to process each request and generate the response. This is called the request processing phase.
Scripting elements
► In JSP, java code can be written inside the jsp page using the scriptlet tag.

► The scripting elements provides the ability to insert java code inside the jsp.

There are three types of scripting elements:

1. scriptlet tag

2. expression tag

3. declaration tag
Scripting elements
1) JSP scriptlet tag
► A scriptlet tag is used to execute java source code in JSP.
► Syntax is as follows:
<% java source code %>
Example of JSP scriptlet tag Index.jsp
Index.html <html>
<html> <head>
<body> <title>JSP Page</title>
<form action="index.jsp"> </head>
<input type="text" name="uname"> <body>
<input type="submit" value="go"><br/>
<%
</form>
String name=request.getParameter("uname");
</body>
out.print("welcome "+name);
</html>
%>
</body>
</html>
Scripting elements
2) JSP Expression tag
► The code placed within JSP expression tag is written to the output stream of the response.
► You need not write out.print() to write data.
Syntax of JSP expression tag
<%= statement %>

Example of JSP expression tag

<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>
Scripting elements
2) JSP Expression tag
Example of JSP expression tag that prints the user name
index.jsp welcome.jsp
<html> <html>
<body> <body>
<form action="welcome.jsp"> <%= "Welcome "+request.getParameter("uname") %
>
<input type="text" name="uname"><br/>
</body>
<input type="submit" value="go">
</html>
</form>
</body>
</html>
Scripting elements
3) JSP Declaration tag

► The JSP declaration tag is used to declare fields and methods.

► The code written inside the jsp declaration tag is placed outside the service() method of auto
generated servlet.

Syntax of JSP declaration tag

<%! field or method declaration %>


Scripting elements
► Example of JSP declaration tag that declares method
index.jsp
<html>
<body>
<%!
int cube(int n)
{
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>
Difference between JSP Scriptlet tag and
Declaration tag
JSP Implicit Objects
► There are 9 jsp implicit objects. These objects are created by the web
container that are available to all the jsp pages.

► The available implicit objects are out, request, config, session, application etc.
JSP Implicit Objects
1) JSP out implicit object
► For writing any data to the buffer, JSP provides an implicit object named out. It is the
object of JspWriter.
► In case of servlet you need to write:
PrintWriter out=response.getWriter();
► But in JSP, you don't need to write this code.
► Example of out implicit object
► In this example we are simply displaying date and time.
index.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>
JSP Implicit Objects
2) JSP request implicit object

► The JSP request is an implicit object of type HttpServletRequest i.e. created for each jsp request by
the web container.

► It can be used to get request information such as parameter, header information, remote address,
server name, server port, content type, character encoding etc.

► It can also be used to set, get and remove attributes from the jsp request scope.
Example of JSP request implicit object
index.html welcome.jsp
<form action="welcome.jsp"> <%
<input type="text" name="uname"> String name=request.getParameter("uname");
<input type="submit" value="go"><br/> out.print("welcome "+name);
</form> %>
JSP Implicit Objects
3) JSP response implicit object

► In JSP, response is an implicit object of type HttpServletResponse.

► The instance of HttpServletResponse is created by the web container for each jsp request.

► It can be used to add or manipulate response such as redirect response to another resource,
send error etc.
Example of response implicit object
index.html
welcome.jsp
<form action="welcome.jsp">
<%
<input type="text" name="uname">
response.sendRedirect("http://www.google.com");
<input type="submit" value="go"><br/>
%>
</form>
JSP Implicit Objects
4) JSP config implicit object

► In JSP, config is an implicit object of type ServletConfig.

► This object can be used to get initialization parameter for a particular JSP page.

► The config object is created by the web container for each jsp page.

Example of config implicit object:

index.html welcome.jsp
<%
<form action="welcome">
out.print("Welcome "+request.getParameter("uname"));
<input type="text" name="uname"> String driver=config.getInitParameter("dname");
<input type="submit" value="go"><br/> out.print("driver name is="+driver);
%>
</form>
JSP Implicit Objects
web.xml file
<web-app>
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>

<init-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
JSP Implicit Objects
5) JSP application implicit object

► In JSP, application is an implicit object of type ServletContext.

► The instance of ServletContext is created only once by the web container when application or
project is deployed on the server.

► This object can be used to get initialization parameter from configuaration file (web.xml).

► It can also be used to get, set or remove attribute from the application scope.
JSP Implicit Objects
Example of application implicit object:
index.html welcome.jsp
<form action="welcome"> <%
<input type="text" name="uname"> out.print("Welcome "+request.getParameter("uname"));
<input type="submit" value="go"><br/> String driver=application.getInitParameter("dname");
</form> out.print("driver name is="+driver);
%>
JSP Implicit Objects
Web.xml
<web-app>
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>
</web-app>
JSP Implicit Objects
6) session implicit object

► In JSP, session is an implicit object of type HttpSession.

► The Java developer can use this object to set, get or remove attribute or to get session information.

Example of session implicit object

index.html

<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
JSP Implicit Objects
Example of session implicit object

welcome.jsp
second.jsp
<html> <html>
<body> <body>
<% <%
String name=request.getParameter("uname");
String name=(String)session.getAttribute("
out.print("Welcome "+name); user");
session.setAttribute("user",name); out.print("Hello "+name);
<a href="second.jsp">second jsp page</a>
%> %>
</body>
</body>
</html>
</html>
JSP Implicit Objects
7) pageContext implicit object
► In JSP, pageContext is an implicit object of type PageContext class.
► The pageContext object can be used to set, get or remove attribute from one of the following scopes:
1. page
2. request
3. session
4. application
Example of pageContext implicit object
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form> </body> </html>
JSP Implicit Objects
welcome.jsp
second.jsp
<html>
<html>
<body>
<body>
<%
<%
String name=request.getParameter("uname");
String name=(String)pageContext.getAt
out.print("Welcome "+name); tribute("user",PageContext.SESSION_
SCOPE);
pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE);
out.print("Hello "+name);
<a href="second.jsp">second jsp page</a> %>
%> </body>
</body> </html>
</html>
JSP Implicit Objects
8) page implicit object

► In JSP, page is an implicit object of type Object class.

► This object is assigned to the reference of auto generated servlet class.

► It is written as:

Object page=this;

► For using this object it must be cast to Servlet type.

► For example:

<% (HttpServlet)page.log("message"); %>

Since, it is of type Object it is less used because you can use this object directly in jsp.

<% this.log("message"); %>


JSP Implicit Objects
9) exception implicit object

► In JSP, exception is an implicit object of type java.lang.Throwable class.

► This object can b


Example of exception implicit object:
error.jsp
<%@ page isErrorPage="true" %>
<html>
<body>
Sorry following exception occured:<%= exception %>
</body>
</html>

► e used to print the exception. But it can only be used in error pages.
JSP directives
► The jsp directives are messages that tells the web container how to translate a JSP page
into the corresponding servlet.

► There are three types of directives:

1. page directive

2. include directive

3. taglib directive

► Syntax of JSP Directive

<%@ directive attribute="value" %>


JSP directives
1) JSP page directive

► The page directive defines attributes that apply to an entire JSP page.

► Syntax of JSP page directive

<%@ page attribute="value" %>

► Attributes of JSP page directive

I. import VIII. isThreadSafe

II. contentType IX. autoFlush


III. extends
X. session
IV. info
XI. pageEncoding
V. buffer
XII. errorPage
VI. language

VII. isELIgnored XIII. isErrorPage


JSP directives
I)import

► The import attribute is used to import class,interface or all the members of a package.It is
similar to import keyword in java class or interface.

► Example of import attribute

<html>

<body>

<%@ page import="java.util.Date" %>

Today is: <%= new Date() %>

</body>

</html>
JSP directives
II)contentType
► The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type
of the HTTP response.
► The default value is "text/html;charset=ISO-8859-1".
Example of contentType attribute
<html>
<body>

<%@ page contentType=application/msword %>


Today is: <%= new java.util.Date() %>

</body>
</html>
JSP directives
III) extends
► The extends attribute defines the parent class that will be inherited by the generated servlet.It is
rarely used.

IV) info
► This attribute simply sets the information of the JSP page which is retrieved later by using
getServletInfo() method of Servlet interface.

The web container will create a method getServletInfo() in the


Example of info attribute resulting servlet.
<html> For example:
<body>
<%@ page info="composed by Sonoo Jaiswal" %> public String getServletInfo() {
Today is: <%= new java.util.Date() %> return "composed by Sonoo Jaiswal";
</body> }
</html>
JSP directives
V)buffer

► The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP page.

► The default size of the buffer is 8Kb.

► Example of buffer attribute

<html>

<body>

<%@ page buffer="16kb" %>

Today is: <%= new java.util.Date() %>

</body>

</html>
JSP directives
VI) language

► The language attribute specifies the scripting language used in the JSP page. The default
value is "java".

VII) isELIgnored

► We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute.

► By default its value is false i.e. Expression Language is enabled by default.

<%@ page isELIgnored="true" %>//Now EL will be ignored


JSP directives
VIII) isThreadSafe

► Servlet and JSP both are multithreaded.

► If you want to control this behaviour of JSP page, you can use isThreadSafe attribute of page
directive.

► The value of isThreadSafe value is true.

► If you make it false, the web container will serialize the multiple requests, i.e. it will wait
until the JSP finishes responding to a request before passing another request to it.

► If you make the value of isThreadSafe attribute like:

<%@ page isThreadSafe="false" %>


JSP directives
IX) errorPage

► The errorPage attribute is used to define the error page, if exception occurs in the current
page, it will be redirected to the error page.

► Example of errorPage attribute

index.jsp

<html>

<body>

<%@ page errorPage="myerrorpage.jsp" %>

<%= 100/0 %>

</body>

</html>
JSP directives
X) isErrorPage

► The isErrorPage attribute is used to declare that the current page is the error page.

Example of isErrorPage attribute

myerrorpage.jsp

<html>

<body>

<%@ page isErrorPage="true" %>

Sorry an exception occured!<br/>

The exception is: <%= exception %>

</body>

</html>
JSP directives
2) JSP include directives

► The include directive is used to include the contents of any resource it may be jsp file, html
file or text file.

Advantage of Include directive

► Code Reusability

Syntax of include directive

<%@ include file="resourceName" %>


JSP directives
2) JSP include directives
Example of include directive
► In this example, we are including the content of the header.html file. To run this example
you must create an header.html file.

<html>
<body>
<%@ include file="header.html" %>
Today is: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
JSP directives
3) JSP Taglib directives

► The JSP taglib directive is used to define a tag library that defines many tags.

► We use the TLD (Tag Library Descriptor) file to define the tags. In the custom tag section
we will use this tag so it will be better to learn it in custom tag.

Syntax JSP Taglib directive

<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>


JSP action tags
► There are many JSP action tags or elements. Each JSP action tag is used to perform some
specific tasks.
► The action tags are used to control the flow between pages and to use Java Bean.
JSP action tags
1) jsp:forward action tag
► The jsp:forward action tag is used to forward the request to another resource it may be jsp,
html or another resource.

Syntax of jsp:forward action tag without parameter

<jsp:forward page="relativeURL | <%= expression %>" />

Syntax of jsp:forward action tag with parameter

<jsp:forward page="relativeURL | <%= expression %>">

<jsp:param name="parametername" value="parametervalue | <%=expression%>" />

</jsp:forward>
JSP action tags
1) jsp:forward action tag
Example of jsp:forward action tag without parameter

index.jsp printdate.jsp
<html>
<html>
<body>
<body>
<h2>this is index page</h2>
<% out.print("Today is:"+java.util.Calendar.getInsta
<jsp:forward page="printdate.jsp" />
nce().getTime()); %>
</body>
</body>
</html>
</html>
JSP action tags
1) jsp:forward action tag

Example of jsp:forward action tag with parameter

index.jsp printdate.jsp
<html> <html>
<body> <body>
<h2>this is index page</h2>
<% out.print("Today is:"+java.util.Calendar.get
<jsp:forward page="printdate.jsp" > Instance().getTime()); %>
<jsp:param name="name" value=“abc" /> <%= request.getParameter("name") %>
</jsp:forward>
</body>
</body> </html>
</html>
JSP action tags
2) jsp:include action tag

► The jsp:include action tag is used to include the content of another resource it may be jsp, html
or servlet.

► The jsp include action tag includes the resource at request time so it is better for dynamic
pages because there might be changes in future.

► The jsp:include tag can be used to include static as well as dynamic pages.

Advantage of jsp:include action tag


► Code reusability : We can use a page many times such as including header and footer pages in all
pages. So it saves a lot of time.
JSP action tags
2) jsp:include action tag
JSP action tags
2) jsp:include action tag

Syntax of jsp:include action tag without parameter

<jsp:include page="relativeURL | <%= expression %>" />

Syntax of jsp:include action tag with parameter

<jsp:include page="relativeURL | <%= expression %>">

<jsp:param name="parametername" value="parametervalue | <%=expression%>" />

</jsp:include>
JSP action tags
2) jsp:include action tag

Example of jsp:include action tag without parameter

File: index.jsp File: printdate.jsp


<h2>this is index page</h2> <% out.print("Today is:"+java.util.Calendar.getInstan
ce().getTime()); %>

<jsp:include page="printdate.jsp" />

<h2>end section of index page</h2>


JSP action tags
3) jsp:useBean action tag

Java Bean- A Java Bean is a java class that should follow following conventions:

► It should have a no-arg constructor.

► It should be Serializable.

► It should provide methods to set and get the values of the properties, known as getter and
setter methods.

Why use Java Bean?

► According to Java white paper, it is a reusable software component. A bean encapsulates


many objects into one object, so we can access this object from multiple places. Moreover,
it provides the easy maintenance.
JSP action tags
3) jsp:useBean action tag
Simple example of java bean class
Employee.java Access the java bean class
package mypack; package mypack;
public class Employee implements java.io.Serializable{ public class Test{
private int id; public static void main(String args[])
private String name; {
public Employee(){} Employee e=new Employee();//object is created
public void setId(int id) e.setName("Arjun");//setting value to the object
{ this.id=id; System.out.println(e.getName());
} }
public int getId(){return id;} }
public void setName(String name){this.name=name;}
public String getName(){return name;}
}
JSP action tags
3) jsp:useBean action tag
Syntax of jsp:useBean action tag
<jsp:useBean id= "instanceName" scope= "page | request | session | application"
class= "packageName.className" type= "packageName.className"
beanName="packageName.className | <%= expression >" >
</jsp:useBean>

Attributes and Usage of jsp:useBean action tag


► id: is used to identify the bean in the specified scope.
► scope: represents the scope of the bean. It may be page, request, session or application. The
default scope is page.
► class: instantiates the specified bean class (i.e. creates an object of the bean class) but it must
have no-arg or no constructor and must not be abstract.
► type: provides the bean a data type if the bean already exists in the scope. If you use it without
class or beanName, no bean is instantiated.
► beanName: instantiates the bean using the java.beans.Beans.instantiate() method.
JSP action tags
3) jsp:useBean action tag

Calculator.java (a simple Bean class) index.jsp file


package com.javatpoint; <jsp:useBean id="obj" class="com.javatpoint.Cal
culator"/>
public class Calculator{
<%
public int cube(int n){
int m=obj.cube(5);
return n*n*n;
out.print("cube of 5 is "+m);
}
%>
}
JSP action tags
4) jsp:setProperty and jsp:getProperty action tags

► The setProperty and getProperty action tags are used for developing web application with Java
Bean.

► In web devlopment, bean class is mostly used because it is a reusable software component
that represents data.

The jsp:setProperty :action tag sets a property value or values in a bean using the setter
method.
Syntax of jsp:setProperty action tag
<jsp:setProperty name="instanceOfBean" property= "*" |
property="propertyName" param="parameterName" |
property="propertyName" value="{ string | <%= expression %>}"
/>
JSP action tags
4) jsp:setProperty and jsp:getProperty action tags

jsp:getProperty action tag

► The jsp:getProperty action tag returns the value of the property.

Syntax of jsp:getProperty action tag

<jsp:getProperty name="instanceOfBean" property="propertyName" />


JSP action tags
4) jsp:setProperty and jsp:getProperty action tags

Example of bean development in JSP

1. index.html for input of values

2. welocme.jsp file that sets the incoming values to the bean object and prints the one
value

3. User.java bean class that have setter and getter methods


JSP action tags
4) jsp:setProperty and jsp:getProperty action tags
Index.html
User.java
<form action="welcome.jsp"/>
package com.javatpoint;
Enter Name:<input type="text" name="name"/>
public class User{
<input type="submit" value="go" />
private String name;
</form>
public void setName(String name){
this.name=name;
}
Welcome.jsp
public String getName(){
<jsp:useBean id="obj"
return name;
class="com.javatpoint.User" />
}
<jsp:setProperty name="obj" property="*" />
}

Welcome, <jsp:getProperty name="obj"


property="name" />
JSP action tags
5) jsp:plugin action tag

► The jsp:plugin action tag is used to embed applet in the jsp file. The jsp:plugin action tag
downloads plugin at client side to execute an applet or bean.

Syntax of jsp:plugin action tag

<jsp:plugin type= "applet | bean" code= "nameOfClassFile"

codebase= "directoryNameOfClassFile"

</jsp:plugin>
JSP action tags
5) jsp:plugin action tag

► Following is the typical syntax of using plugin action:

<jsp:plugin type="applet" codebase="dirname" code="MyApplet.class" width="60" height="80">

<jsp:param name="fontcolor" value="red" />

<jsp:param name="background" value="black" />

<jsp:fallback> Unable to initialize Java Plugin </jsp:fallback>

</jsp:plugin>

► A new element, the <fallback> element, can be used to specify an error string to be sent to
the user in case the component fails.
Example
Create database of student subject-wise data and retrieve all data using JSP
stud.html
<html>
<head>
<title>Three Tier Application</title>
</head>
<body>
<h2>EXAMINATION RESULT</h2><hr/>
<form name="f1" method"GET" action="marklist.jsp">
Enter Your Reg.No:
<input type="text" name="regno"/><br/><br/>
<input type="submit" value="SUBMIT"/>
</form>
</body>
<html>
Example
marklist.jsp
<%@ page contentType="text/html" language="java" import="java.sql.*"%>
<html>
<head>
<title>Three Tier Application</title>
</head>
<body>
<h2>EXAMINATION RESULT</h2><hr/>
<%
String str=request.getParameter("regno");
Class.forName(" com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/STUDENTS", "root", "");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("SELECT * FROM markTab WHERE rno="+str);
while(rs.next())
{
%>
Example
marklist.jsp (cont’d)
Register No:<%=rs.getString(1)%><br/>
Name:<%=rs.getString (2)%><br/>
<table border="1">
<th>SUBJECT</th><th>Mark</th>
<tr><td>Advanced Java Technology</td><td><%=rs. getString3)%></td></tr>
<tr><td>Software Engineering</td><td><%=rs. getString(4)%></td></tr>
<tr><td>Dot net technology</td><td><%=rs. getString(5)%></td></tr>
<tr><td>Web technology</td><td><%=rs. getString(6)%></td></tr>
<tr><td>SPI</td><td><%=rs. getString(7)%></td></tr>
<tr><td>CPI</td><td><%=rs. getString(8)%></td></tr>
</table>
<% } %>
<br/>
<a href="stud.html">Back</a>
</body></html>
MVC in JSP
► MVC stands for Model View and Controller.

► It is a design pattern that separates the business logic, presentation logic and data.

► Controller acts as an interface between View and Model. Controller intercepts all the incoming
requests.

► Model represents the state of the application i.e. data. It can also have business logic.

► View represents the presentaion i.e. UI(User Interface).

Advantage of MVC (Model 2) Architecture

1. Navigation Control is centralized

2. Easy to maintain the large application


MVC in JSP
MVC in JSP
Example of following MVC in JSP
► Write small web application which takes marks of three subject and pass to servlet. Servlet
forward to model classs having method getClass() and getPercentage(). Display class and
percentage in .jsp page.

► In this example, we have created following pages:


1. index.jsp a page that gets input from the user.
2. studentResult.java a servlet that acts as a controller.
3. Display.jsp file acts as view components.
4. Student.java – works as Bean
MVC in JSP
File: index.jsp
<html>
<head>
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<form name="StudentMarks" action="StudentResult" method="POST">
<input type="text" name="sub1" value="" />
<input type="text" name="sub2" value="" />
<input type="text" name="sub3" value="" />
<input type="submit" value="Submit" name="submit" />
</form>
</body>
</html>
MVC in JSP
File: Student.java (Bean) public float getPercentage()
public class Student { {
int sub1; return percentage;
int sub2; }
int sub3; public String getStudentClass()
float percentage; {
if(percentage<100 && percentage>=70)
public void setMarks(int sub1,int sub2,int sub3) return "Distinction";
{ else if(percentage<70 && percentage>=60)
this.sub1 = sub1; return "First Class";
this.sub2 = sub2; else if(percentage<60 && percentage>=45)
this.sub3 = sub3; return "Second Class";
} else
public void calculatePercentage() return "Fail";
{ }
percentage = (float)(sub1+sub2+sub3)*100/300; }
}
MVC in JSP
StudentResult.java (Servlet)
public class StudentResult extends HttpServlet {
request.setAttribute("percentage",percentage);
protected void processRequest(HttpServletRequest request,
request.setAttribute("Class",Class);
HttpServletResponse response)
view.forward(request, response);
throws ServletException, IOException {
}
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter(); protected void doGet(HttpServletRequest request,
HttpServletResponse response)
Student ob = new Student();
throws ServletException, IOException {
int sub1 = Integer.parseInt(request.getParameter("sub1")); processRequest(request, response);
int sub2 = Integer.parseInt(request.getParameter("sub2")); }
int sub3 = Integer.parseInt(request.getParameter("sub3")); protected void doPost(HttpServletRequest request,
HttpServletResponse response)
ob.setMarks(sub1, sub2, sub3);
throws ServletException, IOException {
ob.calculatePercentage(); processRequest(request, response); }
float percentage = ob.getPercentage(); public String getServletInfo() {
String Class = ob.getStudentClass(); return "Short description";
RequestDispatcher view = }
request.getRequestDispatcher("Display.jsp"); }
MVC in JSP
Display.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Student Result</h1>
<% Float percentage = (Float)request.getAttribute("percentage");
String Class = (String)request.getAttribute("Class") %>
<h2>Percentage:<%=percentage%></h2>
<h2>Class:<%=Class%></h2>
</body>
</html>
Session Tracking in JSP
Following ways are used to maintain session between client and web server:

► Cookies

► Hidden Form Fields

► URL Rewriting

► HTTP sessions
Session Tracking in JSP
1) Cookies

► A cookie, also known as an HTTP cookie, web cookie, or browser cookie, is a small piece of
data sent from a website and stored in a user’s web browser while the user is browsing that
website.

► A cookie’s value can uniquely identify a client, so cookies are commonly used for session
management.

► Browser stores each message in a small file, called cookie.txt.

► When you request another page from the server, your browser sends the cookie back to the
server.

► Cookies have lifespan and are flushed by the client browser at the end of lifespan.
Session Tracking in JSP
1) Cookies

Cookie objects have following methods.

1. getComment () : Returns comment describing the purpose of the cookie.

2. getMaxAge () : Returns maximum specified age of the cookie.

3. getName() : Returns name of the cookie.

4. getPath() : Returns URL for which cookie is targeted.

5. getValue() :Returns value of the cookie.

6. setComment(String) : Cookie’s purpose will be described using this comment.

7. setMaxAge(int) : Sets maximum age of the cookie. A zero value causes the cookie to be deleted.

8. setPath(String) : It determines Cookie should begin with this URL .

9. setValue(String) : Sets the value of the cookie. Values with special characters such as white space,
brackets, equal sign, comma, double quote, slashes , “at” sign, colon and semicolon should be
avoided.
Session Tracking in JSP (Example)
1) Cookies
Index.html Login.jsp (Setting cookie)
Session Tracking in JSP (Example)
1) Cookies
Profile.jsp (For getting cookie) Logout.jsp (Destroying Cookie)
Session Tracking in JSP
2) Hidden Form Fields

► It is hidden (invisible) text field used for maintaining the state of user.

► We store the information in the hidden field and get it from another servlet.
Following shows how to store value in hidden field.

<input type=”hidden” name=”uname” value=”javabeat”>

► Here, name is hidden field name and javabeat is hidden field value. When the form is
submitted, the specified name and value are automatically included in the GET or POST
data.
Session Tracking in JSP
3) URL Rewriting

► A static HTML page or form must be dynamically generated to encode every URL.

► If you cannot verify that every user of web application uses cookies, then you must
consider web container need to use URL-rewriting.

Adding the session ID to a link contain following of methods:

1. response.encodeURL (): Associates a session ID with a given URL.

2. response.encodeRedirectURL () : If you are using redirection, this method can be


used
Session Tracking in JSP (Example)
3) URL Rewriting
For setting the value of session:
<a href="store/catalog;$jsessionid$DA32242SSGE2">

For getting the value of session:


<% response.encodeURL ("/store/catalog"); %>
Session Tracking in JSP
4) Session implicit object

► Session is most frequently used implicit object in JSP. The main usage of it to gain access to all the user’s
data till the user session is active.

Methods of session Implicit Object

1. setAttribute(String, object) – This method is used to save an object in session by assigning a unique string
to the object.

2. getAttribute(String name) – The object stored by setAttribute method is fetched from session using
getAttribute method.

3. removeAttribute(String name) – The objects which are stored in session can be removed from session using
this method. Pass the unique string identifier as removeAttribute’s method.

4. getAttributeNames – It returns all the objects stored in session. Basically, it results in an enumeration of
objects.

5. getCreationTime – This method returns the session creation time, the time when session got initiated
(became active).
Session Tracking in JSP
4) Session implicit object

Methods of session Implicit Object

6. getId – Servlet container assigns a unique string identifier to session while creation of
it. getId method returns that unique string identifier.

7. isNew() – Used to check whether the session is new. It returns Boolean value (true or
false).

8. invalidate() – It kills a session and breaks the association of session with all the stored
objects.

9. getMaxInactiveInterval – Returns session’s maximum inactivate time interval in seconds.

10. getLastAccessedTime – Generally used to know the last accessed time of a session.
Session Tracking in JSP
4) Session implicit object
index.html
<html>
<head>
<title>Welcome Page: Enter your name</title>
</head>
<body>
<form action="session.jsp">
<input type="text" name="inputname">
<input type="submit" value="click here!!"><br/>
</form>
</body>
</html>
Session Tracking in JSP
4) Session implicit object
session.jsp
<html>
<head>
<title>Passing the input value to a session variable</title>
</head>
<body>
<% String uname=request.getParameter("inputname"); out.print("Welcome "+ uname);
session.setAttribute("sessname",uname); %>
<a href="output.jsp">Check Output Page Here </a>
</body>
</html>
Session Tracking in JSP
4) Session implicit object
output.jsp

<html>

<head>

<title>Output page: Fetching the value from session</title>

</head>

<body>

<% String name=(String)session.getAttribute("sessname"); out.print("Hello User: You have


entered the name: "+name); %>

</body>

</html>
Java Server Pages Standard Tag Library(JSTL)
► The JavaServer Pages Standard Tag Library JSTL is a collection of useful JSP tags which
encapsulates core functionality common to many JSP applications.

► JSTL has support for common, structural tasks such as iteration and conditionals, tags
for manipulating XML documents, internationalization tags, and SQL tags. It also
provides a framework for integrating existing custom tags with JSTL tags.

► The JSTL tags can be classified, according to their functions, into following JSTL tag
library groups that can be used when creating a JSP page:
1. Core Tags
2. Formatting tags
3. SQL tags
4. XML tags
5. JSTL Functions
Java Server Pages Standard Tag Library(JSTL)
Install JSTL Library:

► If you are using Apache Tomcat container then follow the following two simple steps:

1. Download the binary distribution from Apache Standard Taglib and unpack the
compressed file.

2. To use the Standard Taglib from its Jakarta Taglibs distribution, simply copy the JAR
files in the distribution's 'lib' directory to your application's webapps\ROOT\WEB-
INF\lib directory.

► To use any of the libraries, you must include a <taglib> directive at the top of each JSP
that uses the library.
Java Server Pages Standard Tag Library(JSTL)
1) Core Tags:
► The core group of tags are the most frequently used JSTL tags. Following is the syntax to include
JSTL Core library in your JSP:

<%@ taglib prefix="c"


uri="http://java.sun.com /jsp/jstl/core" %>

► There are following Core JSTL Tags:


1) Core Tags:
1) Core Tags:
Java Server Pages Standard Tag Library(JSTL)
2) Formatting tags:

► The JSTL formatting tags are used to format and display text, the date, the time, and numbers
for internationalized Web sites. Following is the syntax to include Formatting library in your JSP:

<%@ taglib prefix="fmt"


uri="http://java.sun.com /jsp/jstl/fmt" %>
2) Formatting tags:
Java Server Pages Standard Tag Library(JSTL)
3) SQL tags:
► The JSTL SQL tag library provides tags for interacting with relational databases RDBMSs such as
Oracle, mySQL, or Microsoft SQL Server.
► Following is the syntax to include JSTL SQL library in your JSP:

<%@ taglib prefix="sql"


uri="http://java.sun.com /jsp/jstl/sql" %>
3) SQL tags:
Java Server Pages Standard Tag Library(JSTL)
4) XML tags:

► The JSTL XML tags provide a JSP-centric way of creating and manipulating XML documents.

► Following is the syntax to include JSTL XML library in your JSP.

► The JSTL XML tag library has custom tags for interacting with XML data. This includes
parsing XML, transforming XML data, and flow control based on XPath expressions.

<%@ taglib prefix="x"

uri="http://java.sun.com /jsp/jstl/xm l" %>


4) XML tags:
Java Server Pages Standard Tag Library(JSTL)
5) JSTL Functions:
► JSTL includes a number of standard functions, most of which are common string manipulation
functions.
► Following is the syntax to include JSTL Functions library in your JSP:

<%@ taglib prefix="fn"


uri="http://java.sun.com /jsp/jstl/functions" %>
5) JSTL Functions:
Example
► Write a JSTL program to parse & display text of XML file.
Parsing XML using JSTL
► The x prefix type of tag of JSTL can be used for parsing xml documents.
Let us keep the XML content in a file called data.xml. Following is the content of data.xml
<!-- Filename: data.xml -->
<persons>
<student>
<name>Mary</name>
<age>12</age>
<class>5</class>
</student>
<student>
<name>John</name>
<age>13</age>
<class>6</class>
</student>
</persons>
Example
<!-- Filename: ShowStudents.jsp --> <x:forEach
select="$parsedDocument/persons/student">
<%@taglib uri="http://java.sun.com/jsp/jstl/xml"
prefix="x"%> <tr>
<td> <x:out select="name" /> </td>
<%@taglib uri="http://java.sun.com/jsp/jstl/core"
prefix="c"%> <td> <x:out select="age" /> </td>

<HTML> <td> <x:out select="class" /> </td>


</tr>
<HEAD>
</x:forEach>
<TITLE>Display Student Information</TITLE>
</table>
</HEAD> </BODY>
<BODY> </HTML>
<c:import var="xmlDoc" url="data.xml"/>
<x:parse var="parsedDocument" xml="${xmlDoc}"/>
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Class</th> </tr>
JSP - Custom Tags
► A custom tag is a user-defined JSP language element.

► For creating any custom tag, we need to follow following steps:

1. Create the Tag handler class and perform action at the start or at the end of the tag.

2. Create the Tag Library Descriptor (TLD) file and define tags

3. Create the JSP file that uses the Custom tag defined in the TLD file
JSP - Custom Tags
1) Create the Tag handler class

► To create the Tag Handler, we are inheriting the TagSupport class and overriding its method doStartTag().

► To write data for the jsp, we need to use the JspWriter class.

► The PageContext class provides getOut() method that returns the instance of JspWriter class. TagSupport class

provides instance of pageContext bydefault.


JSP - Custom Tags
1) Create the Tag handler class

File: MyTagHandler.java

package com.example.myproject

public class MyTagHandler extends TagSupport{

public int doStartTag() throws JspException {

JspWriter out=pageContext.getOut();//returns the instance of JspWriter

try{

out.print(Calendar.getInstance().getTime());//printing date and time using JspWriter

}catch(Exception e){System.out.println(e);}

return SKIP_BODY;//will not evaluate the body content of the tag


JSP - Custom Tags
2) Create the TLD file
► Tag Library Descriptor (TLD) file contains information of tag and Tag Handler classes. It must be contained inside
the WEB-INF directory.
File: mytags.tld
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-
//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/j2ee/dtd/webjsptaglibrary_1_2.dtd"

<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>simple</short-name>
<uri>http://tomcat.apache.org/example-taglib</uri>
<tag>
<name>today</name>
<tag-class>com.example.myproject .MyTagHandler</tag-class>
</tag>
</taglib>
JSP - Custom Tags
3) Create the JSP file

► Use the tag in our jsp file. Here, we are specifying the path of tld file directly.

► But it is recommended to use the uri name instead of full path of tld file.

► It uses taglib directive to use the tags defined in the tld file.

File: index.jsp

<%@ taglib uri="WEB-INF/mytags.tld" prefix="m" %>

Current Date and Time is: <m:today/>


JSP Expression Language (EL)
► JSP Expression Language (EL) makes it possible to easily access application data stored in
JavaBeans components.
► JSP EL allows you to create expressions both (a) arithmetic and (b) logical.
► Within a JSP EL expression, you can use integers, floating point numbers, strings, the built-in
constants true and false for boolean values, and null.
Simple Syntax:
► Typically, when you specify an attribute value in a JSP tag, you simply use a string. For example:
<jsp:setProperty name="box" property="perimeter"
value="100"/>
► JSP EL allows you to specify an expression for any of these attribute values. A simple syntax for
JSP EL is as follows:
${expr}
► Here expr specifies the expression itself.
► The most common operators in JSP EL are . and [].
► These two operators allow you to access various attributes of Java Beans and built-in JSP objects.
JSP Expression Language (EL)
► For example above syntax <jsp:setProperty> tag can be written with an expression like:

<jsp:setProperty name="box" property="perimeter" value="${2*box.width+2*box.height}"/>

► When the JSP compiler sees the ${} form in an attribute, it generates code to evaluate the
expression and substitues the value of expresson.
► You can include a JSP EL expression in the body of a <jsp:text> tag (or any other tag) with the same
${} syntax you use for attributes. For example:
<jsp:text>
Box Perimeter is: ${2*box.width + 2*box.height}
</jsp:text>
► EL expressions can use parentheses to group subexpressions. For example, ${(1 + 2) * 3} equals 9, but
${1 + (2 * 3)} equals 7.
JSP Expression Language (EL)
► To deactivate the evaluation of EL expressions, we specify the isELIgnored attribute of
the page directive as below:

<%@ page isELIgnored ="true|false" %>

► The valid values of this attribute are true and false.

► If it is true, EL expressions are ignored when they appear in static text or tag
attributes.

► If it is false, EL expressions are evaluated by the container.


JSP Expression Language (EL)
Basic Operators in EL:
• JSP Expression Language (EL) supports most of the arithmetic and logical operators supported by Java. Below is the
list of most frequently used operators:
JSP Expression Language (EL)
JSP EL Implicit Objects:
► The JSP expression language supports the following implicit objects:
JSP Expression Language (EL)
Ex-1 : Simple example of Expression Language that Ex-2 : Example of Expression Language that prints the
prints the name of the user value set in the session scope

index.jsp index.jsp
<h3>welcome to index page</h3>
<form action="process.jsp"> <%
Enter Name:<input type="text" name="name" /> session.setAttribute("user","sonoo");
%>
<input type="submit" value="go"/>
<a href="process.jsp">visit</a>
</form>

process.jsp
process.jsp Value is ${ sessionScope.user }
Welcome, ${ param.name }
JSP Expression Language (EL)
Ex-3 : Expression language evaluates the expressions
index.jsp
<html>
<head>
<title>Expression language example1</title>
</head>
<body>
${1<2}
${1+2+3}
</body>
</html>
JSP Expression Language (EL)
Ex-4 : Getting values from application object.
display.jsp
index.jsp
<html>
<html>
<head>
<head>
<title>Display Page</title>
<title>EL example3</title>
</head>
</head>
<body>
<body> ${applicationScope.author}<br>
<% application.setAttribute("author", "Chaitanya"); ${applicationScope.Site}

application.setAttribute("Site", "BeginnesBook.com"); %> </body>

<a href="display.jsp">Click</a> </html>

</body>
</html>
JSP - Database Access
<sql:query dataSource="${snapshot}" var="result">
SELECT Operation:
SELECT * from Employees;
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
</sql:query>
<%@ page import="javax.servlet.http.*,javax.servlet.*"
%>
<table border="1" width="100%">
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" <tr>
prefix="c"%>
<th>Emp ID</th>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql"
<th>First Name</th>
prefix="sql"%>
<th>Last Name</th>
<html>
</tr>
<head> <c:forEach var="row" items="${result.rows}">
<title>SELECT Operation</title> <tr>
</head> <td><c:out value="${row.id}"/></td>
<body> <td><c:out value="${row.first}"/></td>
<td><c:out value="${row.last}"/></td>
<sql:setDataSource var="snapshot"
driver="com.mysql.jdbc.Driver" </tr>
url="jdbc:mysql://localhost/TEST" </c:forEach>
</table>
user="root" password="pass123"/>
</body></html>
JSP - Database Access
insert Operation:
<%@ page import="java.io.*,java.util.*,java.sql.*"%> <sql:query dataSource="${snapshot}" var="result">
SELECT * from Employees;
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
</sql:query>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<table border="1" width="100%">
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%> <tr>
<html> <th>Emp ID</th>
<head> <th>First Name</th>
</head> <th>Last Name</th>
</tr>
<body>
<c:forEach var="row" items="${result.rows}">
<sql:setDataSource var="snapshot“ driver="com.mysql.jdbc.Driver"
<tr>
url="jdbc:mysql://localhost/TEST"
<td><c:out value="${row.id}"/></td>
user="root" password="pass123"/> <td><c:out value="${row.first}"/></td>
<sql:update dataSource="${snapshot}" var="result"> <td><c:out value="${row.last}"/></td>
INSERT INTO Employees VALUES (104, 2, 'Nuha', 'Ali'); </tr>
</sql:update> </c:forEach>
</table>
JSP - Database Access
Delete Operation
<html> <sql:query dataSource="${snapshot}" var="result">
SELECT * from Employees;
<head>
</sql:query>
<title>DELETE Operation</title>
<table border="1" width="100%">
</head> <tr>
<body> <th>Emp ID</th>
<sql:setDataSource var="snapshot" <th>First Name</th>
driver="com.mysql.jdbc.Driver" <th>Last Name</th>
url="jdbc:mysql://localhost/TEST" </tr>
user="root" password="pass123"/> <c:forEach var="row" items="${result.rows}">
<tr>
<c:set var="empId" value="103"/>
<td><c:out value="${row.id}"/></td>
<td><c:out value="${row.first}"/></td>
<sql:update dataSource="${snapshot}" var="count">
<td><c:out value="${row.last}"/></td>
DELETE FROM Employees WHERE Id = ? </tr>
<sql:param value="${empId}" /> </c:forEach>
</sql:update> </table>
JSP - Exception Handling
When you are writing JSP code, a programmer may leave a coding errors which can occur
at any part of the code. You can have following type of errors in your JSP code:

► Checked exceptions: A checked exception is an exception that is typically a user


error or a problem that cannot be foreseen by the programmer. For example, if a file
is to be opened, but the file cannot be found, an exception occurs. These exceptions
cannot simply be ignored at the time of compilation.

► Runtime exceptions: A runtime exception is an exception that occurs that probably


could have been avoided by the programmer. As opposed to checked exceptions,
runtime exceptions are ignored at the time of compilation.

► Errors: These are not exceptions at all, but problems that arise beyond the control of
the user or the programmer. Errors are typically ignored in your code because you can
rarely do anything about an error. For example, if a stack overflow occurs, an error
will arise. They are also ignored at the time of compilation.
JSP - Exception Handling
Using Exception
Object:
► The exception
object is an
instance of a
subclass of
Throwable (e.g.,
java.lang.
NullPointerExceptio
n) and is only
available in error
pages. Following is
the list of
important
medthods available
in the Throwable
class.
JSP - Exception Handling
► JSP gives you an option to specify Error Page for each JSP. Whenever the page throws an exception, the JSP
container automatically invokes the error page.
Main.jsp
<%@ page errorPage="ShowError.jsp" %> ShowError.jsp
<%@ page isErrorPage="true" %>
<html> <html>
<head> <head>
<title>Error Handling Example</title> <title>Show Error Page</title>
</head> </head>
<body> <body>
<% <h1>Opps...</h1>
// Throw an exception to invoke the error <p>Sorry, an error occurred.</p>
page <p>Here is the exception stack trace: </p>
int x = 1; <pre>
if (x == 1) <%
{ exception.printStackTrace(response.getWriter());
throw new RuntimeException("Error %>
condition!!!"); </pre>
} </body>
%> </html>
</body>
</html>
JSP - Exception Handling
Output
java.lang.RuntimeException: Error condition!!!
......

Opps...
Sorry, an error occurred.

Here is the exception stack trace:


JSP - Exception Handling
Using JSTL tags for Error Page:
<td><b>URI:</b></td>
<%@ taglib prefix="c" <td>${pageContext.errorData.requestURI}</td>
uri="http://java.sun.com/jsp/jstl/core" %>
<tr valign="top">
<%@page isErrorPage="true" %> <td><b>Status code:</b></td>
<html> <td>${pageContext.errorData.statusCode}</td>
<head> </tr>
<title>Show Error Page</title> <tr valign="top">
<td><b>Stack trace:</b></td>
</head>
<td>
<body>
<c:forEach var="trace"
<h1>Opps...</h1> items="${pageContext.exception.stackTrace}">
<table width="100%" border="1"> <p>${trace}</p>
<tr valign="top"> </c:forEach>
<td width="40%"><b>Error:</b></td> </td>

<td>${pageContext.exception}</td> </tr>
</table>
</tr>
</body>
<tr valign="top"></tr>
</html>
JSP - Exception Handling
OUTPUT:
Error: java.lang.RuntimeException: Error condition!!!

URI: /main.jsp
Status code: 500
Stack trace: org.apache.jsp.main_jsp._jspService(main_jsp.java:65)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase
.java:68)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:
265)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
...................
JSP - Exception Handling
Using Try...Catch Block:
If you want to handle errors with in the same page and want to take
some action instead of firing an error page, you can make use of
try....catch block.
main.jsp
<html>
<body>
<% try{
int i = 1; OUTPUT: An exception occurred: / by zero
i = i / 0;
out.println("The answer is " + i);
}
catch (Exception e){
out.println("An exception occurred: " + e.getMessage());
}
%>
</body> </html>
Advanced java Programming
GTU #3160707

Unit-5
Java Server Faces
Subject Overview
Sr. No. Unit % Weightage
1 Java Networking 5
2 JDBC Programming 10
3 Servlet API and Overview 25
4 Java Server Pages 25
5 Java Server Faces 10
6 Hibernate 15
7 Java Web Frameworks: Spring MVC 10

# 3160707  Unit 5 – Java Server Faces 2


What is JSF?
 Java Server Faces (JSF) is a MVC web framework.
 JSF simplifies the construction of user interfaces (UI) for server-based applications by using
reusable UI components in the page.
 The JSF specification defines a set of standard UI components and provides an (API) for
developing components.
 JSF enables the reuse and extension of the existing standard UI components.

# 3160707  Unit 5 – Java Server Faces 3


Advantages of JSF
 Providing reusable UI components
 Making easy data transfer between UI components
 Managing UI state across multiple server requests
 Enabling implementation of custom components
 Wiring client side event to server side application code
 Good separation of the logic and presentation

# 3160707  Unit 5 – Java Server Faces 4


What is MVC Design Pattern?
 MVC design pattern designs an application using three separate modules:
Model Model Carries Data and login
View Shows User Interface
Controller Handles processing of an application.

UI Logic Business Logic

View Model

Controller
Request & Relay data

# 3160707  Unit 5 – Java Server Faces 5


JSF Request Processing Life Cycle
 JSF application lifecycle consist of six phases which are as follows:
 Phase-I: Restore View (RV)
 Phase-II: Apply Request Values (ARV)
 Phase-III: Process Validations (PV)
 Phase-IV: Update Model Values (UMV)
 Phase-V: Invoke Application (IA)
 Phase-IV: Render Response (RR)

# 3160707  Unit 5 – Java Server Faces 6


JSF request processing Life cycle

Request
Create or Apply Request Process
Restore View Values Validations

Response
Render Invoke Update Model
Response Application Values

# 3160707  Unit 5 – Java Server Faces 7


JSF request processing Life cycle
Phase 1: Restore view
 JSF begins the restore view phase as soon as a link or a button is clicked and JSF receives a
request.
 During this phase, the JSF builds the view, wires event handlers and validators to UI components
and saves the view in the FacesContext instance.
 The FacesContext instance will now contains all the information required to process a request.

# 3160707  Unit 5 – Java Server Faces 8


JSF request processing Life cycle

Request
Create or Apply Request Process
Restore View Values Validations

Response
Render Invoke Update Model
Response Application Values

# 3160707  Unit 5 – Java Server Faces 9


JSF request processing Life cycle
Phase 2: Apply request values
 In this phase, the values that are entered by the user will be updated on each and every individual
component defined in the View graph.
 Component stores this value.
 If any of the Conversions or the Validations fail, then the current processing is terminated and
the control directly goes to the Render Response for rendering the conversion or the validation
errors to the Client.

# 3160707  Unit 5 – Java Server Faces 10


JSF request processing Life cycle

Request
Create or Apply Request Process
Restore View Values Validations

Response
Render Invoke Update Model
Response Application Values

# 3160707  Unit 5 – Java Server Faces 11


JSF request processing Life cycle
Phase 3: Process validation
 This Phase will process any Validations that are configured for UI Components.
 These validations will only happen for the UI Components only if the property 'rendered' property
is set to 'true'.

# 3160707  Unit 5 – Java Server Faces 12


JSF request processing Life cycle

Request
Create or Apply Request Process
Restore View Values Validations

Response
Render Invoke Update Model
Response Application Values

# 3160707  Unit 5 – Java Server Faces 13


JSF request processing Life cycle
Phase 4: Update model values
 After the JSF checks that the data is valid, it walks over the component tree and set the
corresponding server-side object properties to the component’s local values.
 The JSF will update the bean properties corresponding to input component's value attribute.

# 3160707  Unit 5 – Java Server Faces 14


JSF request processing Life cycle

Request
Create or Apply Request Process
Restore View Values Validations

Response
Render Invoke Update Model
Response Application Values

# 3160707  Unit 5 – Java Server Faces 15


JSF request processing Life cycle
Phase 5: Invoke application
 During this phase, the JSF handles any application-level events, such as submitting a form /
linking to another page.
 In this phase, JSF Implementation will call the UIComponentBase.processApplications() method
which will immediately call the Render Response Phase.

# 3160707  Unit 5 – Java Server Faces 16


JSF request processing Life cycle

Request
Create or Apply Request Process
Restore View Values Validations

Response
Render Invoke Update Model
Response Application Values

# 3160707  Unit 5 – Java Server Faces 17


JSF request processing Life cycle
Phase 6: Render response
 And finally, we have reached the Render Response whose job is to render the response back the
Client Application.

# 3160707  Unit 5 – Java Server Faces 18


JSF request processing Life cycle
Recover the component tree
Restore View

Adds new parameter to recovered component


Apply Request Values
tree

Process Validation Validates the parameter

update the bean properties corresponding to


Update Model Values input component's value attribute

Instances MB(Managed Bean), adds value of


Invoke Application component to properties of MB, Method of MB
is executed.

Render Response Add value of the attribute to Component tree,


Generates HTML code.

# 3160707  Unit 5 – Java Server Faces 19


JSF Program
 Java Server Faces technology provides an easy and user-friendly process for creating web
applications.
 Developing a simple JavaServer Faces application typically requires the following tasks:
 Developing managed beans (.java file)
 Creating web pages using component tags (.xhtml file)
 Mapping the javax.faces.webapp.FacesServlet instance (web.xml)

# 3160707  Unit 5 – Java Server Faces 20


JSF Program
Hello.java
1 package hello;
2 import javax.faces.bean.ManagedBean;
3 @ManagedBean
4 public class Hello {
5 String world = "Hello World!";
6 public String getworld()
7 {
8 return world;
9 }
10 }

# 3160707  Unit 5 – Java Server Faces 21


JSF Program : index.xhtml
 Creating the Web Page
 In a typical Facelets application, web pages are created in XHTML.
index.xhtml
1 <?xml version='1.0' encoding='UTF-8' ?>
2 <html xmlns="http://www.w3.org/1999/xhtml"
3 xmlns:h="http://xmlns.jcp.org/jsf/html">
4 <head>
5 <title>Facelet Title</title>
6 </head>
7 <h:body>
8 #{hello.world}
9 </h:body>
10 </html>

# 3160707  Unit 5 – Java Server Faces 22


JSF Program:web.xml
Web.xml
1 <web-app>
2 <context-param>
3 <param-name>javax.faces.PROJECT_STAGE</param-name>
4 <param-value>Development</param-value>
5 </context-param>
6 <servlet>
7 <servlet-name>Faces Servlet</servlet-name>
8 <servlet-class>
9 javax.faces.webapp.FacesServlet
10 </servlet-class>
11 <load-on-startup>1</load-on-startup>
12 </servlet>
13 <servlet-mapping>
14 <servlet-name>Faces Servlet</servlet-name>
15 <url-pattern>/faces/*</url-pattern>
16 </servlet-mapping>
17 <welcome-file-list>
18 <welcome-file>faces/index.xhtml</welcome-file>
19 </welcome-file-list>
20 </web-app>

# 3160707  Unit 5 – Java Server Faces 23


JSF Tag Libraries
 JSF framework provides a standard HTML tag library.
 Each tag will rendered into corresponding html output.
 To use these html tags we have to use the following namespaces of URI in html node.
Syntax
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">

 Two types of JSF Tag library


Syntax

<%@taglib uri=" http://java.sun.com/jsf/core" prefix=" f" %>


<%@taglib uri=" http://java.sun.com/jsf/html" prefix=" h" %>

# 3160707  Unit 5 – Java Server Faces 24


JSF Basic Tags
JSF Basic Tag HTML Tag
h:inputText HTML input of type="text"
h:inputSecret HTML input of type="password",
h:inputHidden HTML input of type="hidden".
h:selectMany A group of HTML check boxes
Checkbox
h:selectOne Listbox Single HTML list box.
h:outputText HTML text.
h:commandButton HTML input of type="submit" button.
h:Link HTML anchor.
h:outputLabel HTML Label

# 3160707  Unit 5 – Java Server Faces 25


JSF Basic Tags
JSF Basic Tag HTML Tag
f:param Parameters for JSF UI Component.
f:attribute Attribute for a JSF UI Component.
f:setProperty Sets value of a managed bean's property
ActionListener

# 3160707  Unit 5 – Java Server Faces 26


JSF Program: Basic Tag
index.xhtml
1 <html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
2 <h:body>
3 <h:form>
4 <h3>JSF Login Logout</h3>
5 <h:outputText value="Username:" />
6 <h:inputText id="username" value=""></h:inputText>
7 <h:outputText value="Password:" />
8 <h:inputSecret id="password" value="" />
9 <h:commandButton action="/index.xhtml”
value="Login"></h:commandButton>
10 <h:selectManyCheckbox value="">
11 <f:selectItem itemValue="1" itemLabel="Diet J2SE" />
12 <f:selectItem itemValue="2" itemLabel="Diet J2EE" />
13 </h:selectManyCheckbox>
14 <h:selectOneRadio value="">
15 <f:selectItem itemValue="1" itemLabel="Sem 4" />
16 <f:selectItem itemValue="2" itemLabel="Sem 6" />
17 </h:selectOneRadio>

# 3160707  Unit 5 – Java Server Faces 27


JSF Program: Basic Tag
index.xhtml
18 <h:selectOneListbox value="">
19 <f:selectItem itemValue="1" itemLabel="List1" />
20 <f:selectItem itemValue="2" itemLabel="List2" />
21 <f:selectItem itemValue="2" itemLabel="List3" />
22 <f:selectItem itemValue="2" itemLabel="List4" />
23 </h:selectOneListbox>
24
25 <h:graphicImage value=
"http://www.darshan.ac.in/Upload/DIET/Brochure/2016/DIET_Placement_Brochure_CE_2016.j
pg"/>
26 </h:form>
27 </h:body>
28 </html>

# 3160707  Unit 5 – Java Server Faces 28


JSF Facelet Tags
 A viewhandler purely created for JSF
 No more JSP
 .xhtml instead of .jsp
 No tld files and no tag classes to defined a UIComponent.
 Faster than using JSP.

# 3160707  Unit 5 – Java Server Faces 29


JSF Facelet Tags
 JSF provides special tags to create common layout for a web application tags.
 These tags gives flexibility to manage common parts of a multiple pages at one place.

ui:insert Inserts content into a template. That content is define with


the ui:define tag
ui:define The define tag defines content that is inserted into a page by a
template.
ui:composition The <ui:composition> tag provides a template encapsulating the
content to be included in the other facelet.
ui:include This tag includes the component in the src attribute as a part of the
current JSF page.

# 3160707  Unit 5 – Java Server Faces 30


JSF Convertor Tags
 JSF has convertors to convert its UI component's data to object used in a managed bean and
vice versa.
 For example, we can convert a text into date object and can validate the format of input as well.

f:convertNumber Converts a String into a Number of desired format


f:convertDateTime Converts a String into a Date of desired format
Custom Convertor Creating a custom convertor

# 3160707  Unit 5 – Java Server Faces 31


JSF Validator Tags
 JSF has built in validators to validate its UI components.
f:validateLength Validates length of a string
f:validateLongRange Validates range of numeric value
f:validateDoubleRange Validates range of float value
f:validateRegex Validate JSF component with a given regular expression.
Custom Validator Creating a custom validator

# 3160707  Unit 5 – Java Server Faces 32


JSF Expression Language
 JSF provides a rich expression language.
 Notation:
#{operation-expression}
Example
#{i=10} <!-- output: 10-->
#{10 > 9} <!-- output: true-->
#{userCar.add} <!– calls add() of UserCar bean -->

# 3160707  Unit 5 – Java Server Faces 33


JSF Program: LoginBean.java
LoginBean.java
1 import javax.faces.bean.ManagedBean;
2 @ManagedBean
3 public class LoginBean {
4 String username;
5 String password;
6 public String getUsername() {return username;}
7 public void setUsername(String username) {this.username = username;}
8 public String getPassword() {return password;}
9 public void setPassword(String password) {this.password = password;}
10
11 public String login()
12 {
13 if(username.equals("java") && password.equals("jsf"))
14 {return "success";}
15 else{return "failure”;}
16 }
17 }

# 3160707  Unit 5 – Java Server Faces 34


JSF Program: index.xhtml
Index.xhtml
1 <html xmlns="http://www.w3.org/1999/xhtml"
2 xmlns:c="http://java.sun.com/jsf/core"
3 xmlns:ui="http://java.sun.com/jsf/facelets"
4 xmlns:h="http://java.sun.com/jsf/html">
5 <h:body>
6 <h:form id="loginForm">
7 <h:outputLabel value="username" />
8 <h:inputText value="#{loginBean.username}" />
9 <h:outputLabel value="password" />
10 <h:inputSecret value="#{loginBean.password}"></h:inputSecret>
11 <h:commandButton value="Login” action="#{loginBean.login}"></h:commandButton>
12 </h:form>
13 </h:body></html>

# 3160707  Unit 5 – Java Server Faces 35


JSF Event Handling
 When a user clicks a JSF button or link or changes any value in text field, JSF UI component fires
event which will be handled by the application code.
 To handle such event, event handler are to be registered in the application code or managed
bean.
 When a UI component checks that a user event has happened, it creates an instance of the
corresponding event class and adds it to an event list.
Event Handlers Description
valueChangeListener Value change events get fired when user make changes in
input components.
actionListener Action events get fired when user clicks on a button or link
component.
Application Events Events firing during JSF lifecycle:
PostConstructApplicationEvent,
PreDestroyApplicationEvent , PreRenderViewEvent.

# 3160707  Unit 5 – Java Server Faces 36


JSF Database ACCESS
 We can easily integrate JDBC with JSF for Database Access, let’s understand with an example.
 Files required for JSF DB access are as follows:
1. AuthenticationBean.java
2. index.xhtml
3. success.xhtml
4. fail.xhtml
5. Faces-config.xml [Navigational file]

# 3160707  Unit 5 – Java Server Faces 37


JSF Database ACCESS
AuthenticationBean.java AuthenticationBean.java
1 import java.sql.*; 17 public String validateFromDB()throws
Exception{
2 import javax.faces.bean.ManagedBean;
3 18 int i=0;
import javax.faces.bean.RequestScoped;
4 19 if(uname.equals("diet") &&
@ManagedBean password.equals("diet") ){
5 @RequestScoped
6 20 Class.forName("com.mysql.jdbc.Driver");
public class AuthenticationBean { Connection con=
7 21
String uname; DriverManager.getConnection
8 String password;
9 ("jdbc:mysql://localhost:3306/ajava",
public String getUname() "root", "root");
10 {return uname;}
11 22 Statement st=con.createStatement();
public String getPassword() i=st.executeUpdate("insert into cxcy
12 23
{return password;} values(2011,'dfg','r1')");
13 public void setUname
24 }
(String uname)
14 {this.uname = uname;} 25 if(i!=0)
15 public void setPassword 26 {return "success";}
27 else {return "failure";}
(String password)
16 {this.password = password;} 28 }}

# 3160707  Unit 5 – Java Server Faces 38


JSF Database ACCESS
Index.xhtml
1 <?xml version='1.0' encoding='UTF-8' ?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4 <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html">
5 <h:body><h:form><center>
6 Enter Name :<h:inputText id="name" value="#{authenticationBean.uname}" ></h:inputText>
7 Enter Password <h:inputSecret id="pwd” value="#{authenticationBean.password}"/>
8 <h:commandButton value="Submit"action="#{authenticationBean.validateFromDB}"/>
9 </center></h:form></h:body></html>

success.xhtml
1 <?xml version='1.0' encoding='UTF-8' ?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4 <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html">
5 <h:head><title>Welcome</title></h:head><h:body>
6 Welcome Home: query executed
7 </h:body></html>

# 3160707  Unit 5 – Java Server Faces 39


JSF Database ACCESS
fail.xhtml
1 <?xml version='1.0' encoding='UTF-8' ?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4 <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html">
5 <h:head><title> login failed </title></h:head><h:body>
6 Login Failed
7 </h:body></html>

# 3160707  Unit 5 – Java Server Faces 40


JSF Database ACCESS
Faces-config.xml
1 <?xml version='1.0' encoding='UTF-8'?>
2 <faces-config version="2.1"
3 xmlns="http://java.sun.com/xml/ns/javaee"
4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
6 http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd">
7 <navigation-rule>
8 <from-view-id>/index.xhtml</from-view-id>
9 <navigation-case>
10 <from-action> #{authenticationBean.validateFromDB}</from-action>
11 <from-outcome>success</from-outcome>
12 <to-view-id>/success.xhtml</to-view-id>
13 </navigation-case>
14 <navigation-case>
15 <from-action> #{authenticationBean.validateFromDB}</from-action>
16 <from-outcome>failure</from-outcome>
17 <to-view-id>/fail.xhtml</to-view-id>
18 </navigation-case>
19 </navigation-rule>
20 </faces-config>

# 3160707  Unit 5 – Java Server Faces 41


JSF Database ACCESS:output

# 3160707  Unit 5 – Java Server Faces 42


JSF Libraries: PrimeFaces
 PrimeFaces is a lightweight library with one jar, zero-configuration and no required dependencies
 To use JSF prime faces library we need to use following code:

Syntax
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:p="http://primefaces.org/ui ">

# 3160707  Unit 5 – Java Server Faces 43


Introduction to PrimeFaces
 Simplicity and Performance
 PrimeFaces is a lightweight library, all decisions made are based on keeping PrimeFaces as lightweight as
possible.
 Usually adding a third-party solution could bring a overhead however this is not the case with PrimeFaces.
 It is just one single jar with no dependencies and nothing to configure.
 Ease of Use
 Components in PrimeFaces are developed with a design principle which states that "A good UI component
should hide complexity but keep the flexibility"
 Strong Community Feedback
 PrimeFaces community continuously helps the development of PrimeFaces by providing feedback, new ideas,
bug reports and patches.

# 3160707  Unit 5 – Java Server Faces 44


PrimeFaces Tags
 JSF prime faces provides following collection of tags:
 <p:inputText>
 <p:inputSecret>
 <p:commandButton>
 <p:commandLink>
 <p:ajax>
 <p:barChart>
 <p:calendar>
 <p:colorPicker>
 <p:dialog>
 <p:fileUpload>
 <p:fileDownload>

# 3160707  Unit 5 – Java Server Faces 45


GTU Questions
 Draw the JSF request processing life cycle and briefly give the function of each phase.
 Write a short note on JSF Facelets.
 List the JSF validation tags and explain any two.

# 3160707  Unit 5 – Java Server Faces 46


Spring Framework
Introduction
• Spring is the most popular application development framework for enterprise
Java. Millions of developers around the world use Spring Framework to create
high performing, easily testable, reusable code.
• Spring framework is an open source Java platform and it was initially written by
Rod Johnson and was first released under the Apache 2.0 license in June 2003.
• Spring is lightweight when it comes to size and transparency. The basic version of
spring framework is around 2MB.
• The core features of the Spring Framework can be used in developing any Java
application, but there are extensions for building web applications on top of the
Java EE platform. Spring framework targets to make J2EE development easier
to use and promote good programming practice by enabling a POJO-based
programming model.
Advantages
• Spring enables developers to develop enterprise-class applications using POJOs. The benefit of using only POJOs is
that you do not need an EJB container product such as an application server but you have the option of using
only a robust servlet container such as Tomcat or some commercial product.

• Spring is organized in a modular fashion. Even though the number of packages and classes are substantial, you
have to worry only about ones you need and ignore the rest.

• Spring does not reinvent the wheel instead, it truly makes use of some of the existing technologies like several
ORM frameworks, logging frameworks, JEE, Quartz and JDK timers, other view technologies.

• Testing an application written with Spring is simple because environment-dependent code is moved into this
framework. Furthermore, by using JavaBean-style POJOs, it becomes easier to use dependency injection for
injecting test data.

• Spring's web framework is a well-designed web MVC framework, which provides a great alternative to web
frameworks such as Struts or other over engineered or less popular web frameworks.

• Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or
JDO, for example) into consistent, unchecked exceptions.

• Lightweight IoC containers tend to be lightweight, especially when compared to EJB containers, for example. This
is beneficial for developing and deploying applications on computers with limited memory and CPU resources.

• Spring provides a consistent transaction management interface that can scale down to a local transaction (using
a single database, for example) and scale up to global transactions (using JTA, for example).
Dependency Injection (DI)
• The technology that Spring is most identified with is the Dependency Injection (DI)
flavor of Inversion of Control. The Inversion of Control (IoC) is a general concept, and it
can be expressed in many different ways and Dependency Injection is merely one
concrete example of Inversion of Control.
• When writing a complex Java application, application classes should be as independent
as possible of other Java classes to increase the possibility to reuse these classes and to
test them independently of other classes while doing unit testing. Dependency Injection
helps in gluing these classes together and same time keeping them independent.
• What is dependency injection exactly? Let's look at these two words separately. Here
the dependency part translates into an association between two classes. For example,
class A is dependent on class B. Now, let's look at the second part, injection. All this
means is that class B will get injected into class A by the IoC.
• Dependency injection can happen in the way of passing parameters to the constructor
or by post-construction using setter methods. As Dependency Injection is the heart of
Spring Framework, so I will explain this concept in a separate chapter with a nice
example.
Aspect Oriented Programming (AOP):
• One of the key components of Spring is the Aspect oriented programming (AOP)
framework. The functions that span multiple points of an application are called
cross-cutting concerns and these cross-cutting concerns are conceptually separate
from the application's business logic. There are various common good examples of
aspects including logging, declarative transactions, security, and caching etc.
• The key unit of modularity in OOP is the class, whereas in AOP the unit of
modularity is the aspect. Whereas DI helps you decouple your application objects
from each other, AOP helps you decouple cross-cutting concerns from the objects
that they affect.
• The AOP module of Spring Framework provides aspect-oriented programming
implementation allowing you to define method-interceptors and pointcuts to
cleanly decouple code that implements functionality that should be separated.
Spring Framework - Architecture
Core Container:
• The Core Container consists of the Core, Beans, Context, and Expression Language
modules whose detail is as follows:
• The Core module provides the fundamental parts of the framework, including the
IoC and Dependency Injection features.
• The Bean module provides BeanFactory which is a sophisticated implementation
of the factory pattern.
• The Context module builds on the solid base provided by the Core and Beans
modules and it is a medium to access any objects defined and configured. The
ApplicationContext interface is the focal point of the Context module.
• The SpEL module provides a powerful expression language for querying and
manipulating an object graph at runtime.
Data Access/Integration:
• The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and
Transaction modules whose detail is as follows:
• The JDBC module provides a JDBC-abstraction layer that removes the need to do
tedious JDBC related coding.
• The ORM module provides integration layers for popular object-relational
mapping APIs, including JPA, JDO, Hibernate, and iBatis.
• The OXM module provides an abstraction layer that supports Object/XML
mapping implementations for JAXB, Castor, XMLBeans, JiBX and XStream.
• The Java Messaging Service JMS module contains features for producing and
consuming messages.
• The Transaction module supports programmatic and declarative transaction
management for classes that implement special interfaces and for all your POJOs.
Web:
• The Web layer consists of the Web, Web-MVC, Web-Socket, and Web-Portlet
modules whose detail is as follows:
• The Web module provides basic web-oriented integration features such as
multipart file-upload functionality and the initialization of the IoC container using
servlet listeners and a web-oriented application context.
• The Web-MVC module contains Spring's model-view-controller (MVC)
implementation for web applications.
• The Web-Socket module provides support for WebSocket-based, two-way
communication between client and server in web applications.
• The Web-Portlet module provides the MVC implementation to be used in a
portlet environment and mirrors the functionality of Web-Servlet module.
Miscellaneous:
• There are few other important modules like AOP, Aspects, Instrumentation, Web and
Test modules whose detail is as follows:
• The AOP module provides aspect-oriented programming implementation allowing you
to define method-interceptors and pointcuts to cleanly decouple code that implements
functionality that should be separated.
• The Aspects module provides integration with AspectJ which is again a powerful and
mature aspect oriented programming (AOP) framework.
• The Instrumentation module provides class instrumentation support and class loader
implementations to be used in certain application servers.
• The Messaging module provides support for STOMP as the WebSocket sub-protocol to
use in applications. It also supports an annotation programming model for routing and
processing STOMP messages from WebSocket clients.
• The Test module supports the testing of Spring components with JUnit or TestNG
frameworks.
Spring - MVC Framework
• The Spring web MVC framework provides model-view-controller architecture and
ready components that can be used to develop flexible and loosely coupled web
applications. The MVC pattern results in separating the different aspects of the
application (input logic, business logic, and UI logic), while providing a loose
coupling between these elements.
• The Model encapsulates the application data and in general they will consist of
POJO.
• The View is responsible for rendering the model data and in general it generates
HTML output that the client's browser can interpret.
• The Controller is responsible for processing user requests and building appropriate
model and passes it to the view for rendering.
Spring - MVC Framework
Spring - MVC Framework
• After receiving an HTTP request, DispatcherServlet consults the HandlerMapping
to call the appropriate Controller.
• The Controller takes the request and calls the appropriate service methods based
on used GET or POST method. The service method will set model data based on
defined business logic and returns view name to the DispatcherServlet.
• The DispatcherServlet will take help from ViewResolver to pickup the defined view
for the request.
• Once view is finalized, The DispatcherServlet passes the model data to the view
which is finally rendered on the browser.
Spring - Bean Life Cycle
• The life cycle of a Spring bean is easy to understand. When a bean is instantiated,
it may be required to perform some initialization to get it into a usable state.
Similarly, when the bean is no longer required and is removed from the
container, some cleanup may be required.
• Though, there is lists of the activities that take place behind the scenes between
the time of bean Instantiation and its destruction, but this chapter will discuss
only two important bean lifecycle callback methods which are required at the
time of bean initialization and its destruction.
• To define setup and teardown for a bean, we simply declare the <bean> with init-
method and/or destroy-method parameters. The init-method attribute specifies a
method that is to be called on the bean immediately upon instantiation. Similarly,
destroy-method specifies a method that is called just before a bean is removed
from the container.
Initialization callbacks:
• The org.springframework.beans.factory.InitializingBean interface specifies a single method:

void afterPropertiesSet() throws Exception;

• So you can simply implement above interface and initialization work can be done inside
afterPropertiesSet() method as follows:
public class ExampleBean implements InitializingBean {
public void afterPropertiesSet() {
// do some initialization work
}
}
• In the case of XML-based configuration metadata, you can use the init-method attribute to
specify the name of the method that has a void no-argument signature. For example:
<bean id="exampleBean" class="examples.ExampleBean" init-method="init"/>
• Following is the class definition:
public class ExampleBean {
public void init() {
// do some initialization work
}
}
Destruction callbacks
• The org.springframework.beans.factory.DisposableBean interface specifies a single method:
void destroy() throws Exception;
• So you can simply implement above interface and finalization work can be done inside destroy() method as
follows:
public class ExampleBean implements DisposableBean {
public void destroy() {
// do some destruction work
}
}
• In the case of XML-based configuration metadata, you can use the destroy-method attribute to specify the name
of the method that has a void no-argument signature. For example:
<bean id="exampleBean" class="examples.ExampleBean" destroy-method="destroy"/>
• Following is the class definition:
public class ExampleBean {
public void destroy() {
// do some destruction work
}
}
• If you are using Spring's IoC container in a non-web application environment; for example, in a rich client
desktop environment; you register a shutdown hook with the JVM. Doing so ensures a graceful shutdown and
calls the relevant destroy methods on your singleton beans so that all resources are released.
•It is recommended that you do not use the InitializingBean or DisposableBean callbacks, because XML configuration
gives much flexibility in terms of naming your method.
XML Configuration on Spring
•<?xml version="1.0" encoding="UTF-8"?>
•<beans xmlns="http://www.springframework.org/schema/beans"
• xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
• xsi:schemaLocation="http://www.springframework.org/schema/beans
• http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
• <!-- A simple bean definition -->
• <bean id="..." class="...">
• <!-- collaborators and configuration for this bean go here -->
• </bean>
• <!-- A bean definition with lazy init set on -->
• <bean id="..." class="..." lazy-init="true">
• <!-- collaborators and configuration for this bean go here -->
• </bean>
• <!-- A bean definition with initialization method -->
• <bean id="..." class="..." init-method="...">
• <!-- collaborators and configuration for this bean go here -->
• </bean>
• <!-- A bean definition with destruction method -->
• <bean id="..." class="..." destroy-method="...">
• <!-- collaborators and configuration for this bean go here -->
• </bean>
• <!-- more bean definitions go here -->
•</beans>
Properties
Properties Description
This attribute is mandatory and specify the bean class to be used to create
class
the bean.
This attribute specifies the bean identifier uniquely. In XML-based
name configuration metadata, you use the id and/or name attributes to specify
the bean identifier(s).
This attribute specifies the scope of the objects created from a particular
scope
bean definition and it will be discussed in bean scopes chapter.
This is used to inject the dependencies and will be discussed in next
constructor-arg
chapters.
This is used to inject the dependencies and will be discussed in next
properties
chapters.
This is used to inject the dependencies and will be discussed in next
autowiring mode
chapters.
A lazy-initialized bean tells the IoC container to create a bean instance
lazy-initialization mode
when it is first requested, rather than at startup.
A callback to be called just after all necessary properties on the bean have
initialization method
been set by the container. It will be discussed in bean life cycle chapter.
A callback to be used when the container containing the bean is destroyed.
destruction method
It will be discussed in bean life cycle chapter.
Scope:

Scope Description
This scopes the bean definition to a single instance per Spring IoC
singleton
container (default).
This scopes a single bean definition to have any number of object
prototype
instances.
This scopes a bean definition to an HTTP request. Only valid in the
request
context of a web-aware Spring ApplicationContext.
This scopes a bean definition to an HTTP session. Only valid in the
session
context of a web-aware Spring ApplicationContext.
global- This scopes a bean definition to a global HTTP session. Only valid in the
session context of a web-aware Spring ApplicationContext.
Event Handling in Spring
• You have seen in all the chapters that core of Spring is the ApplicationContext,
which manages complete life cycle of the beans. The ApplicationContext publishes
certain types of events when loading the beans. For example, a
ContextStartedEvent is published when the context is started and
ContextStoppedEvent is published when the context is stopped.
• Event handling in the ApplicationContext is provided through the
ApplicationEvent class and ApplicationListener interface. So if a bean implements
the ApplicationListener, then every time an ApplicationEvent gets published to
the ApplicationContext, that bean is notified.
Event
S.N. Spring Built-in Events & Description
ContextRefreshedEvent
1 This event is published when the ApplicationContext is either initialized or refreshed. This can also be
raised using the refresh() method on the ConfigurableApplicationContext interface.
ContextStartedEvent
This event is published when the ApplicationContext is started using the start() method on the
2
ConfigurableApplicationContext interface. You can poll your database or you can re/start any stopped
application after receiving this event.
ContextStoppedEvent
This event is published when the ApplicationContext is stopped using the stop() method on the
3
ConfigurableApplicationContext interface. You can do required housekeep work after receiving this
event.
ContextClosedEvent
This event is published when the ApplicationContext is closed using the close() method on the
4
ConfigurableApplicationContext interface. A closed context reaches its end of life; it cannot be
refreshed or restarted.
RequestHandledEvent
5
This is a web-specific event telling all beans that an HTTP request has been serviced.
Listening to Context Events:
• To listen a context event, a bean should implement the ApplicationListener
interface which has just one method onApplicationEvent(). So let us write an
example to see how the events propagates and how you can put your code to do
required task based on certain events.
AOP with Spring Framework
• One of the key components of Spring Framework is the Aspect oriented
programming (AOP) framework. Aspect Oriented Programming entails breaking
down program logic into distinct parts called so-called concerns. The functions
that span multiple points of an application are called cross-cutting concerns and
these cross-cutting concerns are conceptually separate from the application's
business logic. There are various common good examples of aspects like logging,
auditing, declarative transactions, security, and caching etc.
• The key unit of modularity in OOP is the class, whereas in AOP the unit of
modularity is the aspect. Dependency Injection helps you decouple your
application objects from each other and AOP helps you decouple cross-cutting
concerns from the objects that they affect. AOP is like triggers in programming
languages such as Perl, .NET, Java and others.
• Spring AOP module provides interceptors to intercept an application, for
example, when a method is executed, you can add extra functionality before or
after the method execution.
AOP Terminologies:
Terms Description
A module which has a set of APIs providing cross-cutting requirements. For example, a
Aspect logging module would be called AOP aspect for logging. An application can have any
number of aspects depending on the requirement.
This represents a point in your application where you can plug-in AOP aspect. You can
Join point also say, it is the actual place in the application where an action will be taken using
Spring AOP framework.
This is the actual action to be taken either before or after the method execution. This is
Advice
actual piece of code that is invoked during program execution by Spring AOP framework.

This is a set of one or more joinpoints where an advice should be executed. You can
Pointcut
specify pointcuts using expressions or patterns as we will see in our AOP examples.

Introduction An introduction allows you to add new methods or attributes to existing classes.
The object being advised by one or more aspects, this object will always be a proxied
Target object
object. Also referred to as the advised object.
Weaving is the process of linking aspects with other application types or objects to create
Weaving
an advised object. This can be done at compile time, load time, or at runtime.
Types of Advice

Advice Description
before Run advice before the a method execution.
Run advice after the a method execution regardless of its
after
outcome.
Run advice after the a method execution only if method
after-returning
completes successfully.
Run advice after the a method execution only if method exits by
after-throwing
throwing an exception.
around Run advice before and after the advised method is invoked.
Spring - JDBC Framework
• JdbcTemplate Class
• The JdbcTemplate class executes SQL queries, update statements and stored
procedure calls, performs iteration over ResultSets and extraction of returned
parameter values. It also catches JDBC exceptions and translates them to the
generic, more informative, exception hierarchy defined in the
org.springframework.dao package.
• Instances of the JdbcTemplate class are threadsafe once configured. So you can
configure a single instance of a JdbcTemplate and then safely inject this shared
reference into multiple DAOs.
• A common practice when using the JdbcTemplate class is to configure a
DataSource in your Spring configuration file, and then dependency-inject that
shared DataSource bean into your DAO classes, and the JdbcTemplate is created
in the setter for the DataSource.
Configuring Data Source
• <bean id="dataSource"
• class="org.springframework.jdbc.datasource.DriverManagerDataSource">
• <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
• <property name="url" value="jdbc:mysql://localhost:3306/TEST"/>
• <property name="username" value="root"/>
• <property name="password" value="password"/>
• </bean>
Executing SQL statements
• Example :
String SQL = "select count(*) from Student";
int rowCount = jdbcTemplateObject.queryForInt( SQL );

• Querying and returning an object:


String SQL = "select * from Student";
List<Student> students = jdbcTemplateObject.query(SQL, new StudentMapper());
public class StudentMapper implements RowMapper<Student> {
public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
Student student = new Student();
student.setID(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
return student;
}
}
Spring - Transaction Management
• A database transaction is a sequence of actions that are treated as a single unit of work. These actions should either complete
entirely or take no effect at all. Transaction management is an important part of and RDBMS oriented enterprise
applications to ensure data integrity and consistency. The concept of transactions can be described with following four key
properties described as ACID:
• Atomicity: A transaction should be treated as a single unit of operation which means either the entire sequence of operations
is successful or unsuccessful.
• Consistency: This represents the consistency of the referential integrity of the database, unique primary keys in tables etc.
• Isolation: There may be many transactions processing with the same data set at the same time, each transaction should be
isolated from others to prevent data corruption.
• Durability: Once a transaction has completed, the results of this transaction have to be made permanent and cannot be
erased from the database due to system failure.
• A real RDBMS database system will guarantee all the four properties for each transaction. The simplistic view of a transaction
issued to the database using SQL is as follows:
• Begin the transaction using begin transaction command.
• Perform various deleted, update or insert operations using SQL queries.
• If all the operation are successful then perform commit otherwise rollback all the operations.
• Spring framework provides an abstract layer on top of different underlying transaction management APIs. The Spring's
transaction support aims to provide an alternative to EJB transactions by adding transaction capabilities to POJOs. Spring
supports both programmatic and declarative transaction management. EJBs requires an application server, but Spring
transaction management can be implemented without a need of application server.
Methods

S.N. Method & Description

TransactionStatus getTransaction(TransactionDefinition definition)


1 This method returns a currently active transaction or create a new one, according
to the specified propagation behavior.

void commit(TransactionStatus status)


2
This method commits the given transaction, with regard to its status.

void rollback(TransactionStatus status)


3
This method performs a rollback of the given transaction.
S.N. Method & Description
int getPropagationBehavior()
1 This method returns the propagation behavior. Spring offers all of the
transaction propagation options familiar from EJB CMT.
int getIsolationLevel()
2 This method returns the degree to which this transaction is isolated from the
work of other transactions.
String getName()
3
This method returns the name of this transaction.
int getTimeout()
4 This method returns the time in seconds in which the transaction must
complete.
boolean isReadOnly()
5
This method returns whether the transaction is read-only.
S.N. Method & Description
boolean hasSavepoint()
1 This method returns whether this transaction internally carries a savepoint,
that is, has been created as nested transaction based on a savepoint.
boolean isCompleted()
2 This method returns whether this transaction is completed, that is, whether
it has already been committed or rolled back.
boolean isNewTransaction()
3
This method returns true in case the present transaction is new.
boolean isRollbackOnly()
4 This method returns whether the transaction has been marked as rollback-
only.
void setRollbackOnly()
5
This method sets the transaction rollback-only.
Network
Programming
In JAVA
Content
• Java.net Package
• Client Server Programs
• TCP UDP Protocol
• URL Class
Network
• Group of computer connected by cable to share the information
• Set of computer & peripheral which are physically connected
• Enable sharing of resource for communication
• Mechanisms by which software running on two or more
computational devices can exchange messages
• Desktop Computers
• PDAs / Set Top Boxes / Mobile Telephones?

• Java is a network centric programming language


• Java abstracts details of network implementation behind a
standard API
Network Programming
More than one CPU are interconnected through different topology
so each CPU Communicate with each other
• Java.net Package
• Provides classes and methods for developing network application through
different protocol

• RMI Remote method Invocation


• For distributed Application
Network Components
• Server Client
• Peer
• Protocol
• Physical Media
• Physical Devices
• IP Address
• DNS
Servers and Clients
• Two machines must connect
• Server waits for connection
• Client initiates connection (create socket)
• Once the connection is made, server & client look identical
Protocol - Set of rules

• TCP Transmission Control Protocol


• UDP User Datagram Protocol
• File Transfer Protocol
• Telnet
• Simple Mail Transport Proto.
• HTTP
• POP3 (Post Office Protocol)
Internet Protocol (IPv4)
• Abstracts away the details of the physical network
implementations (such as Ethernet, Token Ring, ATM, Sonet)
• All traffic uses the same rules to move from machine to machine
• Easy to write programs
• Easy to build network hardware

• Works with Datagrams: small discrete packets of data (rather


like a letter)
• A way of uniquely addressing machines using 32 bit addresses:
giving 4 billion possible addresses (like a zip code)
• IPv6 64 bit
Port Number
• A system for numbering ports on each machine (like a post office
box)
• Port numbers allow several services to operate from a machine
at the same time
• When set up client and server, you must specify IP address and
port.
• Port number range: 0 to 65,535
• 1-1023 are reserved, others may be used.
• 20/21 FTP, 23 Telnet , 25 SMTP, 80 HTTP, 110 POP3
DNS
• IP Address
difficult to
remember
• Maps one
particular IP
Address to a
string of character
which popularly
knowns as DNS
Java InetAddress class
encapsulate the IP Address and DNS
Method Description

public static InetAddress


it returns the instance of InetAddress
getByName(String host) throws
containing LocalHost IP and name.
UnknownHostException

public static InetAddress getLocalHost() it returns the instance of InetAdddress


throws UnknownHostException containing local host name and address.

it returns the host name of the IP


public String getHostName()
address.

it returns the IP address in string


public String getHostAddress()
format.
Example:
import java.io.*;
import java.net.*;
public class InetDemo{
public static void main(String[] args){
try{
InetAddress ip=InetAddress.getByName("www.google.com");
System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());
}catch(Exception e){System.out.println(e);}
}

}
What is a socket?
• Socket
• The combination of an IP address and a port number.
• The name of the Berkeley-derived application programming interfaces (APIs) for applications
using TCP/IP protocols.
• Two types
• Stream socket : reliable two-way connected communication streams
• Datagram socket

• Socket pair
• Specified the two end points that uniquely identifies each TCP connection in an internet.
• 4-tuple: (client IP address, client port number, server IP address, server port number)
Socket Programming with TCP

• The application developer has the ability to fix a few TCP parameters, such
as maximum buffer and maximum segment sizes.
Sockets for server and client
• Server
• Welcoming socket
• Welcomes some initial contact from a client.
• Connection socket
• Is created at initial contact of client.
• New socket that is dedicated to the particular client.

• Client
• Client socket
• Initiate a TCP connection to the server by creating a socket object. (Three-way handshake)
• Specify the address of the server process, namely, the IP address of the server and the port
number of the process.
TCP IP
• Most reliable protocol
• Bidirectional
• Stream
• Two classes
• ServerSocket
• Socket
ServerSocket Class
• Waits for the client to make connection

• Constructor
• ServerSocket(int port)
• ServerSocket(int port, int max)

• Methods
Method Description
returns the socket and establish a
1) public Socket accept()
connection between server and client.
2) public synchronized void close() closes the server socket.
Socket Class
• Establishes connection between the client and server
• Communication between source and destination
• Read and Write data on socket
• Constructor
• Socket(String HostName, int port)
• ServerSocket(InetAddress ia, int port)
• Methods
Method Description
returns the InputStream attached with this
1) public InputStream getInputStream()
socket.
returns the OutputStream attached with
2) public OutputStream getOutputStream()
this socket.
3) public synchronized void close() closes this socket
Example Server Class
import java.io.*;
import java.net.*;
public class TCPServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
BufferedReader br= new BufferedReader(new InputStreamReader(s.getInputStream()));
String str=(String)br.readLine();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){
System.out.println(e);
}
}
}
Example Client Class
import java.io.*;
import java.net.*;
public class TCPClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
PrintWriter out=new PrintWriter(s.getOutputStream());
out.write("Hello Server");
out.flush();
out.close();
s.close();
}catch(Exception e){
System.out.println(e);
}
}
}
DatagramSocket Class
• Constructor
• DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it
with the available Port Number on the localhost machine.
• DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and
binds it with the given Port Number.
• DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a
datagram socket and binds it with the specified port number and host address.

• Method
• void send(DatagramPacket fullPacket)
• Sends the full datagram out onto the network
• void receive(DatagramPacket emptyPacket)
• Waits until a datagram and fills in emptyPacket with the message
DatagramPacket Class
• Constructor
• DatagramPacket(byte[] data, int length): it creates a datagram packet. This
constructor is used to receive the packets.
• DatagramPacket(byte[] data, int length, InetAddress address, int port): it
creates a datagram packet. This constructor is used to send the packets.
URL Class
• Constructor
URL(String spec) Creates a URL object from the String representation.
URL(String protocol, String host, int port, String file) Creates a URL object from the
specified protocol, host, port number, and file.
URL(String protocol, String host, int port, String file, URLStreamHandler handler)
Creates a URL object from the specified protocol, host, port number, file, and
handler.
URL(String protocol, String host, String file) Creates a URL from the specified
protocol name, host name, and file name.
• Method
public String getProtocol() it returns the protocol of the URL.
public String getHost() it returns the host name of the URL.
public String getPort() it returns the Port Number of the URL.
public String getFile() it returns the file name of the URL.
it returns the instance of URLConnection
public URLConnection openConnection()
i.e. associated with this URL.
URLConnection Class
• Constructor
URLConnection(URL url)

Constructs a URL connection to the specified URL.

• Method
• Object getContent() - Retrieves the contents of this URL connection.
• InputStream getInputStream() - Returns an input stream that reads from
this open connection..
• OutputStream getOutputStream() - Returns an output stream that writes to
this connection.
Thanks
JSP
JSP
• JSP technology is used to create web application just like Servlet
technology. It can be thought of as an extension to servlet because it
provides more functionality than servlet such as expression language, jstl
etc.
• A JSP page consists of HTML tags and JSP tags. The jsp pages are easier
to maintain than servlet because we can separate designing and
development. It provides some additional features such as Expression
Language, Custom Tag etc.
• There are many advantages of JSP over servlet. They are as follows:
1) Extension to Servlet
2) Easy to maintain
3) Fast Development: No need to recompile and redeploy
4) Less code than Servlet
Life cycle of a JSP
• 1. JSP Page Translation: A java servlet file is generated from the JSP source file. This is the first
step in its tedious multiple phase life cycle. In the translation phase, the container validates the
syntactic correctness of the JSP pages and tag files. The container interprets the standard
directives and actions, and the custom actions referencing tag libraries used in the page.
• 2. JSP Page Compilation: The generated java servlet file is compiled into a java servlet class.
• 3. Class Loading: The java servlet class that was compiled from the JSP source is loaded into the
container.
• 4. Execution phase: In the execution phase the container manages one or more instances of this
class in response to requests and other events. The interface JspPage contains jspInit() and
jspDestroy(). The JSP specification has provided a special interface HttpJspPage for JSP pages
serving HTTP requests and this interface contains _jspService().
• 5. Initialization: jspInit() method is called immediately after the instance was created. It is called
only once during JSP life cycle.
• 6. _jspService() execution: This method is called for every request of this JSP during its life cycle.
This is where it serves the purpose of creation. Oops! it has to pass through all the above steps to
reach this phase. It passes the request and the response objects. _jspService() cannot be
overridden.
• 7. jspDestroy() execution: This method is called when this JSP is destroyed. With this call the
servlet serves its purpose and submits itself to heaven (garbage collection). This is the end of jsp
life cycle.
JSP API
• The JSP API consists of two packages:
• javax.servlet.jsp
• javax.servlet.jsp.tagext

• javax.servlet.jsp package
• two interfaces are as follows:
• JspPage
• HttpJspPage

• The classes are as follows:


• JspWriter
• PageContext
• JspFactory
• JspEngineInfo
• JspException
• JspError
JSP Scripting elements
• The scripting elements provides the ability to insert java code inside the jsp. There
are three types of scripting elements:
• scriptlet tag
• <% java source code %>

• expression tag
• <%= statement %>

• declaration tag
• <%! field or method declaration %>
Example
• <html>
• <body>
• <%!
• int cube(int n){
• return n*n*n*;
• }
• %>
• <%= "Cube of 3 is:"+cube(3) %>
• </body>
• </html>
JSP Implicit Objects

Object Type

out JspWriter

request HttpServletRequest

response HttpServletResponse

config ServletConfig

application ServletContext

session HttpSession

pageContext PageContext

page Object

exception Throwable
Example
• <%
• String name=request.getParameter("uname");
• out.print("welcome "+name);
• response.sendRedirect("http://www.google.com");
• String driver=config.getInitParameter("dname");
• String driver=application.getInitParameter("dname");
• session.setAttribute("user",name);
• pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE);
• <% (HttpServlet)page.log("message"); %>
• <% this.log("message"); %>
• <%= exception %>
• %>
second.jsp
• index.html welcome.jsp
1.<html>
1. <html> 1.<html>
2.<body>
2. <body> 2.<body>
3.<%
3.<%
3. <form action="welcome.jsp" 4.
4.
> 5.String name=(String)sessio
5.String name=request.getParamet
4. <input type="text" name="un er("uname");
n.getAttribute("user");
ame"> 6.out.print("Hello "+name);
6.out.print("Welcome "+name);
5. <input type="submit" value= 7.
7.
"go"><br/> 8.%>
8.session.setAttribute("user",name);
9.</body>
6. </form>
10.</html>
7. </body> 9.
8. </html> 10.<a href="second.jsp">second jsp
page</a>
11.
12.%>
13.</body>
14.</html>
JSP directives
• The jsp directives are messages that tells the web container how to translate a
JSP page into the corresponding servlet.
• There are three types of directives:
• page directive
• include directive
• taglib directive

• <%@ directive attribute="value" %>


JSP page directive
• <%@ page attribute="value" %>
• Attributes of JSP page directive
• import <%@ page import="java.util.Date" %>
• contentType <%@ page contentType=application/msword %>
• extends
• info <%@ page info="composed by Sonoo Jaiswal" %>
• buffer <%@ page buffer="16kb" %>
• language
• isELIgnored <%@ page isELIgnored="true" %>
• isThreadSafe <%@ page isThreadSafe="false" %>
• autoFlush
• session
• pageEncoding
• errorPage <%@ page errorPage="myerrorpage.jsp" %>
• isErrorPage <%@ page isErrorPage="true" %>
1)import
• The import attribute is used to import class,interface or all the members of a
package.It is similar to import keyword in java class or interface.
• Example of import attribute
• <html>
• <body>

• <%@ page import="java.util.Date" %>
• Today is: <%= new Date() %>

• </body>
• </html>
2)contentType
• The contentType attribute defines the MIME(Multipurpose Internet Mail Extension)
type of the HTTP response.The default value is "text/html;charset=ISO-8859-1".

• Example of contentType attribute


• <html>
• <body>

• <%@ page contentType=application/msword %>
• Today is: <%= new java.util.Date() %>

• </body>
• </html>
4)info
• This attribute simply sets the information of the JSP page which is retrieved later by using
getServletInfo() method of Servlet interface.

• Example of info attribute


• <html>
• <body>

• <%@ page info="composed by Sonoo Jaiswal" %>
• Today is: <%= new java.util.Date() %>

• </body>
• </html>
• The web container will create a method getServletInfo() in the resulting servlet.For example:

• public String getServletInfo() {


• return "composed by Sonoo Jaiswal";
• }
5)buffer
• The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP
page.The default size of the buffer is 8Kb.

• Example of buffer attribute


• <html>
• <body>

• <%@ page buffer="16kb" %>
• Today is: <%= new java.util.Date() %>

• </body>
• </html>
9)errorPage

The errorPage attribute is used to define the error page, if exception occurs in the current page, it will be redirected to the
error page.

Example of errorPage attribute


1.//index.jsp
2.<html>
3.<body>
4.
5.<%@ page errorPage="myerrorpage.jsp" %>
6.
7. <%= 100/0 %>
8.
9.</body>
10.</html>
10)isErrorPage
• //myerrorpage.jsp
• <html>
• <body>

• <%@ page isErrorPage="true" %>

• Sorry an exception occured!<br/>
• The exception is: <%= exception %>

• </body>
• </html>
Jsp Include Directive
• The include directive is used to include the contents of any resource it may be jsp
file, html file or text file. The include directive includes the original content of the
included resource at page translation time (the jsp page is translated only once so
it will be better to include static resource).
• <%@ include file="resourceName" %>
JSP Taglib directive
• The JSP taglib directive is used to define a tag library that defines many tags. We
use the TLD (Tag Library Descriptor) file to define the tags. In the custom tag
section we will use this tag so it will be better to learn it in custom tag.
• <%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>
JSP Action Tags

JSP Action Tags Description


jsp:forward forwards the request and response to another resource.
jsp:include includes another resource.
jsp:useBean creates or locates bean object.
jsp:setProperty sets the value of property in bean object.
jsp:getProperty prints the value of property of the bean.
jsp:plugin embeds another components such as applet.
jsp:param sets the parameter value. It is used in forward and include mostly.
jsp:fallback can be used to print the message if plugin is working. It is used in jsp:plugin.
Expression Language (EL) in JSP
• The Expression Language (EL) simplifies the accessibility of data stored in the Java
Bean component, and other objects like request, session, application etc.
• There are many implicit objects, operators and reserve words in EL.
• It is the newly added feature in JSP technology version 2.0.
• ${ expression }
[] .
• Reserve word and operator
()

lt le gt ge -(unary) not ! empty

eq ne true false * / div % mod

and or not instanceof + - (binary)

div mod empty null < <= > >= lt le gt ge


== != eq ne
&& and
|| or
?:
Implicit Objects in Expression Language (EL)
Implicit Objects Usage
pageScope it maps the given attribute name with the value set in the page scope

requestScope it maps the given attribute name with the value set in the request scope

sessionScope it maps the given attribute name with the value set in the session scope

applicationScope it maps the given attribute name with the value set in the application scope

param it maps the request parameter to the single value


paramValues it maps the request parameter to an array of values
header it maps the request header name to the single value
headerValues it maps the request header name to an array of values
cookie it maps the given cookie name to the cookie value
initParam it maps the initialization parameter
pageContext it provides access to many objects request, session etc.
JSTL (JSP Standard Tag Library)
Tag Name Description

The JSTL core tag provide variable support, URL management, flow control etc.
core tags The url for the core tag is http://java.sun.com/jsp/jstl/core . The prefix of core
tag is c.

The JSTL sql tags provide SQL support. The url for the sql tags is
sql tags
http://java.sun.com/jsp/jstl/sql and prefix is sql.

The xml sql tags provide flow control, transformation etc. The url for the xml
xml tags
tags is http://java.sun.com/jsp/jstl/xml and prefix is x.

The internationalization tags provide support for message formatting, number


internationalization tags and date formatting etc. The url for the internationalization tags is
http://java.sun.com/jsp/jstl/fmt and prefix is fmt.

The functions tags provide support for string manipulation and string length.
functions tags The url for the functions tags is http://java.sun.com/jsp/jstl/functions and prefix
is fn.
core tags
Tag Description
<c:out > Like <%= ... >, but for expressions.
<c:set > Sets the result of an expression evaluation in a 'scope'
<c:remove > Removes a scoped variable (from a particular scope, if specified).
Catches any Throwable that occurs in its body and optionally
<c:catch>
exposes it.
Simple conditional tag which evalutes its body if the supplied
<c:if>
condition is true.
Simple conditional tag that establishes a context for mutually
<c:choose>
exclusive conditional operations, marked by <when> and <otherwise>
Subtag of <choose> that includes its body if its condition evalutes to
<c:when>
'true'.
Subtag of <choose> that follows <when> tags and runs only if all of
<c:otherwise >
the prior conditions evaluated to 'false'.
Retrieves an absolute or relative URL and exposes its contents to
<c:import>
either the page, a String in 'var', or a Reader in 'varReader'.
The basic iteration tag, accepting many different collection types
<c:forEach >
and supporting subsetting and other functionality .
<c:forTokens> Iterates over tokens, separated by the supplied delimeters.
<c:param> Adds a parameter to a containing 'import' tag's URL.
Format tags
Tag Description

<fmt:formatNumber> To render numerical value with specific precision or format.

<fmt:parseNumber> Parses the string representation of a number, currency, or percentage.

<fmt:formatDate> Formats a date and/or time using the supplied styles and pattern

<fmt:parseDate> Parses the string representation of a date and/or time


<fmt:bundle> Loads a resource bundle to be used by its tag body.

<fmt:setLocale> Stores the given locale in the locale configuration variable.

Loads a resource bundle and stores it in the named scoped variable or


<fmt:setBundle>
the bundle configuration variable.
Specifies the time zone for any time formatting or parsing actions
<fmt:timeZone>
nested in its body.

<fmt:setTimeZone> Stores the given time zone in the time zone configuration variable

<fmt:message> To display an internationalized message.


<fmt:requestEncoding> Sets the request character encoding
sql tags

Tag Description

<sql:setDataSource> Creates a simple DataSource suitable only for prototyping

<sql:query> Executes the SQL query defined in its body or through the sql attribute.

<sql:update> Executes the SQL update defined in its body or through the sql attribute.

<sql:param> Sets a parameter in an SQL statement to the specified value.

<sql:dateParam> Sets a parameter in an SQL statement to the specified java.util.Date value.

Provides nested database action elements with a shared Connection, set up to execute
<sql:transaction >
all statements as one transaction.
xml tags
Tag Description
<x:out> Like <%= ... >, but for XPath expressions.

<x:parse> Use to parse XML data specified either via an attribute or in the tag body.

<x:set > Sets a variable to the value of an XPath expression.

Evaluates a test XPath expression and if it is true, it processes its body. If


<x:if >
the test condition is false, the body is ignored.

<x:forEach> To loop over nodes in an XML document.

Simple conditional tag that establishes a context for mutually exclusive


<x:choose>
conditional operations, marked by <when> and <otherwise>

<x:when > Subtag of <choose> that includes its body if its expression evalutes to 'true'

Subtag of <choose> that follows <when> tags and runs only if all of the
<x:otherwise >
prior conditions evaluated to 'false'
<x:transform > Applies an XSL transformation on a XML document
Use along with the transform tag to set a parameter in the XSLT
<x:param >
stylesheet
functions tags
Function Description
fn:contains() Tests if an input string contains the specified substring.
fn:containsIgnoreCas Tests if an input string contains the specified substring in a case insensitive
e() way.
fn:endsWith() Tests if an input string ends with the specified suffix.

fn:escapeXml() Escapes characters that could be interpreted as XML markup.

Returns the index withing a string of the first occurrence of a specified


fn:indexOf()
substring.
fn:join() Joins all elements of an array into a string.
Returns the number of items in a collection, or the number of characters in a
fn:length()
string.
Returns a string resulting from replacing in an input string all occurrences
fn:replace()
with a given string.
fn:split() Splits a string into an array of substrings.
fn:startsWith() Tests if an input string starts with the specified prefix.
fn:substring() Returns a subset of a string.

fn:substringAfter() Returns a subset of a string following a specific substring.

fn:substringBefore() Returns a subset of a string before a specific substring.


fn:toLowerCase() Converts all of the characters of a string to lower case.
fn:toUpperCase() Converts all of the characters of a string to upper case.
fn:trim() Removes white spaces from both ends of a string.
JSP - Exception Handling
• Checked exceptions: Achecked exception is an exception that is typically a user
error or a problem that cannot be foreseen by the programmer. For example, if a
file is to be opened, but the file cannot be found, an exception occurs. These
exceptions cannot simply be ignored at the time of compilation.
• Runtime exceptions: A runtime exception is an exception that occurs that
probably could have been avoided by the programmer. As opposed to checked
exceptions, runtime exceptions are ignored at the time of compliation.
• Errors: These are not exceptions at all, but problems that arise beyond the control
of the user or the programmer. Errors are typically ignored in your code because
you can rarely do anything about an error. For example, if a stack overflow
occurs, an error will arise. They are also ignored at the time of compilation.
Methods

SN Methods with Description


public String getMessage()
1 Returns a detailed message about the exception that has occurred. This message is initialized in the
Throwable constructor.
public Throwable getCause()
2
Returns the cause of the exception as represented by a Throwable object.
public String toString()
3
Returns the name of the class concatenated with the result of getMessage()
public void printStackTrace()
4
Prints the result of toString() along with the stack trace to System.err, the error output stream.
public StackTraceElement [] getStackTrace()
5 Returns an array containing each element on the stack trace. The element at index 0 represents the top
of the call stack, and the last element in the array represents the method at the bottom of the call stack.
public Throwable fillInStackTrace()
6 Fills the stack trace of this Throwable object with the current stack trace, adding to any previous
information in the stack trace.
Example:
<%@ page errorPage="ShowError.jsp" %>

<html>
<head>
<title>Error Handling Example</title>
</head>
<body>
<%
// Throw an exception to invoke the error page
int x = 1;
if (x == 1)
{
throw new RuntimeException("Error condition!!!");
}
%>
</body>
</html>
ShowError.jsp
<%@ page isErrorPage="true" %>
<html>
<head>
<title>Show Error Page</title>
</head>
<body>
<h1>Opps...</h1>
<p>Sorry, an error occurred.</p>
<p>Here is the exception stack trace: </p>
<pre>
<% exception.printStackTrace(response.getWriter()); %>
</pre>
</body>
</html>
Processing XML in JSP:
• When you send XML data via HTTP, it makes sense to use JSP to handle incoming and
outgoing XML documents for example RSS documents. As an XML document is merely
a bunch of text, creating one through a JSP is no more difficult than creating an
HTML document.
• Before you proceed with XML processing using JSP, you would need following two XML
and XPath related libraries into your.
• Sending XML from a JSP:
<%@ page contentType="text/xml" %>
<books>
<book>
<name>Padam History</name>
<author>ZARA</author>
<price>100</price>
</book>
</books>
Processing XML in JSP:
•<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
•<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
•<html>
•<head>
• <title>JSTL x:parse Tags</title>
•</head>
•<body>
•<h3>Books Info:</h3>
•<c:import var="bookInfo" url="http://localhost:8080/books.xml"/>
•<x:parse xml="${bookInfo}" var="output"/>
•<b>The title of the first book is</b>:
•<x:out select="$output/books/book[1]/name" />
•<br>
•<b>The price of the second book</b>:
•<x:out select="$output/books/book[2]/price" />
•</body>
•</html>
Formatting XML with JSP:
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html" indent="yes"/>
<xsl:template match="/">
<html>
<body>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match="books">
<table border="1" width="100%">
<xsl:for-each select="book">
<tr>
<td>
<i><xsl:value-of select="name"/></i>
</td>
<td>
<xsl:value-of select="author"/>
</td>
<td>
<xsl:value-of select="price"/>
</td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
<html>
<head>
<title>JSTL x:transform Tags</title>
</head>
<body>
<h3>Books Info:</h3>
<c:set var="xmltext">
<books>
<book>
<name>Padam History</name>
<author>ZARA</author>
<price>100</price>
</book>
<book>
<name>Great Mistry</name>
<author>NUHA</author>
<price>2000</price>
</book>
</books>
</c:set>

<c:import url="http://localhost:8080/style.xsl" var="xslt"/>


<x:transform xml="${xmltext}" xslt="${xslt}"/>

</body>
</html>
Thanks
JSF
Java Server Faces
Model/View/Controller Design Pattern for Web
Development
JSF
• is a “server side user interface component MVC framework for Java™
technology-based web applications”
• is a specification and reference implementation for a web application
development framework
• Components
• Events
• Validators
• Back-end-data integration
• is designed to be leveraged by tools
• NetBeans, RAD (Rational Application Developer), Eclipse, JDeveloper,
etc.
Features of JSF
• Bean management
• Validation model
• Component library that permits extensions
• Flexible rendering (not necessarily XHTML)
• Configurable navigation
• State management
• Conversion Model
• Relies on JSP and Servlet technology
• Think “GUI Building” for the web
• MVC for web applications
• Easy to use
• Extensible Component and Rendering architecture
• Support for client device independence
• Standard
• Huge vendor and industry support
• Built-in UI component model (unlike JSP and Servlet)
• Offers finer-grained separation of behavior and presentation than JSP
• Component-specific event handling
• UI elements as stateful objects on the server

• UI-component and Web-tier concepts without limiting you to a particular scripting


technology or markup language
• Can work with any presentation technology including JSP
Comparison
Architecture
• . JSF technology is a framework for developing, building server side User Interface
Components and using them in a web application.
• JSF technology is based on the Model View Controller (MVC) architecture for
separating logic from presentation
• MVC design pattern designs an application using three separate modules:
Module Description
Model Carries Data and login
View Shows User Interface
Controller Handles processing of an application.

• Purpose of MVC design pattern is to separate model and presentation to enable


developers to set focus on their core skills and collaborate more clearly.
• Web Designers have to concentrate only on view layer rather than model and
controller layer. Developers can change the code for model and typically need not to
change view layer.Controllers are used to process user actions. In this process layer
model and views may be changed.
JSF Architecture
• A JSF application is similar to any other Java technology-based web application;
it runs in a Java servlet container, and contains
• JavaBeans components as models containing application-specific functionality and
data
• A custom tag library for representing event handlers and validators
• A custom tag library for rendering UI components
• UI components represented as stateful objects on the server
• Server-side helper classes
• Validators, event handlers, and navigation handlers
• Application configuration resource file for configuring application resources
Architecture
JSF Life Cycle
• Phase 1: Restore view
• JSF begins the restore view phase as soon as a link or a button is clicked and JSF
receives a request.
• During this phase, the JSF builds the view, wires event handlers and validators to UI
components and saves the view in the FacesContext instance. The FacesContext
instance will now contains all the information required to process a request.
• Phase 2: Apply request values
• After the component tree is created/restored, each component in component tree uses
decode method to extract its new value from the request parameters. Component
stores this value. If the conversion fails, an error message is generated and queued on
FacesContext. This message will be displayed during the render response phase, along
with any validation errors.
• If any decode methods / event listeners called renderResponse on the current
FacesContext instance, the JSF moves to the render response phase.
• Phase 3: Process validation
• During this phase, the JSF processes all validators registered on component tree. It
examines the component attribute rules for the validation and compares these rules to
the local value stored for the component.
• If the local value is invalid, the JSF adds an error message to the FacesContext
instance, and the life cycle advances to the render response phase and display the
same page again with the error message.
• Phase 4: Update model values
• After the JSF checks that the data is valid, it walks over the component tree and set
the corresponding server-side object properties to the components' local values. The
JSF will update the bean properties corresponding to input component's value
attribute.
• If any updateModels methods called renderResponse on the current FacesContext
instance, the JSF moves to the render response phase.
• Phase 5: Invoke application
• During this phase, the JSF handles any application-level events, such as submitting a
form / linking to another page.
• Phase 6: Render response
• During this phase, the JSF asks container/application server to render the page if the
application is using JSP pages. For initial request, the components represented on the
page will be added to the component tree as the JSP container executes the page. If
this is not an initial request, the component tree is already built so components need
not to be added again. In either case, the components will render themselves as the
JSP container/Application server traverses the tags in the page.
• After the content of the view is rendered, the response state is saved so that
subsequent requests can access it and it is available to the restore view phase.
Manage Bean
• Managed Bean is a regular Java Bean class registered with JSF. In other words,
Managed Beans is a java bean managed by JSF framework.
• The managed bean contains the getter and setter methods, business logic or even
a backing bean (a bean contains all the HTML form value).
• Managed beans works as Model for UI component.
• Managed Bean can be accessed from JSF page.
• In JSF 1.2,a managed bean had to register it in JSF configuration file such as
faces-config.xml.
• From JSF 2.0 onwards, Managed beans can be easily registered using annotations.
This approach keeps beans and there registration at one place and it becomes
easier to manage.
• @ManagedBean Annotation
• @ManagedBean marks a bean to be a managed bean with the name specified in
name attribute. If the name attribute is not specified, then the managed bean
name will default to class name portion of the fully qualified class name. In our
case it would be helloWorld.
• Another important attribute is eager. If eager="true" then managed bean is
created before it is requested for the first time otherwise "lazy" initialization is
used in which bean will be created only when it is requested.
Scope
Scope Description
Bean lives as long as the HTTP request-response lives. It get created upon a HTTP
@RequestScoped request and get destroyed when the HTTP response associated with the HTTP request is
finished.
Bean lives as long as a single EL evaluation. It get created upon an EL evaluation and get
@NoneScoped
destroyed immediately after the EL evaluation.
Bean lives as long as user is interacting with the same JSF view in the browser
@ViewScoped window/tab. It get created upon a HTTP request and get destroyed once user postback
to a different view.

Bean lives as long as the HTTP session lives. It get created upon the first HTTP request
@SessionScoped
involving this bean in the session and get destroyed when the HTTP session is invalidated.

Bean lives as long as the web application lives. It get created upon the first HTTP request
involving this bean in the application (or when the web application starts up and the
@ApplicationScoped
eager=true attribute is set in @ManagedBean) and get destroyed when the web
application shuts down.

Bean lives as long as the bean's entry in the custom Map which is created for this scope
@CustomScoped
lives.
Navigation
• Navigation rules are those rules provided by JSF Framework which describe which
view is to be shown when a button or link is clicked.
• Navigation rules can be defined in JSF configuration file named faces-config.xml.
• Navigation rules can be defined in managed beans.
• Navigation rules can contain conditions based on which resulted view can be
shown.
• JSF 2.0 provides implicit navigation as well in which there is no need to define
navigation rules as such.
• Implicit Navigation
• JSF 2.0 provides auto view page resolver mechanism named implicit navigation.In
this case you only need to put view name in action attribute and JSF will search
the correct view page automatically in the deployed application.
Basic Tag
• JSF provides a standard HTML tag library. These tags get rendered into
corresponding html output.

• For these tags you need to use the following namespaces of URI in html node.

• <html
• xmlns="http://www.w3.org/1999/xhtml"
• xmlns:h="http://java.sun.com/jsf/html"
• >
S.N. Tag & Description h:graphicImage
13
h:inputText Renders an image.
1 Renders a HTML input of type="text", h:outputStylesheet
14
text box. Includes a CSS style sheet in HTML output.
h:inputSecret h:outputScript
15
2 Renders a HTML input of Includes a script in HTML output.
type="password", text box. h:commandButton
h:inputTextarea 16 Renders a HTML input of type="submit"
3
Renders a HTML textarea field. button.
h:inputHidden h:Link
4 17
Renders a HTML input of type="hidden". Renders a HTML anchor.
h:selectBooleanCheckbox h:commandLink
5 18
Renders a single HTML check box. Renders a HTML anchor.
h:selectManyCheckbox h:outputLink
6 19
Renders a group of HTML check boxes. Renders a HTML anchor.
h:selectOneRadio h:panelGrid
7 20
Renders a single HTML radio button. Renders an HTML Table in form of grid.
h:selectOneListbox h:message
8 21
Renders a HTML single list box. Renders message for a JSF UI Component.
h:messages
h:selectManyListbox
9 22 Renders all message for JSF UI
Renders a HTML multiple list box.
Components.
h:selectOneMenu f:param
10 23
Renders a HTML combo box. Pass parameters to JSF UI Component.
h:outputText f:attribute
11 24
Renders a HTML text. Pass attribute to a JSF UI Component.
h:outputFormat f:setPropertyActionListener
12 Renders a HTML text. It accepts 25
Sets value of a managed bean's property
parameters.
Facelets Servlet
S.N. Tag & Description
Templates
We'll demonstrate how to use templates using following
tags
1 •<ui:insert>
•<ui:define>
•<ui:include>
•<ui:define>
Parameters
We'll demonstrate how to pass parameters to a template
2
file using following tag
•<ui:param>
Custom
3
We'll demonstrate how to create custom tags.
Remove
4 We'll demonstrate capability to remove JSF code from
generated HTML page.
Convertor Tag

S.N. Tag & Description


f:convertNumber
1 Converts a String into a Number of desired
format
f:convertDateTime
2
Converts a String into a Date of desired format
Custom Convertor
3
Creating a custom convertor
Validator Tag

S.N. Tag & Description


f:validateLength
1
Validates length of a string
f:validateLongRange
2
Validates range of numeric value
f:validateDoubleRange
3
Validates range of float value
f:validateRegex
4 Validate JSF component with a given regular
expression.
Custom Validator
5
Creating a custom validator
Composite Tags

S.N. tag & Description


composite:interfaceDeclare configurable values to be used in
1
composite:implementatio
2 composite:attributeConfiguration values are declared using this tag
composite:implementationDeclares JSF component. Can access the
3 configurable values defined in composite:interface using
#{cc.attrs.attribute-name} expression.
Data Table
• When a user clicks a JSF button or link or changes any value in text field, JSF UI
component fires event which will be handled by the application code.
• To handle such event, event handler are to be registered in the application code
or managed bean.
• When a UI component checks that a user event has happened, it creates an
instance of the corresponding event class and adds it to an event list.
• Then, Component fires the event, i.e., checks the list of listeners for that event
and call the event notification method on each listener or handler.
• JSF also provide system level event handlers which can be used to do some tasks
when application starts or is stopping.
Event Handling

S.N. Event Handlers & Description


valueChangeListener
1 Value change events get fired when user make changes in input
components.
actionListener
2
Action events get fired when user clicks on a button or link component.
Application Events
3 Events firing during JSF lifecycle: PostConstructApplicationEvent,
PreDestroyApplicationEvent , PreRenderViewEvent.
EL in JSF
• JSF provides a rich expression language. We can write normal operations using
#{operation-expression} notation. Some of the advantages of JSF Expression
languages are following.
• Can reference bean properties where bean can be a object stored in request,
session or application scope or is a managed bean.
• Provides easy access to elements of a collection which can be a list, map or an
array.
• Provides easy access to predefined objects such as request.
• Arithmetic, logical, relational operations can be done using expression language.
• Automatic type conversion.
• Shows missing values as empty strings instead of NullPointerException.
JSF PrimeFaces
• A Different Point of View

• Prime Technology is not a software vendor but a software development house along with the consulting&training activities. A
framework that's not even used by its own creators can easily miss vital points regarding usability and simplicity, a major
difference compared to vendor products is that we use PrimeFaces in all of our clients' projects as the front end framework. This
helps us to view the project from an application developer's point of view so that we can easily realize the missing features and
quickly fix the bugs. This significantly differs PrimeFaces from other libraries.

• Simplicity and Performance

• PrimeFaces is a lightweight library, all decisions made are based on keeping PrimeFaces as lightweight as possible. Usually adding a
third-party solution could bring a overhead however this is not the case with PrimeFaces. It is just one single jar with no
dependencies and nothing to configure.

• Ease of Use

• Components in PrimeFaces are developed with a design principle which states that "A good UI component should hide complexity
but keep the flexibility" while doing so.

• Strong Community Feedback

• PrimeFaces community continuously helps the development of PrimeFaces by providing feedback, new ideas, bug reports and
patches.

• Spring Applications

• If you are using Spring Framework and looking for a JSF front-end framework, then your search is over as SpringSource suggests
PrimeFaces to be used in JSF-Spring applications. Also Spring ROO only supports PrimeFaces in JSF addon. Please note that
PrimeFaces is a UI framework and not coupled with a middleware framework like Spring, EJBs or similar.
Snippet:
•Namespaces
•PrimeFaces namespace is necessary to add PrimeFaces components to your pages.
•view plainprint?
• xmlns:p="http://primefaces.org/ui"
•For PrimeFaces Mobile, the namespace would be;
•view plainprint?
• xmlns:p="http://primefaces.org/mobile"
•Test Run
•That's it, now you can add a test component to see if everything is ok.
•view plainprint?
• <html xmlns="http://www.w3.org/1999/xhtml"
• xmlns:h="http://java.sun.com/jsf/html"
• xmlns:f="http://java.sun.com/jsf/core"
• xmlns:p="http://primefaces.org/ui">
• <h:head>
• </h:head>
• <h:body>
• <p:spinner />
• </h:body>
• </html>
JDBC
Java Database Connectivity

Java

1
Java JDBC
• Java JDBC is a java API to connect and execute query with
the database. JDBC API uses jdbc drivers to connect with
the database.

2 JDBC
JDBC Driver
• JDBC Driver is a software component that enables java
application to interact with the database. There are 4 types
of JDBC drivers:

• JDBC-ODBC bridge driver


• Native-API driver (partially java driver)
• Network Protocol driver (fully java driver)
• Thin driver (fully java driver)

3 JDBC
JDBC-ODBC bridge driver
• The JDBC-ODBC bridge driver uses ODBC driver to connect to
the database. The JDBC-ODBC bridge driver converts JDBC
method calls into the ODBC function calls. This is now
discouraged because of thin driver.

• Advantages:
• easy to use.
• can be easily connected to any database.

• Disadvantages:
• Performance degraded because JDBC method call is converted into the
ODBC function calls.
• The ODBC driver needs to be installed on the client machine.
4 JDBC
JDBC-ODBC bridge driver
• The JDBC-ODBC bridge driver uses ODBC driver to connect to
the database. The JDBC-ODBC bridge driver converts JDBC
method calls into the ODBC function calls. This is now
discouraged because of thin driver.

• Advantages:
• easy to use.
• can be easily connected to any database.

• Disadvantages:
• Performance degraded because JDBC method call is converted into the
ODBC function calls.
• The ODBC driver needs to be installed on the client machine.
5 JDBC
Native-API driver
• The Native API driver uses the client-side libraries of the
database. The driver converts JDBC method calls into native
calls of the database API. It is not written entirely in java.

• Advantages:
• performance upgraded than JDBC-ODBC bridge driver..

• Disadvantages:
• The Native driver needs to be installed on the each client machine.
• The Vendor client library needs to be installed on client machine.

6 JDBC
Network Protocol driver
• The Network Protocol driver uses middleware (application
server) that converts JDBC calls directly or indirectly into the
vendor-specific database protocol. It is fully written in java.

• Advantages:
• No client side library is required because of application server that can
perform many tasks like auditing, load balancing, logging etc.

• Disadvantages:
• Network support is required on client machine.
• Requires database-specific coding to be done in the middle tier.
• Maintenance of Network Protocol driver becomes costly because it requires
database-specific coding to be done in the middle tier.

7 JDBC
Thin driver
• The thin driver converts JDBC calls directly into the
vendor-specific database protocol. That is why it is known
as thin driver. It is fully written in Java language.

• Advantages:
• Better performance than all other drivers.
• No software is required at client side or server side.

• Disadvantages:
• Drivers depends on the Database.

8 JDBC
5 Steps to connect to the database in
java

• Register the driver class


• Creating connection
• Creating statement
• Executing queries
• Closing connection

9 JDBC
Register the driver class
• The forName() method of Class. Class is used to register the
driver class. This method is used to dynamically load the
driver class.
• Syntax of forName() method
• public static void forName(String className)throws ClassNotFoundEx
ception

• Example to register the OracleDriver class


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

10 JDBC
Create the connection object
• The getConnection() method of DriverManager class is used
to establish connection with the database
• Syntax of getConnection() method
• 1) public static Connection getConnection(String url)throws
SQLException
• 2) public static Connection getConnection(String url,String
name,String password) throws SQLExceptiontion

• Example to establish connection with the Oracle database


• Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@local
host:1521:xe","system","password");

11 JDBC
Create the Statement object
• The createStatement() method of Connection interface is
used to create statement. The object of statement is
responsible to execute queries with the database.
• Syntax of createStatement() method
• public Statement createStatement()throws SQLException

• Example to create the statement object


• Statement stmt=con.createStatement();

12 JDBC
Execute the query
• The executeQuery() method of Statement interface is used
to execute queries to the database. This method returns the
object of ResultSet that can be used to get all the records of
a table.
• Syntax of executeQuery() method
• public ResultSet executeQuery(String sql)throws SQLException

• Example to execute query


• ResultSet rs=stmt.executeQuery("select * from emp");
• while(rs.next()){
• System.out.println(rs.getInt(1)+" "+rs.getString(2));
• }

13 JDBC
Close the connection object
• By closing connection object statement and ResultSet will be
closed automatically. The close() method of Connection
interface is used to close the connection.
• Syntax of close() method
• public void close()throws SQLException

• Example to close connection


• con.close();

14 JDBC
DriverManager class:
• The DriverManager class acts as an interface between user
and drivers.
• It keeps track of the drivers that are available and handles
establishing a connection between a database and the
appropriate driver.
• The DriverManager class maintains a list of Driver classes
that have registered themselves by calling the method
DriverManager.registerDriver().

15 JDBC
Commonly used methods of
DriverManager class:
1) public static void is used to register the given driver with
registerDriver(Driver driver): DriverManager.
is used to deregister the given driver
2) public static void
(drop the driver from the list) with
deregisterDriver(Driver driver):
DriverManager.
3) public static Connection is used to establish the connection with
getConnection(String url): the specified url.
4) public static Connection is used to establish the connection with
getConnection(String url,String the specified url, username and
userName,String password): password.

16 JDBC
Connection interface:
• A Connection is the session between java application and
database.
• The Connection interface is a factory of Statement,
PreparedStatement, and DatabaseMetaData i.e. object of
Connection can be used to get the object of Statement and
DatabaseMetaData.
• The Connection interface provide many methods for
transaction management like commit(),rollback() etc.

17 JDBC
Commonly used methods of Connection
interface:
1) public Statement createStatement(): creates a statement object that can be used
to execute SQL queries.

2) public Statement createStatement(int resultSetType,int resultSetConcurrency):


Creates a Statement object that will generate ResultSet objects with the given type
and concurrency.

3) public void setAutoCommit(boolean status): is used to set the commit status.By


default it is true.

4) public void commit(): saves the changes made since the previous commit/rollback
permanent.

5) public void rollback(): Drops all changes made since the previous
commit/rollback.

6) public void close(): closes the connection and Releases a JDBC resources
immediately.

18 JDBC
Statement interface
• The Statement interface provides methods to execute
queries with the database. The statement interface is a
factory of ResultSet i.e. it provides factory method to get
the object of ResultSet.
• Commonly used methods of Statement interface:
• 1) public ResultSet executeQuery(String sql): is used to execute
SELECT query. It returns the object of ResultSet.
• 2) public int executeUpdate(String sql): is used to execute specified
query, it may be create, drop, insert, update, delete etc.
• 3) public boolean execute(String sql): is used to execute queries that
may return multiple results.
• 4) public int[] executeBatch(): is used to execute batch of commands.

19 JDBC
ResultSet interface
is used to move the cursor to the one row next from the current
1) public boolean next():
position.
is used to move the cursor to the one row previous from the current
2) public boolean previous():
position.
3) public boolean first(): is used to move the cursor to the first row in result set object.

4) public boolean last(): is used to move the cursor to the last row in result set object.

is used to move the cursor to the specified row number in the ResultSet
5) public boolean absolute(int row):
object.
is used to move the cursor to the relative row number in the ResultSet
6) public boolean relative(int row):
object, it may be positive or negative.
is used to return the data of specified column index of the current row
7) public int getInt(int columnIndex):
as int.
8) public int getInt(String is used to return the data of specified column name of the current row
columnName): as int.
9) public String getString(int is used to return the data of specified column index of the current row
columnIndex): as String.
10) public String getString(String is used to return the data of specified column name of the current row
columnName): as String.

20 JDBC
PreparedStatement interface
• The PreparedStatement interface is a subinterface of
Statement. It is used to execute parameterized query.
• As you can see, we are passing parameter (?) for the values.
Its value will be set by calling the setter methods of
PreparedStatement.
• The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only
once.
• Syntax:
public PreparedStatement prepareStatement(String query)t
hrows SQLException{}

21 JDBC
Methods of PreparedStatement interface
Method Description

public void setInt(int paramIndex, int sets the integer value to the given
value) parameter index.

public void setString(int paramIndex, sets the String value to the given
String value) parameter index.

public void setFloat(int paramIndex, float sets the float value to the given parameter
value) index.

public void setDouble(int paramIndex, sets the double value to the given
double value) parameter index.

executes the query. It is used for create,


public int executeUpdate()
drop, insert, update, delete etc.

executes the select query. It returns an


public ResultSet executeQuery()
instance of ResultSet.

22 JDBC
DatabaseMetaData interface
• DatabaseMetaData interface provides methods to get meta data of a
database such as database product name, database product version,
driver name, name of total number of tables, name of total number
of views etc.
• Commonly used methods of DatabaseMetaData interface
• public String getDriverName()throws SQLException: it returns the name of the
JDBC driver.
• public String getDriverVersion()throws SQLException: it returns the version
number of the JDBC driver.
• public String getUserName()throws SQLException: it returns the username of the
database.
• public String getDatabaseProductName()throws SQLException: it returns the
product name of the database.
• public String getDatabaseProductVersion()throws SQLException: it returns the
product version of the database.
• public ResultSet getTables(String catalog, String schemaPattern, String
tableNamePattern, String[] types)throws SQLException: it returns the description
of the tables of the specified catalog. The table type can be TABLE, VIEW, ALIAS,
SYSTEM TABLE, SYNONYM etc.
23 JDBC
CallableStatement Interface
• To call the stored procedures and functions,
CallableStatement interface is used.
• We can have business logic on the database by the use of
stored procedures and functions that will make the
performance better because these are precompiled.
• Suppose you need the get the age of the employee based on
the date of birth, you may create a function that receives
date as the input and returns age of the employee as the
output.
• public CallableStatement prepareCall("{ call procedurename(
?,?...?)}");
• CallableStatement stmt=con.prepareCall("{call myprocedure(
?,?)}");

24 JDBC
Difference between stored procedures and
functions
Stored Procedure Function
is used to perform business logic. is used to perform calculation.
must not have the return type. must have the return type.
may return 0 or more values. may return only one values.
We can call functions from the Procedure cannot be called from
procedure. function.
Procedure supports input and output
Function supports only input parameter.
parameters.
Exception handling using try/catch block Exception handling using try/catch can't
can be used in stored procedures. be used in user defined functions.

25 JDBC
Transaction Management in JDBC
• Transaction represents a single unit of work.
• The ACID properties describes the transaction management
well. ACID stands for Atomicity, Consistency, isolation and
durability.
• Atomicity means either all successful or none.
• Consistency ensures bringing the database from one
consistent state to another consistent state.
• Isolation ensures that transaction is isolated from other
transaction.
• Durability means once a transaction has been committed, it
will remain so, even in the event of errors, power loss etc.

26 JDBC
Transaction methods

Method Description
It is true bydefault means each
void setAutoCommit(boolean status)
transaction is committed bydefault.

void commit() commits the transaction.

void rollback() cancels the transaction.

27 JDBC
Batch Processing in JDBC
• Instead of executing a single query, we can execute a batch
(group) of queries. It makes the performance fast.
• The java.sql.Statement and java.sql.PreparedStatement
interfaces provide methods for batch processing

Method Description
void addBatch(String query) It adds query into batch.
int[] executeBatch() It executes the batch of queries.

28 JDBC
Statement

29 March 15, 2024


Java.sql

30 March 15, 2024


SQL Types/Java Types Mapping
SQL Type Java Type

CHAR String
VARCHAR String
LONGVARCHAR String
NUMERIC java.Math.BigDecimal
DECIMAL java.Math.BigDecimal
BIT boolean
TINYINT int
SMALLINT int
INTEGER int
BIGINT long
REAL float
FLOAT double
DOUBLE double
BINARY byte[]
VARBINARY byte[]
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp
31 March 15, 2024
Oracle DB
import java.sql.*;

class OracleCon{

public static void main(String args[]){


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

Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

Statement stmt=con.createStatement();

ResultSet rs=stmt.executeQuery("select * from emp");


while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

con.close();

}catch(Exception e){ System.out.println(e);}

}
}

32 JDBC
MySQL DB
import java.sql.*;

class MysqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");

Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sonoo","ro
ot","root");
//here sonoo is the database name, root is the username and root is the
password
Statement stmt=con.createStatement();

ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

con.close();

}catch(Exception e){ System.out.println(e);}

33
} JDBC

}
MS Access DB
import java.sql.*;
class Test{
public static void main(String ar[]){
try{
String database="student.mdb";//Here database exists in the current
directory

String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" +


database + ";DriverID=22;READONLY=true";

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c=DriverManager.getConnection(url);
Statement st=c.createStatement();
ResultSet rs=st.executeQuery("select * from login");

while(rs.next()){
System.out.println(rs.getString(1));
}

}catch(Exception ee){System.out.println(ee);}

}
}
34 JDBC
PS
class RS{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system
","oracle");
PreparedStatement ps=con.prepareStatement("insert into emp130 values(?,?,?)");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
do{
System.out.println("enter id:");
int id=Integer.parseInt(br.readLine());
System.out.println("enter name:");
String name=br.readLine();
System.out.println("enter salary:");
float salary=Float.parseFloat(br.readLine());
ps.setInt(1,id);
ps.setString(2,name);
ps.setFloat(3,salary);
int i=ps.executeUpdate();
System.out.println(i+" records affected");
System.out.println("Do you want to continue: y/n");
String s=br.readLine();
if(s.startsWith("n")){
break;
}
}while(true);
con.close();
} 35 JDBC

}
ResultSet MetaDATA
import java.sql.*;
class Rsmd{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");

Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

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


ResultSet rs=ps.executeQuery();

ResultSetMetaData rsmd=rs.getMetaData();

System.out.println("Total columns: "+rsmd.getColumnCount());


System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnType
Name(1));

con.close();

}catch(Exception
36
e){ System.out.println(e);} JDBC

}
}
DATABASE MetaDATA
import java.sql.*;
class Dbmd{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");

Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

DatabaseMetaData dbmd=con.getMetaData();

System.out.println("Driver Name: "+dbmd.getDriverName());


System.out.println("Driver Version: "+dbmd.getDriverVersion());
System.out.println("UserName: "+dbmd.getUserName());
System.out.println("Database Product Name: "+dbmd.getDatabaseProductName
());
System.out.println("Database Product Version: "+dbmd.getDatabaseProductVersi
on());
con.close();

}catch(Exception e){ System.out.println(e);}


37 JDBC
}
}
Inserting Photo
import java.sql.*;
import java.io.*;
public class InsertImage {
public static void main(String[] args) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

PreparedStatement ps=con.prepareStatement("insert into imgtable values(?,?)")


;
ps.setString(1,"sonoo");

FileInputStream fin=new FileInputStream("d:\\g.jpg");


ps.setBinaryStream(2,fin,fin.available());
int i=ps.executeUpdate();
System.out.println(i+" records affected");

con.close();
}catch (Exception e) {e.printStackTrace();}
}
} 38 JDBC
Retrieving Photo
import java.sql.*;
import java.io.*;
public class RetrieveImage {
public static void main(String[] args) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

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


ResultSet rs=ps.executeQuery();
if(rs.next()){//now on 1st row

Blob b=rs.getBlob(2);//2 means 2nd column data


byte barr[]=b.getBytes(1,(int)b.length());//1 means first image

FileOutputStream fout=new FileOutputStream("d:\\sonoo.jpg");


fout.write(barr);

fout.close();
}//end of if
System.out.println("ok");

con.close();
}catch
39
(Exception e) {e.printStackTrace(); } JDBC
}
}
Callable Statement
create or replace procedure "INSERTR" (id IN NUMBER, name IN VARCHAR2)
is
begin
insert into user values(id, name);
end;

import java.sql.*;
public class Proc {
public static void main(String[] args) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

CallableStatement stmt=con.prepareCall("{call insertR(?,?)}");


stmt.setInt(1,1011);
stmt.setString(2,"Amit");
stmt.execute();

System.out.println("success");
}
} 40 JDBC
Transaction Management
class TM{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
con.setAutoCommit(false);
PreparedStatement ps=con.prepareStatement("insert into user values(?,?)");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.println("enter id");
String s1=br.readLine();
int id=Integer.parseInt(s1);
System.out.println("enter name");
String name=br.readLine();
ps.setInt(1,id);
ps.setString(2,name);
ps.executeUpdate();
System.out.println("commit/rollback");
String answer=br.readLine();
if(answer.equals("commit")){
con.commit();
}
else
con.rollback();

System.out.println("Want to add more records y/n");


String ans=br.readLine();
if(ans.equals("n")){
break;
}
}
con.commit();
41 JDBC
System.out.println("record successfully saved");
con.close();//before closing connection commit() is called
}catch(Exception e){System.out.println(e);}
}
RowSet
public class RowSetExample {
public static void main(String[] args) throws Exception {
Class.forName("oracle.jdbc.driver.OracleDriver");

//Creating and Executing RowSet


JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();
rowSet.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
rowSet.setUsername("system");
rowSet.setPassword("oracle");

rowSet.setCommand("select * from emp400");


rowSet.execute();

while (rowSet.next()) {
// Generating cursor Moved event
System.out.println("Id: " + rowSet.getString(1));
System.out.println("Name: " + rowSet.getString(2));
System.out.println("Salary: " + rowSet.getString(3));
}

}
} 42 JDBC
43 JDBC
Thanks

44 March 15, 2024


Java Servlet
J2EE Architecture
J2EE – Container Architecture
• Application is considered as a collection of related yet independent components
• Container acts as an execution environment for the components
• Container Provides services to the components

J2EE Container
J2EE Component
J2EE
Component Component Code
& Resources
J2EE
J2EE
J2EE
Component
Component
Component
Component 2
J2EE Architecture
J2EE – Container Architecture 3rd & Nth
Client Tier Tiers
Applet Container

Applet

Middle Tier
Application Container
Database
J2EE Server
Application
Web Container Web Container
internet Servlets JSPs EJBs
J J J J internet Enterprise
D A A M Information
B X A S System

Connections

Connections
JavaMail/JAF

JavaMail/JAF
P
JAX

P
JAX
JDBC

JDBC
C P S JAAS

JAAS
JMS

JTA
JMS

JTA
J2EE Server
J2EE Server

J2ME App

Non-Java Sever

Other
Application
or Server
J2EE Architecture
Client Tier
• Client Container has a contract with applications
to provide certain functionality to the components
Applet Container
in the application

Application Container
Applet

ClientApp
(JAR file)
Application Container

Deployment
Descriptor
Main AppClass
Public static void main (String args[ ] )
Application

J J J J Java Packages,
D A A M Classes, Libraries
B X A S
C P S
J2EE Architecture
Middle Tier Container
• Web Container
• Manages execution of servlets and JSPs
• Part of web or application server
• Supports HTTP
• EJB Container
• Business Components that contain business logic or rules
• Two types of EJBs
• Session Beans – Logic Oriented and deal with handling client
requests and data processing
• Entity Beand – Strongly coupled with data and deal with data
access and persistence
J2EE Architecture
E-Commerce Scenario
WEB Container J2EE Server

Shopping Cart
Application WEB Container
Catalog Servlet
OrderManager
Application Container Cart Servlet Application Supplier Server
Order StockOrder
WEB Container WEB Container (XML)
Process Servlet Order Manager
ClientApp
Servlet

Static
Pages EJB Container

Order Manager
EJBApplication
WEB Container
Order EJB
Database

• Two distinct parts of the applications


• Shopping Cart: Handles consumer side of the store
• Order Manager: Handles back end processing
J2EE Architecture
E-Commerce
• Cart Application
• Catalog servlet gets product data from the database
• Cart servlet keeps track of the customer purchase
• Process servlet processes the order
• Order Process Application
• Processes customer order
• Checks inventory levels (orders new parts from Suppliers)
• Processes payments
• Sends acknowledgement to the client
Web Architecture Models

Model 1 Model 2
HTTP
Application Layer Protocol

• User applications implement this protocol


• Other protocols implemented by the OS.
• Different applications use different protocols
• Web Servers/Browsers use HTTP
• File Transfer Utilities use FTP
• Electronic Mail applications use SMTP
• Naming Servers use DNS
• Interacts with transport layer to send messages
HTTP
Application Layer Protocol

Socket Socket

TCP/UDP TCP/UDP
with with
Process Buffers Buffers Process
and and
Variables Internet Variables

Controlled by Controlled by Controlled by Controlled by


Application Operating Operating Application
Developer System System Developer

HOST HOST

• Two parameter required for identifying the receiving


process
• Host machine identifier- IP Address (localhost or ip-address)
• Host machine process identifier - Port (80 or 8080 for web
server)
HTTP
HyperText Transfer Protocol
• Lightweight protocol for the web involving a single request
& response for communication
• Provides 8 methods
• Get: Used to request data from server
(By convention get will not change data on server)
• Post: Used to post data to the server
• Head: returns just the HTTP headers for a resource.
• Put: allows you to "put" (upload) a resource (file) on to a webserver
so that it be found under a specified URI.
• Delete: allows you to delete a resource (file).
• Connect:
• Options: To determine the type of requests server will handle
• Trace: Debugging
HTTP
GET and POST
• GET and POST allow information to be sent back to the web
server from a browser
• e.g. when you click on the “submit” button of a form the data in
the form is send back to the server, as "name=value" pairs.
• Choosing GET as the "method" will append all of the data to the
URL and it will show up in the URL bar of your browser.
• The amount of information you can send back using a GET is
restricted as URLs can only be 1024 characters.
• A POST sends the information through a socket back to the
webserver and it won't show up in the URL bar.
• This allows a lot more information to be sent to the server
• The data sent back is not restricted to textual data and it is
possible to send files and binary data such as serialized Java objects.
HTTP
HTTP Headers
• Contains information about client and the request
• Four categories of header information
• General Information: Date, caching information, warnings etc.
• Entity Information: Body of the request or response e.g. MIME
type, length etc.
• Request Information: Information about client e.g. cookies, types of
acceptable responses etc.
• Response Information: Information about server e.g. cookies,
authentication information etc.
• General & Entity information used for both client & server
• Request information included by client
• Response information included by server
HTTP
Protocol
• HTTP is a stateless protocol
• Request/Response occurs across a single network connection
• At the end of the exchange the connection is closed
• This is required to make the server more scalable
• Web Sites maintain persistent authentication so user does
not have to authenticate repeatedly
• While using HTTP persistent authentication is maintained
using a token exchange mechanism
• HTTP 1.1 has a special feature (keep-alive) which allows
clients to use same connection over multiple requests
• Not many servers support this
• Requests have to be in quick succession
HTTP
HTTP Status Codes
• When a server responds to a request it provides a status code
• Web Container automatically handles setting of status codes
• Five categories of status codes
• Informational
• Success
• Redirection
• Client error
• Server error
• Common Status Codes
• 200 – Request was processed normally
• 401 – Unauthorized access
• 403 – Forbidden
• 404 – Requested resource not found on server
• 405 – Method Not allowed
• 500 – Internal server error
HTTP Request Response Processing
JAVA Servlet
• A servlet is a Java class that can be loaded dynamically into and run by a special
web server.
• This servlet-aware web server, is known as servlet container.
• Servlets interact with clients via a request-response model based on HTTP.
• Therefore, a servlet container must support HTTP as the protocol for client
requests and server responses.
• A servlet container also can support similar protocols such as HTTPS (HTTP over
SSL) for secure transactions.
Servlet VS CGI
• A Servlet does not run in a separate process.
• A Servlet stays in memory between requests.
• A CGI program needs to be loaded and started for each CGI request.
• There is only a single instance of a servlet which answers all requests
concurrently.

Perl 1

Browser 1
Browser 1

Browser 2 Web Servlet


Browser 2 Web Perl 2
Server
Server
Browser N
Browser N

Perl N
Benefits of Java Servlets
• Performance
• The performance of servlets is superior to CGI because there is no process creation
for each client request.
• Each request is handled by the servlet container process.
• After a servlet has completed processing a request, it stays resident in memory,
waiting for another request.
• Portability
• Like other Java technologies, servlet applications are portable.
• Rapid development cycle
• As a Java technology, servlets have access to the rich Java library that will help
speed up the development process.
• Robustness
• Servlets are managed by the Java Virtual Machine.
• Don't need to worry about memory leak or garbage collection, which helps you
write robust applications.
• Widespread acceptance
• Java is a widely accepted technology.
Performance Feature
Security Feature
Possible Sources of Loading Servlet
Servlet Life Cycle

Initialization
init()

Service
service()

doGet() Concurrent
doPost() Threads
doDelete() of Execution
doHead()
doTrace()
doOptions()

Destruction
destroy()
Servlet Lifecycle
Servlet Lifecycle
• Multithreaded access (usually default)
• init called first time only (by the container)
• zero to many calls to service
• destroy called
init (ServletConfig)
• call super.init (config), or just use init ()
• Called once
• Prior to any call to service
• Don’t worry about multithreading issues here
• Sometimes used to get resources needed for the lifetime of the servlet
service (req, resp)
• Not usually overridden
• Default impl. determines what request handler to call (based on HTTP
request type), calls it
• Service method will call doGet, doPost, doPut, etc. based on service
type.
• Default implementations provided for doHead, doTrace, doOptions
doPost, doGet, etc.
• doPost (HttpServletRequest req, HttpServletResponse
resp)
• Implement this to handle POSTs
• Read from req, build resp
• Multithreaded access by default (depending on server config)
• Beware instance variables, shared data
• config and context are shared, session is usually safe, req/resp are
not
• Use locks and/or synchronized data structures if shared data is an issue
destroy ()
• called once
• Servlet timeout, servlet reload, container shutdown
• Other threads may still be processing service requests, no further
requests will be processed
• Release resources, write data, etc.
Servlet Model
Servlets
Servlet API
• Contained in two packages
• javax.servlet
• javax.servlet.Http
• Contains 20 interfaces and 16 classes
• Prevalence of interfaces allows servlet
implementation to be customized to container
Servlets
JAVA Servlets
• Javax.servlet package can be extended for
use with any application layer protocol
• http is the most popularly used protocol
• Javax.servlet.http package is extension of the
javax.servlet package for http protocol
• The Servlet spec allows you to implement separate
Java methods implementing each HTTP method in
your subclass of HttpServlet.
• Override the doGet() and/or doPost() method to provide
normal servlet functionality.
• Override doPut() or doDelete() if you want to
implement these methods.
• There's no need to override doOptions() or doTrace().
• The superclass handles the HEAD method all on its own.
Servlets
Javax.servlet Package
• Provides the contract between the servlet/web
application and the web container
• Used for creating protocol independent server
applications
• Servlet interface defines the core of the entire
package
• Other interfaces provide additional services to the
developer
• Contains 12 interfaces
• 7 interfaces implemented by the package
• 5 interfaces implemented by the user
Servlets
Class Diagram
Exception EventListener
ServletException interface

EventObject ServletContextListener

ServletContextEvent
UnavailableException EventListener
interface
ServletContextAttributeEvent ServletContextAttributeListener
interface interface
Servlet ServletConfig
interface
interface
ServletResponse
ServletRequest

Serializable
GenericServlet ServletResponseWrapper
ServletRequestWrapper

interface interface interface OutputStream interface


FilterConfig ServletContext RequestDispatcher ServletOutputStream SingleThreadModel

interface InputStream
FilterChain ServletInputStream
Servlets
Interfaces
• Server implemented interfaces
• ServletConfig
• ServletContext
• ServletRequest
• ServletResponse
• RequestDispatcher
• FilterChain
• FilterConfig
• User implemented interfaces
• Servlet
• ServletContextListener
• ServletContextAttributeListener
• SingleThreadModel
• Filter
Servlets
Classes
• Servlet Classes
• GenericServlet
• ServletContextEvent
• ServletContextAttriubuteEvent
• ServletInputStream
• ServletOutputStream
• ServletRequestWrapper
• ServletResponseWrapper

• Exception Classes
• ServletException
• UnavailableException
Servlets
Generic Servlet Class
• GenericServlet is abstract class that implements
servlet interface
• Requires implementing the service() method
• Servlets normally extend from this class
• Methods
• LifeCycle Methods
• init()
• service()
• destroy()
• Environment Methods
• getServletContext()
• getInitParameter(…)
• getInitParameterNames()
• Utility Methods
• log(…)
Servlets
javax.servlet.http
• Javax.servlet package provides interfaces and
classes to service client requests in protocol
independent manner.
• Javax.servlet.http package supports http-specific
functions.

• Several of the classes are derived from the


javax.servlet packaage
• Some methods from the javax.servlet package are
also used
• Contains
• 8 interfaces
• 7 classes
Servlets
Classes and Interfaces
Interfaces Classes
– Cookie
• HttpSession – HttpServlet
• HttpServletRequest – HttpServletRequestWrapper
– HttpServletResponseWrapper
• HttpServletResponse – HttpSessionBindingEvent
• HttpSessionAttributeLis – HttpSessionEvent
tener – HttpUtils
• HttpSessionActivationLi
stener
• HttpSessionBindingListe
ner
• HttpSessionContext
• HttpSessionListener
Servlets
Class Diagram
GenericServlet EventObject
Serializable
HttpSessionEvent
HttpServlet

ServletRequest HttpSessionBindingEvent
interface
HttpServletRequest Interface
HttpSessionContext
ServletRequestWrapper
Interface
HttpServletRequestWrapper
HttpSession

EventListener
ServletResponse Interface
interface HttpSessionListener
HttpServletResponse
EventListener Interface
HpptSessionAttributeListener
Object ServletRequestWrapper
NoBodyResponse HttpServletRequestWrapper
EventListener Interface
HpptSessionActivationListener
Object ServletOutputStream
HttpUtils NoBodyOutStream
EventListener Interface
HpptSessionBindingListener
Servlets
HttpServlet Class
• Extends the Generic Servlet
• Inherits the init() and destroy methods()
• Overrides the service() method
• Service() method
• Signature: Protected void
service(HttpServletRequest req,
HttpServletResponse res)
• Forwards the request to the appropriate method
• Developer should not normally override this
method
• The developer needs to implement the
methods corresponding to the request
• doGet(), doPost(), doHead(), doPut()
Servlets
HttpServletRequest Interface
• Extends ServletRequest
• Inherited methods from ServletRequest
• getParameterNames()
• getParameter(String name)
• getParameterValues(String name)
• getServerName()
• getServerPort()
• getRequestDispatcher
• New methods defined
• getCookies()
• getHeader()
• getPathInfo()
• getContextPath()
• getQueryString()
Servlets
Writing a Servlet
• Create a servletclass
• extend HttpServlet
• Implement the doGet() or doPost() method
• Both methods accept two parameters
• HttpServletRequest
• HttpServletResponse
• Obtain parameters from HttpServletRequest
Interface using
• getParameter(String name)
• Obtain the writer from the response object
• Process input data and generate output (in html
form) and write to the writer
• Close the writer
Servlets
HttpServletRequest Interface, cont’d.
• Extends ServletResponse
• Inherited methods from ServletResponse
• getoutputStream()
• getWriter(String name)
• flushBuffer()
• setContentType()
• New methods
• encodeURL(String url)
• encodeRedirectURL(String url)
• setDateHeader()
• setStatus()
• ………
Session
• Session simply means a particular interval of time.
• Session Tracking is a way to maintain state (data) of an user. It is also known as
session management in servlet.
• Http protocol is a stateless so we need to maintain state using session tracking
techniques. Each time user requests to the server, server treats the request as the
new request. So we need to maintain the state of an user to recognize to
particular user.
Session Tracking Techniques
There are four techniques used in Session tracking:
• Cookies
• Hidden Form Field
• URL Rewriting
• HttpSession
Cookies
• A cookie is a small piece of information that is persisted between the multiple
client requests.
• A cookie has a name, a single value, and optional attributes such as a comment,
path and domain qualifiers, a maximum age, and a version number.
• By default, each request is considered as a new request. In cookies technique, we
add cookie with response from the servlet. So cookie is stored in the cache of the
browser. After that if request is sent by the user, cookie is added with request by
default. Thus, we recognize the user as the old user.
Cookie
• There are 2 types of cookies in servlets.
• Non-persistent cookie
• It is valid for single session only. It is removed each time when user closes the browser.

• Persistent cookie
• It is valid for multiple session . It is not removed each time when user closes the browser. It is
removed only if user logout or signout.

• Advantage of Cookies
• Simplest technique of maintaining the state.
• Cookies are maintained at client side.

• Disadvantage of Cookies
• It will not work if cookie is disabled from the browser.
• Only textual information can be set in Cookie object.
Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of
useful methods for cookies.
Constructor of Cookie class

Useful Methods of Cookie class


There are given some commonly used methods of the Cookie class.
Constructor Description
Cookie() constructs a cookie.
Cookie(String name, String value) constructs a cookie with a specified name and value.

Method Description
public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.
Returns the name of the cookie. The name cannot be changed after
public String getName()
creation.
public String getValue() Returns the value of the cookie.
public void setName(String name) changes the name of the cookie.
public void setValue(String value) changes the value of the cookie.
For adding cookie or getting the value from the cookie, we need some
methods provided by other interfaces. They are:

public void addCookie(Cookie ck):method of HttpServletResponse interface is


Cookie used to add cookie in response object.

public Cookie[] getCookies():method of HttpServletRequest interface is used


to return all the cookies from the browser.

Add
Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object
response.addCookie(ck);//adding cookie in the response

Delete
Cookie ck=new Cookie("user","");//deleting value of cookie
ck.setMaxAge(0);//changing the maximum age to 0 seconds
response.addCookie(ck);//adding cookie in the response

Fetch:
Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++){
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue
}
Hidden Form Field
• In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining
the state of an user.
• In such case, we store the information in the hidden field and get it from another
servlet. This approach is better if we have to submit form in all the pages and we
don't want to depend on the browser.
• Let's see the code to store value in hidden field.
• <input type="hidden" name="uname" value=“ ”>
• Advantage of Hidden Form Field
• It will always work whether cookie is disabled or not.

• Disadvantage of Hidden Form Field:


• It is maintained at server side.
• Extra form submission is required on each pages.
• Only textual information can be used.
URL Rewriting
• In URL rewriting, we append a token or identifier to the URL of the next Servlet
or the next resource. We can send parameter name/value pairs using the
following format:
• url?name1=value1&name2=value2&??
• A name and a value is separated using an equal = sign, a parameter name/value
pair is separated from another parameter using the ampersand(&). When the
user clicks the hyperlink, the parameter name/value pairs will be passed to the
server. From a Servlet, we can use getParameter() method to obtain a parameter
value.
• Advantage of URL Rewriting
• It will always work whether cookie is disabled or not (browser independent).
• Extra form submission is not required on each pages.

• Disadvantage of URL Rewriting


• It will work only with links.
• It can send Only textual information.
Session
• In such case, container creates a session id for each user. The container uses this
id to identify the particular user. An object of HttpSession can be used to perform
two tasks:
• bind objects
• view and manipulate information about a session, such as the session identifier, creation time,
and last accessed time.
Session
• The HttpServletRequest interface provides two methods to get the object
of HttpSession:
• public HttpSession getSession():Returns the current session associated with this request, or
if the request does not have a session, creates one.
• public HttpSession getSession(boolean create):Returns the current HttpSession associated
with this request or, if there is no current session and create is true, returns a new
session.

• Commonly used methods of HttpSession interface


• public String getId():Returns a string containing the unique identifier value.
• public long getCreationTime():Returns the time when this session was created, measured
in milliseconds since midnight January 1, 1970 GMT.
• public long getLastAccessedTime():Returns the last time the client sent a request
associated with this session, as the number of milliseconds since midnight January 1,
1970 GMT.
• public void invalidate():Invalidates this session then unbinds any objects bound to it.
Event and Listener
• Events are basically occurrence of something. Changing the state of an object is
known as an event.
• We can perform some important tasks at the occurrence of these exceptions, such
as counting total and current logged-in users, creating tables of the database at
time of deploying the project, creating database connection object etc.
• There are many Event classes and Listener interfaces in the javax.servlet and
javax.servlet.http packages.

The event classes are as follows: The event interfaces are as follows:
ServletRequestEvent ServletRequestListener
ServletContextEvent ServletRequestAttributeListener
ServletRequestAttributeEvent ServletContextListener
ServletContextAttributeEvent ServletContextAttributeListener
HttpSessionEvent HttpSessionListener
HttpSessionBindingEvent HttpSessionAttributeListener
HttpSessionBindingListener
HttpSessionActivationListener
Filter
• A filter is an object that is invoked at the preprocessing and postprocessing of a
request.
• It is mainly used to perform filtering tasks such as conversion, logging,
compression, encryption and decryption, input validation etc.
• The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we
remove the entry of filter from the web.xml file, filter will be removed
automatically and we don't need to change the servlet.
• So maintenance cost will be less.
Filter
• Usage of Filter
• recording all incoming requests
• logs the IP addresses of the computers from which the requests originate
• conversion
• data compression
• encryption and decryption
• input validation etc.

• Advantage of Filter
• Filter is pluggable.
• One filter don't have dependency onto another resource.
• Less Maintenance
Filter API
• Like servlet filter have its own API. The javax.servlet package contains the three
interfaces of Filter API.
• Filter
• FilterChain
• FilterConfig
Method Description
• Filter Interface public void init(FilterConfig
init() method is invoked only
once. It is used to initialize
config)
• Filter Chain Interface the filter.
doFilter() method is invoked
public void
every time when user request
doFilter(HttpServletRequest
to any resource, to which the
request,HttpServletResponse
filter is mapped.It is used to
response, FilterChain chain)
perform filtering tasks.
This is invoked only once
public void destroy() when filter is taken out of the
service.
Thanks
Hibernate
An Object-Relational mapping framework
for object persistence
Problem area
• When working with object-oriented systems,
there’s a mismatch between the object model and
the relational database
• How do we map one to the other?

public class Student


{
private String name;
private String
address;
private Set<Course>
courses; private
Set<Degree> degrees;
}

Java object with Relational database


properties and with tables and
associations columns
Problem area

• How to map associations between objects?


– References are directional, foreign keys not
– Foreign keys can
’ t represent many-to-many
associations

public class Student


N N Java
{
Student Degree private Collection<Degree>
degrees;
...

STUDENT DEGREE Relational


student_i degree_i
database /
d name d type
address name SQL
degree_id
Technology
(Domain
• Why relational databases? model)
– Flexible and robust approach to
data management Studen Cours
– De-facto standard in software t e
development
Degree
• Why object-oriented models?
– Business logic can be
implemented in Java (opposed to
stored procedures)
– Allows for use of design patterns
and concepts like polymorphism
– Improves code reuse and maintainability

• Demand for mapping interaction!


(Database)
Approaches to ORM
• Write SQL conversion methods by hand using JDBC
– Tedious and requires lots of code
– Extremely error-prone
– Non-standard SQL ties the application to specific databases
– Vulnerable to changes in the object model
– Difficult to represent associations between objects

public void addStudent( Student student )


{ Student Course
String sql = ”INSERT INTO student ( name, address ) VALUES (
’” + student.getName() + ”’, ’” + student.getAddress() + ”’ )”;

// Initiate a Connection, create a Statement, and execute the


} query Degree
Approaches to ORM

• Use Java serialization – write application state to


a file
– Can only be accessed as a whole
– Not possible to access single objects

• Object oriented database systems


– No complete query language implementation exists
– Lacks necessary features
The preferred solution

• Use a Object-Relational Mapping System (eg.


Hibernate)
• Provides a simple API for storing and retrieving
Java objects directly to and from the database
• Non-intrusive: No need to follow specific rules or
design patterns
• Transparent: Your object model is unaware

Student Course ORM / Hibernate

Magic
Degree
happens here!

(Domain (Relational
model) database)
What Hibernate Does
• Object - Relational mapping
• Transparent persistence & retrieval of objects
• Persistence of associations and collections
• Guaranteed uniqueness of an object (within a session)
What Hibernate Does
• Object - Relational mapping
• Transparent persistence & retrieval of objects
• Persistence of associations and collections
• Guaranteed uniqueness of an object (within a session)
Hibernate
• Hibernate is an Object-Relational Mapping(ORM) solution
for JAVA and it raised as an open source persistent
framework created by Gavin King in 2001. It is a powerful,
high performance Object-Relational Persistence and Query
service for any Java Application.
• Hibernate maps Java classes to database tables and from
Java data types to SQL data types and relieve the developer
from 95% of common data persistence related
programming tasks.
• Hibernate sits between traditional Java objects and database
server to handle all the work in persisting those objects
based on the appropriate O/R mechanisms and patterns.
Advantages
• Hibernate takes care of mapping Java classes to database tables
using XML files and without writing any line of code.
• Provides simple APIs for storing and retrieving Java objects
directly to and from the database.
• If there is change in Database or in any table then the only need
to change XML file properties.
• Abstract away the unfamiliar SQL types and provide us to work
around familiar Java Objects.
• Hibernate does not require an application server to operate.
• Manipulates Complex associations of objects of your database.
• Minimize database access with smart fetching strategies.
• Provides Simple querying of data.
Architecture
Configuration
• Configuration Object:
• The Configuration object is the first Hibernate object you
create in any Hibernate application and usually created only
once during application initialization. It represents a
configuration or properties file required by the Hibernate.
The Configuration object provides two keys components:
• Database Connection: This is handled through one or more
configuration files supported by Hibernate. These files are
hibernate.properties and hibernate.cfg.xml.
• Class Mapping Setup
• This component creates the connection between the Java
classes and database tables..
SessionFactory Object

• Configuration object is used to create a SessionFactory object


which inturn configures Hibernate for the application using
the supplied configuration file and allows for a Session object
to be instantiated. The SessionFactory is a thread safe object
and used by all the threads of an application.
• The SessionFactory is heavyweight object so usually it is
created during application start up and kept for later use.
You would need one SessionFactory object per database
using a separate configuration file. So if you are using
multiple databases then you would have to create multiple
SessionFactory objects.
Session Object:
• A Session is used to get a physical connection with a
database. The Session object is lightweight and designed to
be instantiated each time an interaction is needed with the
database. Persistent objects are saved and retrieved through
a Session object.
• The session objects should not be kept open for a long time
because they are not usually thread safe and they should be
created and destroyed them as needed.
Transaction Object:
• A Transaction represents a unit of work with the database
and most of the RDBMS supports transaction functionality.
Transactions in Hibernate are handled by an underlying
transaction manager and transaction (from JDBC or JTA).
• This is an optional object and Hibernate applications may
choose not to use this interface, instead managing
transactions in their own application code.
Query and Criteria
• Query Object:
• Query objects use SQL or Hibernate Query Language (HQL)
string to retrieve data from the database and create objects.
A Query instance is used to bind query parameters, limit
the number of results returned by the query, and finally to
execute the query.
• Criteria Object:
• Criteria object are used to create and execute object
oriented criteria queries to retrieve objects.
Session
• A Session is used to get a physical connection with a database. The
Session object is lightweight and designed to be instantiated each time
an interaction is needed with the database. Persistent objects are saved
and retrieved through a Session object.
• The session objects should not be kept open for a long time because they
are not usually thread safe and they should be created and destroyed
them as needed. The main function of the Session is to offer create, read
and delete operations for instances of mapped entity classes. Instances
may exist in one of the following three states at a given point in time:
• transient: A new instance of a persistent class which is not associated
with a Session and has no representation in the database and no
identifier value is considered transient by Hibernate.
• persistent: You can make a transient instance persistent by associating it
with a Session. A persistent instance has a representation in the
database, an identifier value and is associated with a Session.
• detached: Once we close the Hibernate Session, the persistent instance
will become a detached instance.
O-R Mapping
Collection Mapping
Collection type Mapping and Description
This is mapped with a <set> element and
java.util.Set
initialized with java.util.HashSet
This is mapped with a <set> element and
initialized with java.util.TreeSet. The sort
java.util.SortedSet
attribute can be set to either a comparator or
natural ordering.
This is mapped with a <list> element and
java.util.List
initialized with java.util.ArrayList
This is mapped with a <bag> or <ibag> element
java.util.Collection
and initialized with java.util.ArrayList
This is mapped with a <map> element and
java.util.Map
initialized with java.util.HashMap
This is mapped with a <map> element and
initialized with java.util.TreeMap. The sort
java.util.SortedMap
attribute can be set to either a comparator or
natural ordering.
Association Mappings

Mapping type Description


Mapping many-to-one relationship using
Many-to-One
Hibernate
Mapping one-to-one relationship using
One-to-One
Hibernate
Mapping one-to-many relationship using
One-to-Many
Hibernate
Mapping many-to-many relationship using
Many-to-Many
Hibernate
Component Mappings
• It is very much possible that an Entity class can have a
reference to another class as a member variable. If the
referred class does not have it's own life cycle and
completely depends on the life cycle of the owning entity
class, then the referred class hence therefore is called as the
Component class.
• The mapping of Collection of Components is also possible in
a similar way just as the mapping of regular Collections
with minor configuration differences.
HQL
• Hibernate Query Language (HQL) is an object-oriented
query language, similar to SQL, but instead of operating on
tables and columns, HQL works with persistent objects and
their properties. HQL queries are translated by Hibernate
into conventional SQL queries which in turns perform action
on database.
• Although you can use SQL statements directly with
Hibernate using Native SQL but I would recommend to use
HQL whenever possible to avoid database portability hassles,
and to take advantage of Hibernate's SQL generation and
caching strategies.
• Keywords like SELECT , FROM and WHERE etc. are not case
sensitive but properties like table and column names are
case sensitive in HQL.
FROM
• You will use FROM clause if you want to load a complete persistent objects
into memory. Following is the simple syntax of using FROM clause:

• String hql = "FROM Employee";


• Query query = session.createQuery(hql);
• List results = query.list();

• If you need to fully qualify a class name in HQL, just specify the package and
class name as follows:

• String hql = "FROM com.hibernatebook.criteria.Employee";


• Query query = session.createQuery(hql);
• List results = query.list();
AS
• The AS clause can be used to assign aliases to the classes in your HQL queries,
specially when you have long queries. For instance, our previous simple example
would be the following:

• String hql = "FROM Employee AS E";

• Query query = session.createQuery(hql);

• List results = query.list();

• The AS keyword is optional and you can also specify the alias directly after the class
name, as follows:

• String hql = "FROM Employee E";

• Query query = session.createQuery(hql);

• List results = query.list();


SELECT
• The SELECT clause provides more control over the result set
than the from clause. If you want to obtain few properties
of objects instead of the complete object, use the SELECT
clause. Following is the simple syntax of using SELECT clause
to get just first_name field of the Employee object:

• String hql = "SELECT E.firstName FROM Employee E";


• Query query = session.createQuery(hql);
• List results = query.list();

• It is notable here that Employee.firstName is a property of


Employee object rather than a field of the EMPLOYEE table.
WHERE
• If you want to narrow the specific objects that are returned
from storage, you use the WHERE clause. Following is the
simple syntax of using WHERE clause:

• String hql = "FROM Employee E WHERE E.id = 10";


• Query query = session.createQuery(hql);
• List results = query.list();
ORDER BY
• To sort your HQL query's results, you will need to use the ORDER BY clause. You can order the
results by any property on the objects in the result set either ascending (ASC) or descending
(DESC). Following is the simple syntax of using ORDER BY clause:

• String hql = "FROM Employee E WHERE E.id > 10 ORDER BY E.salary DESC";

• Query query = session.createQuery(hql);

• List results = query.list();

• If you wanted to sort by more than one property, you would just add the additional properties to
the end of the order by clause, separated by commas as follows:

• String hql = "FROM Employee E WHERE E.id > 10 " +

• "ORDER BY E.firstName DESC, E.salary DESC ";

• Query query = session.createQuery(hql);

• List results = query.list();


Group By
• This clause lets Hibernate pull information from the
database and group it based on a value of an attribute and,
typically, use the result to include an aggregate value.
Following is the simple syntax of using GROUP BY clause:

• String hql = "SELECT SUM(E.salary), E.firtName FROM


Employee E " +
• "GROUP BY E.firstName";
• Query query = session.createQuery(hql);
• List results = query.list();
Named Parameter
• Hibernate supports named parameters in its HQL queries.
This makes writing HQL queries that accept input from the
user easy and you do not have to defend against SQL
injection attacks. Following is the simple syntax of using
named parameters:

• String hql = "FROM Employee E WHERE E.id =


:employee_id";
• Query query = session.createQuery(hql);
• query.setParameter("employee_id",10);
• List results = query.list();
UPADATE
• Bulk updates are new to HQL with Hibernate 3, and deletes work differently in
Hibernate 3 than they did in Hibernate 2. The Query interface now contains a
method called executeUpdate() for executing HQL UPDATE or DELETE statements.

• The UPDATE clause can be used to update one or more properties of an one or
more objects. Following is the simple syntax of using UPDATE clause:

• String hql = "UPDATE Employee set salary = :salary " +

• "WHERE id = :employee_id";

• Query query = session.createQuery(hql);

• query.setParameter("salary", 1000);

• query.setParameter("employee_id", 10);

• int result = query.executeUpdate();

• System.out.println("Rows affected: " + result);


DELETE
• The DELETE clause can be used to delete one or more
objects. Following is the simple syntax of using DELETE
clause:

• String hql = "DELETE FROM Employee " +


• "WHERE id = :employee_id";
• Query query = session.createQuery(hql);
• query.setParameter("employee_id", 10);
• int result = query.executeUpdate();
• System.out.println("Rows affected: " + result);
INSERT INTO
• HQL supports INSERT INTO clause only where records can
be inserted from one object to another object. Following is
the simple syntax of using INSERT INTO clause:

• String hql = "INSERT INTO Employee(firstName, lastName,


salary)" +
• "SELECT firstName, lastName, salary FROM old_employee";
• Query query = session.createQuery(hql);
• int result = query.executeUpdate();
• System.out.println("Rows affected: " + result);
AGGREGATION FUNCTION

S.N. Functions Description


The average of a property's
1 avg(property name)
value
count(property name The number of times a
2
or *) property occurs in the results
The maximum value of the
3 max(property name)
property values
The minimum value of the
4 min(property name)
property values
The sum total of the property
5 sum(property name)
values
Pagination using Query

S.N. Method & Description


Query setFirstResult(int startPosition) This method
1 takes an integer that represents the first row in your
result set, starting with row 0.
Query setMaxResults(int maxResult) This method tells
2 Hibernate to retrieve a fixed number maxResults of
objects.
Example of Retrieving an Object
// use the existing session factory
Session session = sessionFactory.openSession();
// query Event objects for "Java Days"
Transaction tx = session.beginTransaction();
Query query = session.createQuery(
"from Event where name='Java Days'" );
List events = query.list( );
out.println("Upcoming Java Days events: ");
for( Object obj : events ) {
Event event = (Event) obj;
String name = event.getName( );
Location loc = event.getLocation( );
...
}
tx.commit( );
Using Named Parameters in Query
// use the existing session factory
Session session = sessionFactory.openSession();
// Hibernate Query Language (HQL) can use named params
Query query = session.createQuery(
"from Event where name=:name");
query.setParameter( "name", "Java Days");
List events = query.list( );

out.println("Upcoming Java Days events: ");


for( Object obj : events ) {
Event event = (Event) obj;
String name = event.getName( );
Location loc = event.getLocation( );
...

You might also like