Professional Documents
Culture Documents
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.
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();
}
}
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.
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);
}
}
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);
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();
}
}
-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();
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();}}
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 {
}
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();
}
}
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();
}}}
-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());
}
}
The server reads the string, finds number of words, characters and digits of received
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");
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));
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.
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
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.
15
JDBC Driver
• API: Set of interfaces independent of the RDBMS
• Driver: RDBMS-specific implementation of API
interfaces e.g. Oracle, DB2, MySQL, etc.
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
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
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
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
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
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
38
JDBC Package
java.sql
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");
Connection conn=
DriverManager.getConnection(URL,USER_NM,PASS);
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();
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”);
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
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”);
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.
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 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.
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");
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
3. Update methods Used to update the data in the columns of the current
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.
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.
74
Types of ResultSet
Type Description
ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the
result set. Default
Type
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.
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.
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.
► 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
► 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.
► 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.
► 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.
2) JSP Initialization
► When a container loads a JSP it invokes the jspInit() method before servicing any requests.
// 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 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.
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.
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 %>
<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 code written inside the jsp declaration tag is placed outside the service() method of auto
generated servlet.
► 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
► 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
► 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.
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
► 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
► The Java developer can use this object to set, get or remove attribute or to get session information.
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
► It is written as:
Object page=this;
► For example:
Since, it is of type Object it is less used because you can use this object directly in jsp.
► 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.
1. page directive
2. include directive
3. taglib directive
► The page directive defines attributes that apply to an entire JSP page.
► 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.
<html>
<body>
</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>
</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 buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP page.
<html>
<body>
</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.
► If you want to control this behaviour of JSP page, you can use isThreadSafe attribute of page
directive.
► 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.
► 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.
index.jsp
<html>
<body>
</body>
</html>
JSP directives
X) isErrorPage
► The isErrorPage attribute is used to declare that the current page is the error page.
myerrorpage.jsp
<html>
<body>
</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.
► Code Reusability
<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.
</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
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.
</jsp:include>
JSP action tags
2) jsp:include action tag
Java Bean- A Java Bean is a java class that should follow following conventions:
► It should be Serializable.
► It should provide methods to set and get the values of the properties, known as getter and
setter methods.
► 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
2. welocme.jsp file that sets the incoming values to the bean object and prints the one
value
► 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.
codebase= "directoryNameOfClassFile"
</jsp:plugin>
JSP action tags
5) jsp:plugin action tag
</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.
► Cookies
► 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.
► 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
7. setMaxAge(int) : Sets maximum age of the cookie. A zero value causes the cookie to be deleted.
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.
► 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.
► 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.
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
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.
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>
</head>
<body>
</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:
► 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:
► The JSTL XML tags provide a JSP-centric way of creating and manipulating XML documents.
► 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.
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
File: MyTagHandler.java
package com.example.myproject
try{
}catch(Exception e){System.out.println(e);}
<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
► 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:
► If it is true, EL expressions are ignored when they appear in static text or tag
attributes.
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}
</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:
► 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.
<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
View Model
Controller
Request & Relay data
Request
Create or Apply Request Process
Restore View Values Validations
Response
Render Invoke Update Model
Response Application Values
Request
Create or Apply Request Process
Restore View Values Validations
Response
Render Invoke Update Model
Response Application Values
Request
Create or Apply Request Process
Restore View Values Validations
Response
Render Invoke Update Model
Response Application Values
Request
Create or Apply Request Process
Restore View Values Validations
Response
Render Invoke Update Model
Response Application Values
Request
Create or Apply Request Process
Restore View Values Validations
Response
Render Invoke Update Model
Response Application Values
Request
Create or Apply Request Process
Restore View Values Validations
Response
Render Invoke Update Model
Response Application Values
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>
Syntax
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:p="http://primefaces.org/ui ">
• 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:
• 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 );
}
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)
• 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
• 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
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.
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
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 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:formatDate> Formats a date and/or time using the supplied styles and pattern
<fmt:setTimeZone> Stores the given time zone in the time zone configuration variable
Tag Description
<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.
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: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.
<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>
</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
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
• 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.
• 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.
• 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:
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
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
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
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
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
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
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.
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.
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.
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
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{
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
Statement stmt=con.createStatement();
con.close();
}
}
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();
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
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
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");
ResultSetMetaData rsmd=rs.getMetaData();
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();
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");
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");
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();
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
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
Model 1 Model 2
HTTP
Application Layer Protocol
Socket Socket
TCP/UDP TCP/UDP
with with
Process Buffers Buffers Process
and and
Variables Internet Variables
HOST HOST
Perl 1
Browser 1
Browser 1
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 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.
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
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:
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.
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?
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
• If you need to fully qualify a class name in HQL, just specify the package and
class name as follows:
• The AS keyword is optional and you can also specify the alias directly after the class
name, as follows:
• String hql = "FROM Employee E WHERE E.id > 10 ORDER BY E.salary DESC";
• 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:
• 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:
• "WHERE id = :employee_id";
• query.setParameter("salary", 1000);
• query.setParameter("employee_id", 10);