Upload
lydan
View
214
Download
0
Embed Size (px)
Citation preview
Prashant Maheta, CE Department | 2160707
1. Discuss the URL and URLConnection class with their use in network programming.
The URLConnection class is used to connect to a website or resource on a network and get all the details of resource on a website. The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It points to a resource on the World Wide Web. For exam
http://www.darshan.ac.in A URL contains many information:
Protocol: In this case, http is the protocol.
Server name or IP Address:
Port Number: It is an optional attribute. If we write http//ww.80 is the port number. If port number is not mentioned in the URL, it returns
File Name or directory name: In this case, index. Using OpenConnection() method of the URL object, we can contact with the resowebsite is established :
import java.io.*; import java.net.*; import java.util.*;
class Details { public static void main(String args[ ]) throws Exception //pass the site url to URL object URL obj = new //open a connection with the site on Internet URLConnection conn = obj.openConnection();
//display the date System.out.println("Date: "+ new Date(conn.getDate())); //display how many bytes the index.html pag int l = conn.getContentLength(); System.out.println("Length of content: "+ l);
if(l == 0) System.out.println("Content not available"); return; }
Unit 1 – Java Network Programming
2160707– Advanced Java
iscuss the URL and URLConnection class with their use in network programming.
class is used to connect to a website or resource on a network and get all the details of resource on a website.
class represents an URL. URL is an acronym for Uniform Resource Locator. It points to a resource on the World Wide Web. For example:
darshan.ac.in
contains many information:
In this case, http is the protocol.
Server name or IP Address: In this case, www.darshan.ac.in is the server name.
It is an optional attribute. If we write http//ww.darshan.ac.in80 is the port number. If port number is not mentioned in the URL, it returns
File Name or directory name: In this case, index.jsp is the file name.
Using OpenConnection() method of the URL object, we can contact with the reso
public static void main(String args[ ]) throws Exception { //pass the site url to URL object URL obj = new URL("http://www.microsoft.com");
//open a connection with the site on Internet URLConnection conn = obj.openConnection();
//display the date System.out.println("Date: "+ new Date(conn.getDate()));
//display how many bytes the index.html page has int l = conn.getContentLength(); System.out.println("Length of content: "+ l);
{ System.out.println("Content not available"); return;
Network Programming
1
iscuss the URL and URLConnection class with their use in
class is used to connect to a website or resource on a network and get all
class represents an URL. URL is an acronym for Uniform Resource Locator. It
is the server name.
darshan.ac.in:80/index/ 80 is the port number. If port number is not mentioned in the URL, it returns -1.
Using OpenConnection() method of the URL object, we can contact with the resource on a
Prashant Maheta, CE Department | 2160707
else { int ch; InputStream in = conn.getInputStream(); //display the int i = 0;
while((ch = in.read())!=
} } }
2. Explain Socket, ServerSocket, InetAddress classes. Write a java program to find an IP address of the machine on which the program runs.
Socket :
For implementing client side sockets this class is useful. It accepts two arguments ipaddress and port no.Socket s = new Socket(“localhost”,777)
ServerSocket :
For implementing server side sockets this class is useful. It accepts one no. ServerSocket ss = new ServerSocket(777)
InetAddress :
The java.net package provides an Address, some of the methods are : getLocalHost() method will return the object of InetAddress ClassgetHostAddress() method then will return
Example : GetIPAddress.java
import java.net.*; import java.io.*;
public class GetIPAddress {
public static void main(String [] args) try {
InetAddress thisIp =InetAddress.getLocalHost();
Unit 1 – Java Network Programming
2160707– Advanced Java
InputStream in = conn.getInputStream();
//display the content of the index.html page int i = 0; while((ch = in.read())!= -1)
System.out.print((char)ch);
Explain Socket, ServerSocket, InetAddress classes. Write a java program to find an IP address of the machine on which the
For implementing client side sockets this class is useful. It accepts two arguments ipaddress and port no. Socket s = new Socket(“localhost”,777)
For implementing server side sockets this class is useful. It accepts one
ServerSocket ss = new ServerSocket(777)
The java.net package provides an InetAddress class that allows you to retrieve the IP ddress, some of the methods are :
method will return the object of InetAddress Class method then will return the IP Address of the Local System.
Example : GetIPAddress.java :
public static void main(String [] args) {
InetAddress thisIp =InetAddress.getLocalHost();
Network Programming
2
Explain Socket, ServerSocket, InetAddress classes. Write a java program to find an IP address of the machine on which the
For implementing client side sockets this class is useful. It accepts two arguments
For implementing server side sockets this class is useful. It accepts one argument port
class that allows you to retrieve the IP
the IP Address of the Local System.
Prashant Maheta, CE Department | 2160707
System.out.println("IP Address of this System:"+thisIp.getHostAddress()); } catch(Exception e) { e.printStackTrace(); } } }
3. One-way Communication using Connection(TCP)
Example : TCPServerOneWay.Java
import java.io.*; import java.net.*; class TCPServerOneWay { public static void main(String args[ ]) //Create a server socket with some port ServerSocket ss = new ServerSocket(777); //let the server wait till a client accepts connection Socket s = ss.accept(); System.out.println("Connection established"); //attach output stream to the server socket OutputStream obj = s. //attach print stream to send data to the socket PrintStream ps = new PrintStream(obj); //send 2 strings to the client String str = "Hello client"; ps.println(str); ps.println("Bye"); //close connection by closing ps.close(); ss.close(); s.close(); } }
Unit 1 – Java Network Programming
2160707– Advanced Java
System.out.println("IP Address of this System:"+thisIp.getHostAddress());
catch(Exception e) { e.printStackTrace();
Communication using Connection-Oriented Prot
Example : TCPServerOneWay.Java
public static void main(String args[ ]) throws Exception { //Create a server socket with some port number ServerSocket ss = new ServerSocket(777);
//let the server wait till a client accepts connection Socket s = ss.accept(); System.out.println("Connection established");
//attach output stream to the server socket OutputStream obj = s.getOutputStream();
//attach print stream to send data to the socket PrintStream ps = new PrintStream(obj);
//send 2 strings to the client String str = "Hello client"; ps.println(str); ps.println("Bye");
//close connection by closing the streams and sockets
Network Programming
3
System.out.println("IP Address of this System:"+thisIp.getHostAddress());
Oriented Protocol
Prashant Maheta, CE Department | 2160707
Example : TCPClientOneWay.Java
import java.io.*; import java.net.*; class TCPClientOneWay { public static void main(String args[ ]) throws Exception //create client socket Socket s = new Socket("localhost", 777); //to read data coming from server, attach InputStream to the socket InputStream obj = s.getInputStream(); //to read data from the socket into the client, use BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(obj)); //receive strings String str; while((str = br.readLine()) != null)
System.out.println("From server: "+str); //close connection by closing the streams and sockets br.close(); s.close(); } }
4. Two-way Communication using Connection(TCP)
Example : TCPServerTwo
import java.io.*; import java.net.*; class Server2{ public static void main(String args[ ]) //Create server socket ServerSocket ss = new ServerSocket(888);
Unit 1 – Java Network Programming
2160707– Advanced Java
OneWay.Java
public static void main(String args[ ]) throws Exception { //create client socket with same port number Socket s = new Socket("localhost", 777);
//to read data coming from server, attach InputStream to the socketInputStream obj = s.getInputStream();
//to read data from the socket into the client, use BufferedReaderBufferedReader br = new BufferedReader(new InputStreamReader(obj));
//receive strings
while((str = br.readLine()) != null) System.out.println("From server: "+str);
//close connection by closing the streams and sockets
way Communication using Connection-Oriented Protocol
TwoWay.Java
public static void main(String args[ ]) throws Exception {
ServerSocket ss = new ServerSocket(888);
Network Programming
4
//to read data coming from server, attach InputStream to the socket
//to read data from the socket into the client, use BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(obj));
Oriented Protocol
Prashant Maheta, CE Department | 2160707
//Create server socket ServerSocket ss = new ServerSocket(888); //connect it to client socket Socket s = ss.accept(); System.out.println("Connection established"); //to send data to the client PrintStream ps = new PrintStream(s.getOutputStream());
//to read data coming from the client BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); //to read data from the key board BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
//server executes continuously while(true) { String str,str1;
//repeat as long as client does not send null string
while((str = br.readLine()) != null) {
}
//close connection ps.close(); br.close(); kb.close(); ss.close(); s.close(); System.exit(0); //terminate application } //end of while } }
Unit 1 – Java Network Programming
2160707– Advanced Java
//Create server socket ServerSocket ss = new ServerSocket(888);
//connect it to client socket Socket s = ss.accept(); System.out.println("Connection established");
//to send data to the client PrintStream ps = new PrintStream(s.getOutputStream());
//to read data coming from the client BufferedReader br = new BufferedReader(new
InputStreamReader(s.getInputStream()));
//to read data from the key board BufferedReader kb = new BufferedReader(new
InputStreamReader(System.in)); //server executes continuously
String str,str1;
//repeat as long as client does not send null string
while((str = br.readLine()) != null) {
System.out.println(str);
str1 = kb.readLine();
ps.println(str1); //send to client
//close connection ps.close(); br.close(); kb.close(); ss.close(); s.close(); System.exit(0); //terminate application
} //end of while
Network Programming
5
Prashant Maheta, CE Department | 2160707
5. One-way Communication using Connection
Example : UDPServerEx.Java
//A server that sends a messages to the clientimport java.net.*; class UDPServerEx{
public static DatagramSocket mySocket;public static byte myBuffer[]=new byte[2000];public static void serverMethod() throws Exception{
int position=0;while(true){
int charData=System.in.read();switch(charData){
} }
} public static void main(String args[]) throws Exception
System.out.println("Please enter some text here");mySocket=new DatagramSocket(888);serverMethod();
} }
Unit 1 – Java Network Programming
2160707– Advanced Java
way Communication using Connection-Less Protocol (UDP)
Example : UDPServerEx.Java
//A server that sends a messages to the client
public static DatagramSocket mySocket; myBuffer[]=new byte[2000];
public static void serverMethod() throws Exception{ int position=0;
int charData=System.in.read(); switch(charData){
case -1: System.out.println("The execution of the server has been terminated"); return;
case '\r': break;
case '\n': mySocket.send(new DatagramPacket(myBuffer,position,InetAddress.getLocalHost(),777)); position=0; break;
default: myBuffer[position++]=(byte) charData;
public static void main(String args[]) throws Exception { System.out.println("Please enter some text here"); mySocket=new DatagramSocket(888); serverMethod();
Network Programming
6
Less Protocol (UDP)
System.out.println("The execution of the server has been
DatagramPacket(myBuffer,position,InetAddress.getLocalH
Prashant Maheta, CE Department | 2160707
Example : UDPClient.Java
//UDPClient - receives and displays messages sent from the serverimport java.net.*; class UDPClient {
public static DatagramSocket mySocket;public static byte myBuffer[]=new byte[2000]; public static void clientMethod() throws Exception
while(true) { DatagramPacket dataPacket=newDatagramPacket(myBuffer,myBuffer.length); mySocket.receive(dataPacket);System System.out.println(newString(dataPacket.getData(),0,dataPacket.getLength()));
} } public static void main(String args[]) throws Exception
System.out.println("You need to press CTRL+C in order to quit");mySocket=newclientMethod();
} }
6. Protocol Handler & Content Handler
When Java Interacts with Network Programming, then it is categorized into two distinct
domains called :
o Protocol Handler
o Content Handler
Protocol Handler is required to take care of certain
on receipt of data, acknowledging that the data has been received
Content Handler is required to :understand
Working of these two categories is totally different and independent. That means
protocol does not care about the type of downloading data.downloaded does not have to worry about the protocol
Unit 1 – Java Network Programming
2160707– Advanced Java
.Java
receives and displays messages sent from the server
static DatagramSocket mySocket; public static byte myBuffer[]=new byte[2000];
public static void clientMethod() throws Exception {
DatagramPacket dataPacket=new DatagramPacket(myBuffer,myBuffer.length);
mySocket.receive(dataPacket); System.out.println("Message Recieved :");
System.out.println(new String(dataPacket.getData(),0,dataPacket.getLength()));
public static void main(String args[]) throws Exception { System.out.println("You need to press CTRL+C in order to quit");mySocket=new DatagramSocket(777); clientMethod();
& Content Handler
When Java Interacts with Network Programming, then it is categorized into two distinct
Protocol Handler Content Handler
is required to take care of certain issues: - Generating client requestreceipt of data, acknowledging that the data has been received.
is required to :- Convert the raw data in the format which Java can
wo categories is totally different and independent. That means protocol does not care about the type of downloading data. Similarly data getting downloaded does not have to worry about the protocol.
Network Programming
7
String(dataPacket.getData(),0,dataPacket.getLength()));
System.out.println("You need to press CTRL+C in order to quit");
When Java Interacts with Network Programming, then it is categorized into two distinct
Generating client request,
Convert the raw data in the format which Java can
wo categories is totally different and independent. That means Similarly data getting
Prashant Maheta, CE Department | 2160707
Protocol Handler :
Protocol Handler can be defined
protocols. Various protocols supported by JAVA are http,ftp,file.mailto etc. java.net is the package for all this magic. In java.net package there are four important classes defiend
URL – it is the main URLStreamHandler URLConnection
URLStreamHandlerFactory
Content Handler :
What is the Content ? When we request for viewing some file on
then that particular file will be displayed in the browser. Sometimes we can request for viewing some gif and jpg file and the browser displays it. Sometimes we want to see some pdf or ppt file, then browser
external program. Actually the items which get displayed by your browser are reffered to as contents.
Each time when browser wants to handle different contents, plugplug-ins that are required to handle various contenhandler.
Unit 1 – Java Network Programming
2160707– Advanced Java
Protocol Handler can be defined as a collection of classes which know how to handle
Various protocols supported by JAVA are http,ftp,file.mailto etc. java.net is the package for all this magic. In java.net package there are four important classes defiend
it is the main class URLStreamHandler – it is an abstract class URLConnection – it is an abstract class (getInputStream, getOutputStream)URLStreamHandlerFactory – it is an interface
What is the Content ? When we request for viewing some file on the web browser and if it is a simple HTML file then that particular file will be displayed in the browser. Sometimes we can request for viewing some gif and jpg file and the browser displays it.Sometimes we want to see some pdf or ppt file, then browser
Actually the items which get displayed by your browser are reffered to as contents.
Each time when browser wants to handle different contents, plug-ins that are required to handle various contents on web browser are called content
Network Programming
8
as a collection of classes which know how to handle
it is an abstract class (getInputStream, getOutputStream)
the web browser and if it is a simple HTML file
Sometimes we can request for viewing some gif and jpg file and the browser displays it. Sometimes we want to see some pdf or ppt file, then browser takes help of some
Actually the items which get displayed by your browser are reffered to as contents.
-ins are used. These ts on web browser are called content-
Prashant Maheta, CE Department | 2160707
1. Explain various types of JDBC drivers and comment on selection of driver.
JDBC Drivers Types:
JDBC driver implementations vary because of the wide variety of operating systems and hardware platforms in which Java operates.
The different types of drivers available in JDBC are listed in following table:
JDBC driver type
Type-1 (JDBC-ODBC Bridge)
Type-2 Driver (Native)
Type-3 Driver (Middleware)
Type-3 Driver (Pure Java)
Type-1 Driver (JDBC-ODBC Bridge) Type-1 driver act as a
JDBC-ODBC bridge driver.
This driver also included in the java2 SDK within the sun.jdbc.odbc package.
This driver converts jdbc calls into odbc calls and redirect the request to odbc driver.
Advantages :
It is represent the single driver
Allow to communicate with all database supported by odbc driver
It is vendor independent driver
Disadvantages:
Decrease the execution speed
Dependent on the odbc driver
Require odbc binary code or odbc client
Uses java native interface to make odbc call
Type-2 Driver (Native) : JDBC call can be converted into the database vendor specific native call with the help of
type-2 driver
Example of type-2 driver is weblogic driver implemented by BEA weblogic
Its not recommended to use type
Unit 2 – JDBC Programming
2160707 – Advanced Java
Explain various types of JDBC drivers and comment on selection
JDBC driver implementations vary because of the wide variety of operating systems and hardware platforms in which Java operates. The different types of drivers available in JDBC are listed in following table:
Description
C Bridge) Refers to the bridge driver(jdbc-odbc diver)
Refers to partly java and partly native code driver(native partly java driver)
(Middleware) Refers to a pure java driver that uses a middleware driver connect to a database(pure java driver for database middleware)
Refers to a pure java driver(pure).which is directly connect to a database
Table 2.1 : JDBC Driver Type
ODBC Bridge) : 1 driver act as a bridge between jdbc and other connecting mechanisms i.e.sun ODBC bridge driver.
This driver also included in the java2 SDK within the sun.jdbc.odbc package.
This driver converts jdbc calls into odbc calls and redirect the request to odbc driver.
It is represent the single driver
Allow to communicate with all database supported by odbc driver
It is vendor independent driver
Decrease the execution speed
Dependent on the odbc driver
Require odbc binary code or odbc client library
Uses java native interface to make odbc call
JDBC call can be converted into the database vendor specific native call with the help of
2 driver is weblogic driver implemented by BEA weblogic
Its not recommended to use type-2 driver with client side application
JDBC Programming
9
Explain various types of JDBC drivers and comment on selection
JDBC driver implementations vary because of the wide variety of operating systems and
The different types of drivers available in JDBC are listed in following table:
odbc diver)
Refers to partly java and partly native code driver(native
Refers to a pure java driver that uses a middleware driver a database(pure java driver for database
Refers to a pure java driver(pure).which is directly
bridge between jdbc and other connecting mechanisms i.e.sun
This driver also included in the java2 SDK within the sun.jdbc.odbc package.
This driver converts jdbc calls into odbc calls and redirect the request to odbc driver.
JDBC call can be converted into the database vendor specific native call with the help of
2 driver is weblogic driver implemented by BEA weblogic
2 driver with client side application
Prashant Maheta, CE Department | 2160707
Advantage:
The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better performance than the JDBCthan that of Type 1 and also it uses Native api which is Database specific.
Disadvantage :
Native API must be installed in the Client System and hence type 2 drivers cannot be used for the Internet.
Like Type 1 drivers, it’s not written in Java
If we change the Database we have to change the native api as it is specific to a database.
Mostly obsolete now Usually not thread safe.
Type-3 Driver (Middleware): This driver translate the jdbc calls into a database server independent and middleware
server specific calls.
Unit 2 – JDBC Programming
2160707 – Advanced Java
The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better performance than the JDBC-ODBC Bridge as the layers of communication (tiers) than that of Type 1 and also it uses Native api which is Database specific.
Native API must be installed in the Client System and hence type 2 drivers cannot be used for the Internet.
Like Type 1 drivers, it’s not written in Java Language which forms a portability issue.
If we change the Database we have to change the native api as it is specific to a
Usually not thread safe.
Fig. 2.1 : JDBC Driver Types
(Middleware): driver translate the jdbc calls into a database server independent and middleware
JDBC Programming
10
The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better ODBC Bridge as the layers of communication (tiers) are less
than that of Type 1 and also it uses Native api which is Database specific.
Native API must be installed in the Client System and hence type 2 drivers cannot be
Language which forms a portability issue.
If we change the Database we have to change the native api as it is specific to a
driver translate the jdbc calls into a database server independent and middleware
Prashant Maheta, CE Department | 2160707
With the help of the middleware server,database server specific calls
This type of driver also
Type-3 driver is recommended to be used with applets.
Advantages:
Serve as all java driver
Does not require any native library to be installed on client machine
Ensure database independency
Does not provide database detail
Provide the facility to switch over from one database to other
Disadvantage:
Its perform the task slowly due to increased number of network calls as compared to type-2 driver
Type-4 Driver (Pure Java): It is pure java driver
This type of driver does not require any native database library to retrieve the record the records from database
This type of driver is lightweight and generally known as thin driver.
You can use this driver when you want an auto doapplication
i.e. thin driver for oracle from oracle corporation, weblogic and ms sqlserver4 for ms sql server from BEA system
Advantages:
Serves as pure java driver
Does not require any native library to install in client
Uses server specific protocol
Does not require middleware server
Disadvantages:
Its uses the database specific proprietary protocol
Unit 2 – JDBC Programming
2160707 – Advanced Java
With the help of the middleware server, the translated jdbc calls further translated into database server specific calls.
This type of driver also known as net-protocol fully java technology-enabled driver
3 driver is recommended to be used with applets. its auto-downloadable
Serve as all java driver
Does not require any native library to be installed on client machine
base independency
Does not provide database detail
Provide the facility to switch over from one database to other
Its perform the task slowly due to increased number of network calls as compared to
(Pure Java):
This type of driver does not require any native database library to retrieve the record the records from database
This type of driver is lightweight and generally known as thin driver.
You can use this driver when you want an auto downloadable option the client side
i.e. thin driver for oracle from oracle corporation, weblogic and ms sqlserver4 for ms sql server from BEA system
Serves as pure java driver
Does not require any native library to install in client machine
Uses server specific protocol
Does not require middleware server
Its uses the database specific proprietary protocol
JDBC Programming
11
the translated jdbc calls further translated into
enabled driver.
downloadable.
Its perform the task slowly due to increased number of network calls as compared to
This type of driver does not require any native database library to retrieve the record the
wnloadable option the client side
i.e. thin driver for oracle from oracle corporation, weblogic and ms sqlserver4 for ms sql
Prashant Maheta, CE Department | 2160707
2. Explain the use of Statement, PreparedStatement & CallableStatement with example.
Once a connection is
CallableStatement, and PreparedStatement interfaces define the methods and properties that enable you to send SQL or PL/SQL commands and receive data from your database.
They also define methodata types used in a database
Following table provides a summary of each interface's purpose.
Interfaces Recommended Use
Statement Use for generalyou are using static SQL statements at runtime. The Statement interface cannot accept parameters.
PreparedStatement Use when you plan to use the SQL statements many times. The PreparedStatement interface accepts input parameters at runtime.
CallableStatement Use when you want to access database stored procedures. The CallableStatement interface can also accept runtime input parameters.
Statement:
The Statement interface defines a standard abstraction to execute requested by a user and return the results by using the ResultSet object.
The Statement interface is created after the connection to the specified database is made.
The object is created using the createStatement() method of the Connectias shown in following code snippet:
Connection con = DriverManager.getConnection(url, “username”, “password”);Statement stmt = con.createStatement();
Example of Statement import java.io.*; import java.sql.*; class StatementDemo public static void main(String[] args) { try {
Unit 2 – JDBC Programming
2160707 – Advanced Java
in the use of Statement, PreparedStatement & CallableStatement with example.
Once a connection is obtained we can interact with the database. The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and properties that enable you to send SQL or PL/SQL commands and receive data from your
They also define methods that help bridge data type differences between Java and SQL data types used in a database. Following table provides a summary of each interface's purpose.
Recommended Use
Use for general-purpose access to your database. Useful you are using static SQL statements at runtime. The Statement interface cannot accept parameters.
Use when you plan to use the SQL statements many times. The PreparedStatement interface accepts input parameters at runtime.
Use when you want to access database stored procedures. The CallableStatement interface can also accept runtime input parameters.
Table 2.2 : Types of Statements
The Statement interface defines a standard abstraction to execute requested by a user and return the results by using the ResultSet object.
The Statement interface is created after the connection to the specified database is
The object is created using the createStatement() method of the Connectias shown in following code snippet:
Connection con = DriverManager.getConnection(url, “username”, “password”);Statement stmt = con.createStatement();
Example of Statement : Select and Display Record From Table
StatementDemo { public static void main(String[] args) {
JDBC Programming
12
in the use of Statement, PreparedStatement &
obtained we can interact with the database. The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and properties that enable you to send SQL or PL/SQL commands and receive data from your
ds that help bridge data type differences between Java and SQL
purpose access to your database. Useful when you are using static SQL statements at runtime. The Statement
Use when you plan to use the SQL statements many times. The PreparedStatement interface accepts input parameters at
Use when you want to access database stored procedures. The CallableStatement interface can also accept runtime input
The Statement interface defines a standard abstraction to execute the SQL statements requested by a user and return the results by using the ResultSet object.
The Statement interface is created after the connection to the specified database is
The object is created using the createStatement() method of the Connection interface,
Connection con = DriverManager.getConnection(url, “username”, “password”);
Prashant Maheta, CE Department | 2160707
// Load and register the driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Establish the connection to the database server Connection cn = DriverManager.getConnection("jdbc:odbc:exm"); // Create a statement Statement st = cn.createStatement(); // Execute the statement ResultSet rs = st.executeQuery("select * from emp // Retrieve the results while(rs.next()) System.out.println(rs.getInt(1)+" "+rs.getString(2)); // Close the statement and connection st.close(); cn.close(); } catch(SQLException e) { System.out.println(e.getMessage()); } } }
PreparedStatement:
The PreparedStatement interface is subclass of the Statement interface,
represent a precompiled query, which can be executed multiple times.
The object is created using the prepareStatement() method of Connection interface, as shown in following snippet:
Connection con = DriverManager.getConnection(url, “usernamString query = “insert into PreparedStatement ps = con.prepareStatement(query);ps.setInt(1,5); ps.setString(2,int n = ps.executeUpdate();
Advantages:
Improves the performance of an application as executes the same query multiple times.
Inserts or updates the SQL 99 data types columns, such as BLOB, CLOB, or OBJECT, with the help of setXXX() methods.
Provides the programmatic approach to set the values.
Unit 2 – JDBC Programming
2160707 – Advanced Java
// Load and register the driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Establish the connection to the database server Connection cn = DriverManager.getConnection("jdbc:odbc:exm");
// Create a statement Statement st = cn.createStatement();
// Execute the statement ResultSet rs = st.executeQuery("select * from emp”);
// Retrieve the results
System.out.println(rs.getInt(1)+" "+rs.getString(2));
// Close the statement and connection
catch(SQLException e) { System.out.println(e.getMessage());
The PreparedStatement interface is subclass of the Statement interface, represent a precompiled query, which can be executed multiple times.
The object is created using the prepareStatement() method of Connection interface, as shown in following snippet:
Connection con = DriverManager.getConnection(url, “usernamString query = “insert into emp values(? ,?)”; PreparedStatement ps = con.prepareStatement(query);
”New Employee”);
int n = ps.executeUpdate();
Improves the performance of an application as compared to the Statement object that executes the same query multiple times.
Inserts or updates the SQL 99 data types columns, such as BLOB, CLOB, or OBJECT, with the help of setXXX() methods.
Provides the programmatic approach to set the values.
JDBC Programming
13
Connection cn = DriverManager.getConnection("jdbc:odbc:exm");
The PreparedStatement interface is subclass of the Statement interface, can be used to represent a precompiled query, which can be executed multiple times.
The object is created using the prepareStatement() method of Connection interface, as
Connection con = DriverManager.getConnection(url, “username”, “password”);
compared to the Statement object that
Inserts or updates the SQL 99 data types columns, such as BLOB, CLOB, or OBJECT, with
Prashant Maheta, CE Department | 2160707
Disadvantages: The main disadvantage of PreparedStatement is that it can represent only one SQL statement at a time.
Example of PreparedStatement
import java.io.*; import java.sql.*; class PreparedStatementDemo public static void main(String[] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String q = "insert into emp(emp_no,emp_name) values (?,?)"; Connection con = DriverManager.getConnection("jdbc:odbc:exm"); PreparedStatement pst = con.prepareStatement(q);
pst.setString(2,"Employee Name"); pst.setInt(1,10); pst.executeUpdate(); pst.setString(2,"New Employee1"); pst.setInt(1,11); pst.executeUpdate(); pst.setString(2,"New Employee2"); pst.setInt(1,12); pst.executeUpdate(); pst.setString(2,"New Employee3"); pst.setInt(1,13); pst.executeUpdate(); pst.setString(2,"New Employee4"); pst.setInt(1,14); pst.executeUpdate(); } catch(Exception e) { System.o } }
Unit 2 – JDBC Programming
2160707 – Advanced Java
The main disadvantage of PreparedStatement is that it can represent only one SQL statement at
Statement : Insert Records into the Table
PreparedStatementDemo { public static void main(String[] args) {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String q = "insert into emp(emp_no,emp_name) values (?,?)";
Connection con = DriverManager.getConnection("jdbc:odbc:exm");
nt pst = con.prepareStatement(q);
pst.setString(2,"Employee Name");
pst.executeUpdate();
pst.setString(2,"New Employee1");
pst.executeUpdate();
pst.setString(2,"New Employee2");
pst.executeUpdate();
pst.setString(2,"New Employee3");
pst.executeUpdate();
pst.setString(2,"New Employee4");
pst.executeUpdate();
catch(Exception e) { System.out.println(e); }
JDBC Programming
14
The main disadvantage of PreparedStatement is that it can represent only one SQL statement at
Connection con = DriverManager.getConnection("jdbc:odbc:exm");
Prashant Maheta, CE Department | 2160707
CallableStatement: In java the CallableStatement interface is used to call the stored procedure and
functions.
Therefore, the stored procedure can be called by using an object of the CallableStatement interface.
The object is created using the preparein following snippet:
Connection cn = DriverManager.getConnection("jdbc:odbc:exm");CallableStatement cs = cn.prepareCall("{call proc1()}");ResultSet rs= cs.executeQuery();
Example of CallableStatement
import java.io.*; import java.sql.*; class CallableStatement public static void main(String[] args) try { } catch(Exception e) { } } }
Unit 2 – JDBC Programming
2160707 – Advanced Java
In java the CallableStatement interface is used to call the stored procedure and
Therefore, the stored procedure can be called by using an object of the CallableStatement interface.
is created using the prepareCall() method of Connection interface, as shown
Connection cn = DriverManager.getConnection("jdbc:odbc:exm");CallableStatement cs = cn.prepareCall("{call proc1()}"); ResultSet rs= cs.executeQuery();
Statement : Select Records from the Table
CallableStatement { public static void main(String[] args) {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection cn = DriverManager.getConnection("jdbc:odbc:exm");
//call the procedure CallableStatement cs = cn.prepareCall("{call proc1()}");
//display record selected by the procedure ResultSet rs= cs.executeQuery(); while(rs.next()) System.out.println(rs.getInt(1)+" "+rs.getString(2));
catch(Exception e) { System.out.println(e.getMessage());
JDBC Programming
15
In java the CallableStatement interface is used to call the stored procedure and
Therefore, the stored procedure can be called by using an object of the
() method of Connection interface, as shown
Connection cn = DriverManager.getConnection("jdbc:odbc:exm");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); DriverManager.getConnection("jdbc:odbc:exm");
CallableStatement cs = cn.prepareCall("{call proc1()}");
ln(rs.getInt(1)+" "+rs.getString(2));
Prashant Maheta, CE Department | 2160707
3. Explain following in brief: JDBC Architecture
The JDBC API supports both twogeneral JDBC Architecture consists of two layers:
JDBC API: This provides the applicationimportant classes and interface defined in JDBC API are as follows.
o Driver Managero Driver o Connection o Statement o PreparedStatemento CallableStatemento ResultSet o DatabaseMetaDatao ResultSetMetaDatao SqlData o Blob o Clob
JDBC Driver API: This supports the JDBC Manager
Unit 2 – JDBC Programming
2160707 – Advanced Java
Explain following in brief: JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access but in general JDBC Architecture consists of two layers:
This provides the application-to-JDBC Manager connection. Some of the important classes and interface defined in JDBC API are as follows.
Driver Manager
PreparedStatement CallableStatement
DatabaseMetaData ResultSetMetaData
This supports the JDBC Manager-to-Driver Connection.
Fig. 2.2 : JDBC Architecture
JDBC Programming
16
database access but in
JDBC Manager connection. Some of the
Driver Connection.
Prashant Maheta, CE Department | 2160707
The JDBC API uses a driver manager and
connectivity to heterogeneous databases. The JDBC driver manager ensures that the correct driver is used to access each data
source. The driver manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases.
4. Difference Between executeQuery(), executeUpdate() and execute().
executeQuery() : - executeQuery() can be used to execute selection group sql queries
to fetch the data from database.
public ResultSet executeQuery(String sqlquery) When we use selection group sql query with executeQuery() then JVM will send that sql query to the database engine, database engine will execute it, by this database engine(DBE) will fetch the data from database and send back
executeUpdate() : -to update the database.
public int executeUpdate(String sqlquery) When we provide updation group sql query as a parameter to executeUpdate(), will send that sql query to DBE, here DBE will execute it and perform updations on the database
execute() : - execute() can be used to execute either selection group sql queries or
updation group queries.
public boolean execute(String sqlquery) When we use selection group sql query with the execute() then we will get ResultSet object at heap memory with the fetched data. But execute() will return “true” as a Boolean value. When we use updation group sql query with execute() then we will get “ rcount value” at jdbc application. But execute() will return “false” as a Boolean value.
Unit 2 – JDBC Programming
2160707 – Advanced Java
The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases. The JDBC driver manager ensures that the correct driver is used to access each data source. The driver manager is capable of supporting multiple concurrent drivers
nnected to multiple heterogeneous databases.
Difference Between executeQuery(), executeUpdate() and
executeQuery() can be used to execute selection group sql queries
to fetch the data from database.
executeQuery(String sqlquery)
When we use selection group sql query with executeQuery() then JVM will send that sql query to the database engine, database engine will execute it, by this database engine(DBE) will fetch the data from database and send back to the java application.
- executeUpdate() can be used to execute updation group sql query
public int executeUpdate(String sqlquery)
When we provide updation group sql query as a parameter to executeUpdate(), will send that sql query to DBE, here DBE will execute it and perform updations on the
execute() can be used to execute either selection group sql queries or
boolean execute(String sqlquery)
When we use selection group sql query with the execute() then we will get ResultSet object at heap memory with the fetched data. But execute() will return “true” as a Boolean value. When we use updation group sql query with execute() then we will get “ rcount value” at jdbc application. But execute() will return “false” as a Boolean value.
JDBC Programming
17
specific drivers to provide transparent
The JDBC driver manager ensures that the correct driver is used to access each data source. The driver manager is capable of supporting multiple concurrent drivers
Difference Between executeQuery(), executeUpdate() and
executeQuery() can be used to execute selection group sql queries
When we use selection group sql query with executeQuery() then JVM will send that sql query to the database engine, database engine will execute it, by this database engine(DBE)
executeUpdate() can be used to execute updation group sql query
When we provide updation group sql query as a parameter to executeUpdate(), then JVM will send that sql query to DBE, here DBE will execute it and perform updations on the
execute() can be used to execute either selection group sql queries or
When we use selection group sql query with the execute() then we will get ResultSet object at heap memory with the fetched data. But execute() will return “true” as a Boolean value. When we use updation group sql query with execute() then we will get “ records updated count value” at jdbc application. But execute() will return “false” as a Boolean value.
Prashant Maheta, CE Department | 2160707
5. Explain ResultsetMetaData Interface with Example
The metadata means data about data i.e. we can get further information from the data.
If you have to get metadata of a table like total number of column, column name, column type etc. , ResultSetMetaData interface is useful because it provides methods to get metadata from the ResultSet object.
import java.io.*; import java.sql.*; class ResultSetMetaData public static void main(String[] args) { try {
// Load and register the driver try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(Exception e) {} //Driver myDriver = new sun.jdbc.odbc.JdbcOdbcDriver(); //DriverManager.registerDriver(myDriver); // Establish the connection to the database server Connection cn = DriverManager.getConnection("jdbc
// Create a statement Statement st = cn.createStatement(); // Execute the statement ResultSet rs = st.executeQuery("select * from emp"); // Create Meta Data object ResultSetMetaData rsmd = rs.getMetaData(); // Get Column Details for(int i=1;i<=rsmd.getColumnCount();i++) System.out.println("Column"+i+" "+rsmd.getColumnName(i)+" "+rsmd.getPrecision(i)+" "+rsmd.getColumnTypeName(i))
Unit 2 – JDBC Programming
2160707 – Advanced Java
Explain ResultsetMetaData Interface with Example
The metadata means data about data i.e. we can get further information from the data.
have to get metadata of a table like total number of column, column name, column type etc. , ResultSetMetaData interface is useful because it provides methods to get metadata from the ResultSet object.
{
public static void main(String[] args) {
// Load and register the driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
catch(Exception e) {}
//Driver myDriver = new sun.jdbc.odbc.JdbcOdbcDriver(); //DriverManager.registerDriver(myDriver);
// Establish the connection to the database server Connection cn = DriverManager.getConnection("jdbc:odbc:example");
Statement st = cn.createStatement();
// Execute the statement ResultSet rs = st.executeQuery("select * from emp");
// Create Meta Data object ResultSetMetaData rsmd = rs.getMetaData();
for(int i=1;i<=rsmd.getColumnCount();i++) System.out.println("Column"+i+" "+rsmd.getColumnName(i)+"
"+rsmd.getPrecision(i)+" "+rsmd.getColumnTypeName(i));
JDBC Programming
18
Explain ResultsetMetaData Interface with Example
The metadata means data about data i.e. we can get further information from the data.
have to get metadata of a table like total number of column, column name, column type etc. , ResultSetMetaData interface is useful because it provides methods to get
:odbc:example");
System.out.println("Column"+i+" "+rsmd.getColumnName(i)+"
Prashant Maheta, CE Department | 2160707
// Retrieve the results while(rs.next()) System.out.println(rs.getInt("emp_no")+" "+rs.getString(2)); // Close the statement and connection st.close(); cn.close(); } catch(SQLException e) { System.out.println(e.getMessage()); } }
}
Unit 2 – JDBC Programming
2160707 – Advanced Java
// Retrieve the results
System.out.println(rs.getInt("emp_no")+" "+rs.getString(2));
// Close the statement and connection
catch(SQLException e) { System.out.println(e.getMessage());
JDBC Programming
19
Prashant Maheta, CE Department | 2160707
1. Explain Servlet Life Cycle In the life cycle of servlet there are three important methods.
1. Init() 2. Service() 3. Destroy()
The client enters the URL in the web browser and makes a request. The browser then generates the HTTP request and sends it to the Web server. Web server maps this request to the corresponding servlet. The server basically invokes the servlet is loaded in the memory for the first time. Using this method initialization parameters can also be passed to the servlet in order to configure itself. Server can invoke the service for particular HTcan then read the data provided by the HTTP request with the help of Finally server unloads the servlet from the memory using the
Following is a simple servlet in which used. import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class LifeCycle extends GenericServlet {public void init(ServletConfig config) throws System.out.println(“init”);}
Unit 3 – Servlet API and Overview
2160707– Advanced Java
Explain Servlet Life Cycle In the life cycle of servlet there are three important methods. These methods are
Fig. 1 : Servlet Life Cycle enters the URL in the web browser and makes a request. The browser then generates the HTTP request and sends it to the Web server. Web server maps this request to the corresponding servlet.
The server basically invokes the init() method of servlet. This method is called only when the servlet is loaded in the memory for the first time. Using this method initialization parameters can also be passed to the servlet in order to configure itself. Server can invoke the service for particular HTTP request using service() can then read the data provided by the HTTP request with the help of service()Finally server unloads the servlet from the memory using the destroy() method.
Following is a simple servlet in which these three methods viz. init(), service() and destroy() are
class LifeCycle extends GenericServlet { public void init(ServletConfig config) throws ServletException { System.out.println(“init”);
API and Overview
20
These methods are
enters the URL in the web browser and makes a request. The browser then
of servlet. This method is called only when the servlet is loaded in the memory for the first time. Using this method initialization parameters can method. The servlets service() method.
method. these three methods viz. init(), service() and destroy() are
Prashant Maheta, CE Department | 2160707
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {System.out.println(“from service”);PrintWriter out = response.getWriter();out.println(“welcome to servlet”);out.println(“This is my first servlet”);} public void destroy() { System.out.println(“destroy”);} } ServletContext:
ServletContext object is used to get configuration information from Deployment Descriptor(web.xml) which will be available to any Servlet or JSPs that are part of the web application. There is one context per "web application" per Java Virtual Machine. The ServletContext object is contained within the ServletConfig object. That is, tServletContext can be accessed using the ServletConfig object within a servlet. You can specify paramweb.xml file. Example: <context-param><param-name><param-value></context-param>
Diffrence between ServletContext & ServletConfig.Servlet Config Servlet config object represent single servlet
Its like local parameter associated with particular servlet It’s a name value pair defined inside the servlet section of web.xml file so it has servlet wide scope
Unit 3 – Servlet API and Overview
2160707– Advanced Java
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { System.out.println(“from service”); PrintWriter out = response.getWriter(); out.println(“welcome to servlet”); out.println(“This is my first servlet”);
public void destroy() { System.out.println(“destroy”);
ServletContext object is used to get configuration information from Deployment Descriptor(web.xml) which will be available to any Servlet or JSPs that are part of the There is one context per "web application" per Java Virtual Machine.The ServletContext object is contained within the ServletConfig object. That is, tServletContext can be accessed using the ServletConfig object within a servlet. You can specify param-value pairs for ServletContext object in <context
param> name>Parameter Name</param-name> value>Parameter Value</param-value> param> Diffrence between ServletContext & ServletConfig.
Servlet Context Servlet config object represent single It represent whole web application running on particular JVM and all the servlet Its like local parameter associated with Its like global parameter associated with whole application It’s a name value pair defined inside the servlet section of web.xml file so it has ServletContext has application wide scope so define outside of servlet tag in web.xml file.
API and Overview
21
public void service(ServletRequest request, ServletResponse response) throws
ServletContext object is used to get configuration information from Deployment Descriptor(web.xml) which will be available to any Servlet or JSPs that are part of the
The ServletContext object is contained within the ServletConfig object. That is, the ServletContext can be accessed using the ServletConfig object within a servlet. value pairs for ServletContext object in <context-param> tags in
It represent whole web application running on particular JVM and common for
Its like global parameter associated with
has application wide scope so define outside of servlet tag in web.xml
Prashant Maheta, CE Department | 2160707
getServletConfig() method is used to get the config object for example shopping cart of a user specific to particular user so here we can use servlet config
2. Explain Request Dispatcher The RequestDispatcher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp. This interface can also be used to include the content of another resource also. It is one of the way of servlet collaboration.
There are two methods defined in the RequestDispatcher interface.1. public void forward(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:resource (servlet, JSP file, or2. public void include(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:page, or HTML file) in the response.
Example
<form method="post" action="http://localhost:8080/Validate">Name:<input type="text" name="user" /><br/>Password:<input type="password" name="pass" ><br/><input type="submit" value="submit"></form>
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Validate extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter();
Unit 3 – Servlet API and Overview
2160707– Advanced Java
method is used to get getServletContext() method isthe context object. for example shopping cart of a user is a specific to particular user so here we can To get the MIME type of a file or application session related information is stored using servlet context object.
Request Dispatcher in Java Servlet with example.RequestDispatcher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp. This interface can also be used to include the content of another resource also. It is one of the way of servlet collaboration.
There are two methods defined in the RequestDispatcher interface. public void forward(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException: Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. public void include(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException: Includes the content of a resource (servlet, JSP page, or HTML file) in the response.
Index.html method="post" action="http://localhost:8080/Validate"> Name:<input type="text" name="user" /><br/> Password:<input type="password" name="pass" ><br/> <input type="submit" value="submit">
Validate.java
import javax.servlet.http.*; public class Validate extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter();
API and Overview
22
method is used to get To get the MIME type of a file or application session related information is stored using servlet context object.
in Java Servlet with example. RequestDispatcher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp. This interface can also be used to include the content of another resource also. It is one of the way of servlet collaboration.
public void forward(ServletRequest request,ServletResponse response)throws Forwards a request from a servlet to another public void include(ServletRequest request,ServletResponse response)throws Includes the content of a resource (servlet, JSP
protected void doPost(HttpServletRequest request, HttpServletResponse response)
Prashant Maheta, CE Department | 2160707
try { String name = request.getParameter("user"); String password = request.getParameter("pass"); if(password.equals("darshaninst")) { RequestDispatcher rd = request.getRequestDispatcher("Welcome"); rd.forward(request, response); } else { out.println("<font color='red'><b>You have entered incorrect password</b></font>"); } }finally { out.close(); } } }
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;public class Welcome extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); try { out.println("<h2>Welcome user</h2>"); } finally { out.close(); } } }
Unit 3 – Servlet API and Overview
2160707– Advanced Java
String name = request.getParameter("user"); String password = request.getParameter("pass"); if(password.equals("darshaninst"))
RequestDispatcher rd = request.getRequestDispatcher("Welcome");rd.forward(request, response);
out.println("<font color='red'><b>You have entered incorrect password</b></font>");
Welcome.java
import javax.servlet.http.*; public class Welcome extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter();
out.println("<h2>Welcome user</h2>");
API and Overview
23
RequestDispatcher rd = request.getRequestDispatcher("Welcome");
out.println("<font color='red'><b>You have entered incorrect password</b></font>");
protected void doPost(HttpServletRequest request, HttpServletResponse response)
Prashant Maheta, CE Department | 2160707
<web-app> <servlet> <servlet-name> <servlet-class></servlet> <servlet-mapping> <servlet-name> <url-pattern>/</servlet-mapping> <servlet> <servlet-name> <servlet-class></servlet> <servlet-mapping> <servlet-name> <url-pattern>/</servlet-mapping> </web-app>
3 What is filter? What is its use? List the different filter interfaces with their important methods. 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 pluggablethe 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.
Unit 3 – Servlet API and Overview
2160707– Advanced Java
web.xml
name>Validate</servlet-name> class>Validate</servlet-class>
name>Validate</servlet-name> pattern>/Validate</url-pattern>
name>Welcome</servlet-name> class>Welcome</servlet-class>
name>Welcome</servlet-name> pattern>/Welcome</url-pattern>
What is filter? What is its use? List the different filter interfaces with their important methods. 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. 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.
API and Overview
24
What is filter? What is its use? List the different filter interfaces 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, . 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
Prashant Maheta, CE Department | 2160707
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 Less Maintenance
Unit 3 – Servlet API and Overview
2160707– Advanced Java
Fig 1 : Filter
recording all incoming requests logs the IP addresses of the computers from which the requests originate
encryption and decryption
One filter don't have dependency onto another resource.
API and Overview
25
logs the IP addresses of the computers from which the requests originate
Prashant Maheta, CE Department | 2160707
Filter API : Like servlet filter have its own API. The javax.servlet package contains the three interfaces of Filter API.
1. Filter 2. FilterChain 3. FilterConfig 1) Filter interface For creating any filter, you must cycle methods for a filter.
Method public void init(FilterConfig config)public void doFilter(HttpServletRequest request,HttpServletResponse response, FilterChain chain) public void destroy()
2) FilterChain interface The object of FilterChain is responsible to invoke the next filter or resource in the chain.This object is passed in the doFilter method of Filter interface.The one method:
1. public void doFilter(HttpServletRequest request, HttpServletResponse response):passes the control to the next filter or resource. Example MyFilter.java import java.io.IOException;import java.io.PrintWriter;import javax.servlet.*; public class MyFilter implementspublic void init(FilterConfig
Unit 3 – Servlet API and Overview
2160707– Advanced Java
Like servlet filter have its own API. The javax.servlet package contains the three interfaces of
For creating any filter, you must implement the Filter interface. Filter interface provides the life Description
public void init(FilterConfig config) init() method is invoked only once. It is used to initialize the filter. doFilter(HttpServletRequest request,HttpServletResponse response, doFilter() method is invoked every time when user request to any resource, to which the filter is mapped.It is used to perform filtering tasks.
This is invoked only once when filter is taken out of the service.
The object of FilterChain is responsible to invoke the next filter or resource in the chain.This object is passed in the doFilter method of Filter interface.The FilterChain interface contains only
public void doFilter(HttpServletRequest request, HttpServletResponse response):passes the control to the next filter or resource.
java.io.IOException; java.io.PrintWriter;
implements Filter{ init(FilterConfig arg0) throws ServletException {}
API and Overview
26
Like servlet filter have its own API. The javax.servlet package contains the three interfaces of
implement the Filter interface. Filter interface provides the life
init() method is invoked only once. It is used to doFilter() method is invoked every time when user request to any resource, to which the filter is mapped.It is used to perform filtering tasks.
is invoked only once when filter is taken out of
The object of FilterChain is responsible to invoke the next filter or resource in the chain.This FilterChain interface contains only
public void doFilter(HttpServletRequest request, HttpServletResponse response): it
Prashant Maheta, CE Department | 2160707
public void doFilter(ServletRequestthrows IOException, ServletException PrintWriter out=resp.getWriter();out.print("filterchain.doFilter(req,out.print("filter} public void destroy() {}} HelloServlet.java import java.io.IOException;import java.io.PrintWriter; import javax.servlet.ServletException;import javax.servlet.http.*; public class HelloServlet extends public void doGet(HttpServletRequest throws ServletException, response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.print("<br>welcome } } Web.xml <web-app> <servlet> <servlet-name>s1</servlet<servlet-class>HelloServlet</servlet</servlet> <servlet-mapping> <servlet-name>s1<<url-pattern>/servlet1</url</servlet-mapping>
Unit 3 – Servlet API and Overview
2160707– Advanced Java
doFilter(ServletRequest req, ServletResponse resp, FilterChainServletException { out=resp.getWriter(); out.print("filter is invoked before"); chain.doFilter(req, resp);//sends request to next resource out.print("filter is invoked after"); {}
java.io.IOException; java.io.PrintWriter; javax.servlet.ServletException; javax.servlet.http.*;
extends HttpServlet { doGet(HttpServletRequest request, HttpServletResponse response)ServletException, IOException { response.setContentType("text/html"); response.getWriter(); out.print("<br>welcome to servlet<br>");
name>s1</servlet-name> class>HelloServlet</servlet-class>
name>s1</servlet-name> pattern>/servlet1</url-pattern>
API and Overview
27
ilterChain chain)
response)
Prashant Maheta, CE Department | 2160707
<filter> <filter-name>f1</filter<filter-class>MyFilter</filter</filter> <filter-mapping> <filter-name>f1</filter<url-pattern>/servlet1<</filter-mapping> </web-app> 4 Explain Request and Response object in servlet. True job of a Servlet is to handle client request.
Servlet API provides two important interfaces javax.servlet.ServletR Implementation of these interfaces provide important information about client request to a servlet.
Unit 3 – Servlet API and Overview
2160707– Advanced Java
name>f1</filter-name> class>MyFilter</filter-class>
name>f1</filter-name> pattern>/servlet1</url-pattern>
Explain Request and Response object in servlet. True job of a Servlet is to handle client request. Servlet API provides two important interfaces javax.servlet.ServletRequestjavax.servlet.ServletResponse to encapsulate client request and responseImplementation of these interfaces provide important information about client request
Fig : Servlet Request
API and Overview
28
javax.servlet.ServletRequest and and response. Implementation of these interfaces provide important information about client request
Prashant Maheta, CE Department | 2160707
Index.html <form method="post" action="check">Name <input type="text" name="user" ><input type="submit" value="submit"></form> Web.Xml <servlet> <servlet-name>check</servlet <servlet-class>MyServlet</servlet</servlet> <servlet-mapping> <servlet-name>check</servlet <url-pattern>/check</url</servlet-mapping> MyServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet extends
Unit 3 – Servlet API and Overview
2160707– Advanced Java
Fig : Servlet Response
method="post" action="check"> Name <input type="text" name="user" > <input type="submit" value="submit">
name>check</servlet-name> class>MyServlet</servlet-class>
name>check</servlet-name> pattern>/check</url-pattern>
extends HttpServlet {
API and Overview
29
Prashant Maheta, CE Department | 2160707
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF PrintWriter out = response.getWriter(); try { String user=request.getParameter("user"); out.println("<h2> Welcome "+user+"</h2>"); } finally { out.close(); } } } 5 Session in Servlet, Explain with Example. HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request.
Still there are following three ways to maiserver: Cookies:
o A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the recieved cookie. o This may not be an effective cookie, so I would not recommend to use this procedure to maintain the sessions.
Hidden Form Fields: o A web server can send a hidden HTML form field along with a unique session ID as follows: o <input type="ho This entry means that, when the form is submitted, the specified name and value are automatically included in the GET or POST data. Each time when web browser sends request back, then session_id value can be used to kdifferent web browsers.o This could be an effective way of keeping track of the session but clicking on a regular (<A HREF...>) hypertext link does not result in a form submission, so hidden form fields also cannot support general session t
Unit 3 – Servlet API and Overview
2160707– Advanced Java
(HttpServletRequest request, HttpServletResponse response)ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); = response.getWriter();
=request.getParameter("user"); out.println("<h2> Welcome "+user+"</h2>");
Session in Servlet, Explain with Example. "stateless" protocol which means each time a client retrieves a Web page, the client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request.
Still there are following three ways to maintain session between web client and web
A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the recieved This may not be an effective way because many time browser does not support a cookie, so I would not recommend to use this procedure to maintain the
A web server can send a hidden HTML form field along with a unique session ID <input type="hidden" name="sessionid" value="12345"> This entry means that, when the form is submitted, the specified name and value are automatically included in the GET or POST data. Each time when web browser sends request back, then session_id value can be used to kdifferent web browsers. This could be an effective way of keeping track of the session but clicking on a regular (<A HREF...>) hypertext link does not result in a form submission, so hidden form fields also cannot support general session tracking.
API and Overview
30
(HttpServletRequest request, HttpServletResponse response)
"stateless" protocol which means each time a client retrieves a Web page, the client opens a separate connection to the Web server and the server automatically does ntain session between web client and web
A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the recieved way because many time browser does not support a cookie, so I would not recommend to use this procedure to maintain the
A web server can send a hidden HTML form field along with a unique session ID
This entry means that, when the form is submitted, the specified name and value are automatically included in the GET or POST data. Each time when web browser sends request back, then session_id value can be used to keep the track of This could be an effective way of keeping track of the session but clicking on a regular (<A HREF...>) hypertext link does not result in a form submission, so racking.
Prashant Maheta, CE Department | 2160707
URL Rewriting: o You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session.
Session Tracking Example: // Import required java librariesimport java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Extend HttpServlet class public class SessionTrack extends public void doGet(HttpServletRequest HttpServletResponse throws ServletException { // Create a session object if it is already not created. HttpSession session = request // Get session creation time. Date createTime = new Date // Get last access time of this web page. Date lastAccessTime = new Date(session String title = "Welcome Back to my website" Integer visitCount = new Integer String visitCountKey = new String userIDKey = new String String userID = new String // Check if this is new comer on your web page. if (session.isNew()){ title = "Welcome to my website" session.setAttribute(userIDKey } else { visitCount = (Integer)session visitCount = visitCount + userID = (String)session.getAttribute } session.setAttribute(visitCountKey
Unit 3 – Servlet API and Overview
2160707– Advanced Java
You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session. Session Tracking Example: java libraries
extends HttpServlet { HttpServletRequest request, HttpServletResponse response) ServletException, IOException
// Create a session object if it is already not created. request.getSession(true); // Get session creation time. Date(session.getCreationTime()); // Get last access time of this web page. session.getLastAccessedTime());
"Welcome Back to my website"; Integer(0); new String("visitCount"); String("userID"); String("ABCD"); // Check if this is new comer on your web page.
"Welcome to my website"; userIDKey, userID); session.getAttribute(visitCountKey); + 1; getAttribute(userIDKey);
visitCountKey, visitCount);
API and Overview
31
You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has
Prashant Maheta, CE Department | 2160707
// Set response content type response.setContentType( PrintWriter out = response String docType = "<!doctype html public \"- "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title "<body bgcolor=\"#f0f0f0 "<h1 align=\"center\ "<h2 align=\"center "<table border=\"1\" align= "<tr bgcolor=\"#949494 " <th>Session info</th><th>value</th></tr> "<tr>\n" + " <td>id</td>\n" + " <td>" + session.getId "<tr>\n" + " <td>Creation Time</td> " <td>" + createTime " </td></tr>\n" + "<tr>\n" + " <td>Time of Last Access</td> " <td>" + lastAccessTime " </td></tr>\n" + "<tr>\n" + " <td>User ID</td>\ " <td>" + userID + " </td></tr>\n" + "<tr>\n" + " <td>Number of visits</td> " <td>" + visitCount "</table>\n" + "</body></html>"); } }
Unit 3 – Servlet API and Overview
2160707– Advanced Java
// Set response content type ("text/html"); response.getWriter();
-//w3c//dtd html 4.0 " +
title + "</title></head>\n" + "#f0f0f0\">\n" + \">" + title + "</h1>\n" + "center\">Session Infomation</h2>\n" + " align=\"center\">\n" + "#949494\">\n" + </th><th>value</th></tr>\n" + getId() + "</td></tr>\n" +
" <td>Creation Time</td>\n" + createTime +
" <td>Time of Last Access</td>\n" + lastAccessTime +
\n" +
" <td>Number of visits</td>\n" + visitCount + "</td></tr>\n" +
API and Overview
32
Prashant Maheta, CE Department | 2160707
1. Explain JSP unified Expression Language (EL) .
EL is a language that allows JSP programmers to fetch application data stored in JavaBeans
component.
The following methods are used to 1. Placing the entire Java code in a JSP page2. Defining separate helper classes that encapsulate the entire Java code and calling
these helper classes from a JSP page3. Using JavaBeans and JSP page action tags4. Using JSP EL 5. Create tag handler classes to embed the Java code
The incorporation of EL to the JSP has helped reduce the use of scriptles in JSP page.
EL expressions provide short hand notations to retrieve, present, and manipulate Web application data.
EL expressions are enclosed between the ${ and} characters.
The most general example of an EL expression is ${object.data}Where, object can be any Java object representing different scope, such as request,session.
EL expressiongs can be categorized into the following ty1. Immediate and deferred expressions2. Value expressions3. Method expressions
1) Immediate and deferred expressions
Two constructs are used to represent EL expressions, ${ expr } used for expressions that need to be evaluated immediately, and #{ expr } used for expressions that need to be evaluated at later time.
An expression that uses ${ expr } is called immediate expression and
The expression that uses #{ expr } is called deferred expression.2) Value Expressions
Value epressions are used to refer to objects enumerations and implicit objects and their properties.
An object is referred to by using the value expression containing the name of the object
Suppose the ${ employee } expression is used in a JSP page, where employee refethe name of a JavaBean.
Which searches for the employee JavaBeab in the request, session and application scopes
If the employee JavaBean does not exist, a null value is returned.
Syntax of value expression to access properties and elements of a colletwo operators, ( . ) and ( [] ).
For example, The name property of the employee JavaBean can be referred as
${employee.name} or ${ employee[“name”] } expression.
Unit 4 – Java
| 2160707– Advanced Java
Explain JSP unified Expression Language (EL) .
EL is a language that allows JSP programmers to fetch application data stored in JavaBeans
The following methods are used to call the java code from a JSP page: Placing the entire Java code in a JSP page
Defining separate helper classes that encapsulate the entire Java code and calling these helper classes from a JSP page Using JavaBeans and JSP page action tags
Create tag handler classes to embed the Java code
The incorporation of EL to the JSP has helped reduce the use of scriptles in JSP page.
EL expressions provide short hand notations to retrieve, present, and manipulate Web
re enclosed between the ${ and} characters.
The most general example of an EL expression is ${object.data} Where, object can be any Java object representing different scope, such as
EL expressiongs can be categorized into the following types: Immediate and deferred expressions Value expressions Method expressions
Immediate and deferred expressions
Two constructs are used to represent EL expressions, ${ expr } used for expressions that need to be evaluated immediately, and
for expressions that need to be evaluated at later time.
An expression that uses ${ expr } is called immediate expression and
The expression that uses #{ expr } is called deferred expression.
Value epressions are used to refer to objects such as JavaBeans, Collections, enumerations and implicit objects and their properties.
An object is referred to by using the value expression containing the name of the object
Suppose the ${ employee } expression is used in a JSP page, where employee refethe name of a JavaBean.
Which searches for the employee JavaBeab in the request, session and application
If the employee JavaBean does not exist, a null value is returned.
Syntax of value expression to access properties and elements of a colletwo operators, ( . ) and ( [] ).
The name property of the employee JavaBean can be referred as ${employee.name} or ${ employee[“name”] } expression.
ava Server Page
33
EL is a language that allows JSP programmers to fetch application data stored in JavaBeans
Defining separate helper classes that encapsulate the entire Java code and calling
The incorporation of EL to the JSP has helped reduce the use of scriptles in JSP page.
EL expressions provide short hand notations to retrieve, present, and manipulate Web
Where, object can be any Java object representing different scope, such as
${ expr } used for expressions that need to be evaluated immediately, and for expressions that need to be evaluated at later time.
such as JavaBeans, Collections,
An object is referred to by using the value expression containing the name of the object
Suppose the ${ employee } expression is used in a JSP page, where employee refers to
Which searches for the employee JavaBeab in the request, session and application
Syntax of value expression to access properties and elements of a collection in java uses
The name property of the employee JavaBean can be referred as
Prashant Maheta, CE Department | 2160707
To access a specific element of a collection, such as list or an array insiJavaBean we can use ${ employee.name[0] }, ${ employee.name[1] }, etc…
The value expressions are of two types:o rvalue
rvalue expression can only read data, and not write data.o lvalue
lvalue expression can read as well as write data.3) Method Expressions
Method expressions are used to call public methods, which returns a value or object.
Such expressions are usually deferred expressions.
Tags usually use method expressions to call functions that perform operations such as validating a UI component or hand
The following code snippet shows the use of method expressions in JSF page: <h:form>
<h:inputText id=”email”value=”#{employee.email}validator=”#{employee.validateEmail}” />
<h:commandButton id=”submit”action=”#{customer.submit}” />
</h:form>
The various elements shown in the preceding code snippet can be briefly described as follows: o The inputText tag : shows the UIInput component in the form of a text field on a
webpage o The validator attribute : callso The action attribute of the
carries out processing after submitting the webpageo The validateEmail method : Refers to the method that is called during the
phase of the JSP life cycleo The submit method : Refers to the method that is called during the invoke application
phase of the JSP life cycle
Unit 4 – Java
| 2160707– Advanced Java
To access a specific element of a collection, such as list or an array insiJavaBean we can use ${ employee.name[0] }, ${ employee.name[1] }, etc…
The value expressions are of two types:
rvalue expression can only read data, and not write data.
lvalue expression can read as well as write data.
Method expressions are used to call public methods, which returns a value or object.
Such expressions are usually deferred expressions.
Tags usually use method expressions to call functions that perform operations such as validating a UI component or handling the events generated on a UI component.
The following code snippet shows the use of method expressions in JSF page:
id=”email” value=”#{employee.email} validator=”#{employee.validateEmail}” />
id=”submit” action=”#{customer.submit}” />
The various elements shown in the preceding code snippet can be briefly described as
tag : shows the UIInput component in the form of a text field on a
attribute : calls the validateEmail method of the employee JavaBeanattribute of the commandButton tag : calls the submit method, which
carries out processing after submitting the webpage method : Refers to the method that is called during the
phase of the JSP life cycle method : Refers to the method that is called during the invoke application
phase of the JSP life cycle
ava Server Page
34
To access a specific element of a collection, such as list or an array inside a JavaBean we can use ${ employee.name[0] }, ${ employee.name[1] }, etc…
Method expressions are used to call public methods, which returns a value or object.
Tags usually use method expressions to call functions that perform operations such as ling the events generated on a UI component.
The following code snippet shows the use of method expressions in JSF page:
The various elements shown in the preceding code snippet can be briefly described as
tag : shows the UIInput component in the form of a text field on a
the validateEmail method of the employee JavaBean tag : calls the submit method, which
method : Refers to the method that is called during the validation
method : Refers to the method that is called during the invoke application
Prashant Maheta, CE Department | 2160707
2 Enlist and explain the use of action tags in JSP.
Action tags are specific to a JSP page. When a translating a JSP page into a servlet, it generates a Java code corresponding to the task to be performed by the action tag.
The following are some important action tags available in JSP page:1. <jsp:include>
o The <jsp:include> action tag facilitates Java programmers in including a static or dynamic resource, such as an HTML or JSP page in the current JSP page.
o If the resource to be included is static then its content is directly included.o If the resource is dyno Example
<jsp:include page=”test.jsp” />2. <jsp:forward>
o The <jsp:forward> tag forwards a JSP request to another resource which can be either static or dynamic.
o If the request is forwarded to a pass a name and value of a parameter to a resource.
o Example: <jsp:forward page=”/header.html” />
3. <jsp:param> o The <jsp:param> tag allows Java programmers to pass a name and value of a
parameter to a dynamicrequest to another JSP page.
o Example: <jsp:param name=”uname” value=”
4. <jsp:useBean> o To separate the business logic from the presentation logic, it is often a good idea to
encapsulate the busiobject within a JSP page, <jsp:useBean> tag helps in such task.
o The <jsp:useBean> action tag has certain attributes that add extra characteristics to it, some attributes specific to <jsp:use
Id : represents the name assigned to a JavaBean, which is later used as a variable to access the JavaBean
Class : takes the qualified class name to create a JavaBean instance if the JavaBean instance is not found in the given scope.
beanNameo takes the qualified class name or expression of a JavaBean to create a
JavaBean. o Class & beanName can not be used together.o We can not use expressions to create instance of JavaBean from class
attribute, for that we have to use beanName attribute.
Unit 4 – Java
| 2160707– Advanced Java
Enlist and explain the use of action tags in JSP.
Action tags are specific to a JSP page. When a JSP container encounters an action tag while translating a JSP page into a servlet, it generates a Java code corresponding to the task to be performed by the action tag. The following are some important action tags available in JSP page:
The <jsp:include> action tag facilitates Java programmers in including a static or dynamic resource, such as an HTML or JSP page in the current JSP page.If the resource to be included is static then its content is directly included.If the resource is dynamic then first it is processed and result is included in page.
<jsp:include page=”test.jsp” />
The <jsp:forward> tag forwards a JSP request to another resource which can be either static or dynamic. If the request is forwarded to a dynamic resource, a <jsp:param> tag can be used to pass a name and value of a parameter to a resource.
<jsp:forward page=”/header.html” />
The <jsp:param> tag allows Java programmers to pass a name and value of a parameter to a dynamic resource, while including it in a JSP page or forwarding a request to another JSP page.
<jsp:param name=”uname” value=”PM”/>
e business logic from the presentation logic, it is often a good idea to encapsulate the business login in Java object, and then instantiate and use this Java object within a JSP page, <jsp:useBean> tag helps in such task. The <jsp:useBean> action tag has certain attributes that add extra characteristics to it, some attributes specific to <jsp:useBean> are:
: represents the name assigned to a JavaBean, which is later used as a variable to access the JavaBean
: takes the qualified class name to create a JavaBean instance if the JavaBean instance is not found in the given scope. beanName :
takes the qualified class name or expression of a JavaBean to create a JavaBean. Class & beanName can not be used together. We can not use expressions to create instance of JavaBean from class attribute, for that we have to use beanName attribute.
ava Server Page
35
JSP container encounters an action tag while translating a JSP page into a servlet, it generates a Java code corresponding to the task to be
The <jsp:include> action tag facilitates Java programmers in including a static or dynamic resource, such as an HTML or JSP page in the current JSP page. If the resource to be included is static then its content is directly included.
amic then first it is processed and result is included in page.
The <jsp:forward> tag forwards a JSP request to another resource which can be
dynamic resource, a <jsp:param> tag can be used to
The <jsp:param> tag allows Java programmers to pass a name and value of a resource, while including it in a JSP page or forwarding a
e business logic from the presentation logic, it is often a good idea to ness login in Java object, and then instantiate and use this Java
The <jsp:useBean> action tag has certain attributes that add extra characteristics to
: represents the name assigned to a JavaBean, which is later used as a
: takes the qualified class name to create a JavaBean instance if the
takes the qualified class name or expression of a JavaBean to create a
We can not use expressions to create instance of JavaBean from class attribute, for that we have to use beanName attribute.
Prashant Maheta, CE Department | 2160707
Scope : represents the scope in which a JavaBean instance has to be created.o Page scope
<jsp:useBean> action tag is used.o Request scope
page, which processes the saclient by the JSP page.
o Session scopepage invoked in the same session as the JSP page that created the JavaBean.
o Application scopeJSP page in the same application as the JSP page that created the JavaBean.
o Example : <jsp:useBean id=”myBean” class=”MyBeanClass” scope=”session”> ………….</jsp:useBean>
5. <jsp:setProperty> o The <jsp:setProperty> action tag sets
method of a JavaBean.o Before using the <jsp:setProperty> action tag, the JavaBean must be instantiated.o Example:
<jsp:setProperty name=”beanName” property=”uName” value=”6. <jsp:getProperty>
o The <jsp:setPropmethod of a JavaBean and writes the value of the current JspWriter.
o Example: <jsp:getProperty name=”myBean” property=”uName” />
7. <jsp:plugin> o The <jsp:plugin> action tag provides support
in a client Web browser, by using builto The <jsp:plugin> action tag perform the following operations:
Specify whether the component added in the <object> tag is a JavaBean or an applet.
Locate the code that needs to be run. Position an object in the browser window. Specify a URL from which the plug Pass parameter names and values to an object
o Example: <jsp:plugin attributes> ………. </jsp:plugin>
8. <jsp:params> o The <jsp:params> action tag sends the parameters that you want to pass to an
Unit 4 – Java
| 2160707– Advanced Java
represents the scope in which a JavaBean instance has to be created.Page scope : indicates that a JavaBean can be used where <jsp:useBean> action tag is used. Request scope : indicates that a JavaBean can be used from any JSP page, which processes the same request until a response is sent to a client by the JSP page. Session scope : indicates that a JavaBean can be used from any JSP page invoked in the same session as the JSP page that created the JavaBean. Application scope : indicates that a JavaBean caJSP page in the same application as the JSP page that created the JavaBean.
<jsp:useBean id=”myBean” class=”MyBeanClass” scope=”session”>………….
</jsp:useBean>
The <jsp:setProperty> action tag sets the value of a property by using the setter method of a JavaBean. Before using the <jsp:setProperty> action tag, the JavaBean must be instantiated.
<jsp:setProperty name=”beanName” property=”uName” value=”
The <jsp:setProperty> action tag retrives the value of a property by using the getter method of a JavaBean and writes the value of the current JspWriter.
<jsp:getProperty name=”myBean” property=”uName” />
The <jsp:plugin> action tag provides support for including a Java applet or JavaBean in a client Web browser, by using built-in or downloaded Java plugThe <jsp:plugin> action tag perform the following operations:
Specify whether the component added in the <object> tag is a JavaBean or an
Locate the code that needs to be run. Position an object in the browser window. Specify a URL from which the plug-in software is to be downloaded.Pass parameter names and values to an object
<jsp:plugin attributes>
</jsp:plugin>
The <jsp:params> action tag sends the parameters that you want to pass to an
ava Server Page
36
represents the scope in which a JavaBean instance has to be created. : indicates that a JavaBean can be used where
: indicates that a JavaBean can be used from any JSP me request until a response is sent to a
: indicates that a JavaBean can be used from any JSP page invoked in the same session as the JSP page that created the
: indicates that a JavaBean can be used from any JSP page in the same application as the JSP page that created the
<jsp:useBean id=”myBean” class=”MyBeanClass” scope=”session”>
the value of a property by using the setter
Before using the <jsp:setProperty> action tag, the JavaBean must be instantiated.
<jsp:setProperty name=”beanName” property=”uName” value=”PM” />
erty> action tag retrives the value of a property by using the getter method of a JavaBean and writes the value of the current JspWriter.
for including a Java applet or JavaBean in or downloaded Java plug-in.
Specify whether the component added in the <object> tag is a JavaBean or an
in software is to be downloaded.
The <jsp:params> action tag sends the parameters that you want to pass to an
Prashant Maheta, CE Department | 2160707
applet or JavaBean.o Example:
<jsp:params><!- one or more jsp:param tags
</jsp:params>9. <jsp:fallback>
o The <jsp:fallback> action tag is allows you to specify a text displayed if the required plug
o This tag must be used as a child tag with <jsp:plugin> action tag.o Example:
<jsp:fallback>Text message that has to be displayed if the plugin cannot be started
</jsp:fallback>10. <jsp:attribute>
o The <jsp:attribute> action tag is used to specify the value of a standard or custom action attribute.
o Example: <jsp:setProperty name=”myBean”>
<jsp:attribute name=”property”>uName</jsp:attribute><jsp:attribute name=”value”>
</jsp:setProperty>11. <jsp:body>
o The <jsp:body> action tag is used to specify the content (or body) of a standard or custom action tag.
o Example: <jsp:userBean id=”myBean”>
…….. <jsp:body> ……………. </jsp:body>
</jsp:myBean>12. <jsp:element>
o The <jsp:element> actian XML element.
o Example: <jsp:element name=”mytag”>
<jsp:attribute name=”myatt”>My Value </jsp:attribute></jsp:element>
13. <jsp:text> o A <jsp:text> tag is used to enclose template data in an XML o The content of the <jsp:text> body is passed to the implicit object o Example:
<jsp:text> Hello world from the action tag </jsp:text>
Unit 4 – Java
| 2160707– Advanced Java
applet or JavaBean.
<jsp:params> one or more jsp:param tags -->
</jsp:params>
The <jsp:fallback> action tag is allows you to specify a text displayed if the required plug-in cannot run. This tag must be used as a child tag with <jsp:plugin> action tag.
<jsp:fallback> Text message that has to be displayed if the plugin cannot be started
</jsp:fallback>
he <jsp:attribute> action tag is used to specify the value of a standard or custom
<jsp:setProperty name=”myBean”> <jsp:attribute name=”property”>uName</jsp:attribute><jsp:attribute name=”value”>PM</jsp:attribute>
/jsp:setProperty>
The <jsp:body> action tag is used to specify the content (or body) of a standard or custom action tag.
<jsp:userBean id=”myBean”>
<jsp:body> ……………. </jsp:body> </jsp:myBean>
The <jsp:element> action tag is used to dynamically define the value of the tag of an XML element.
<jsp:element name=”mytag”> <jsp:attribute name=”myatt”>My Value </jsp:attribute>
</jsp:element>
A <jsp:text> tag is used to enclose template data in an XML tag.The content of the <jsp:text> body is passed to the implicit object
<jsp:text> Hello world from the action tag </jsp:text>
ava Server Page
37
The <jsp:fallback> action tag is allows you to specify a text message that is
This tag must be used as a child tag with <jsp:plugin> action tag.
Text message that has to be displayed if the plugin cannot be started
he <jsp:attribute> action tag is used to specify the value of a standard or custom
<jsp:attribute name=”property”>uName</jsp:attribute>
The <jsp:body> action tag is used to specify the content (or body) of a standard or
on tag is used to dynamically define the value of the tag of
<jsp:attribute name=”myatt”>My Value </jsp:attribute>
tag. The content of the <jsp:text> body is passed to the implicit object out.
Prashant Maheta, CE Department | 2160707
3 Explain JSP standard tag library (JSTL) with examples.
Initially, web designers used scriplets in JSP pages
This resulted in readability issues and also made it difficult to maintain the JSP page.
Custom tags were introduced to overcome the problems faced in using scriplets, they had some limitations too.
Web designers had to spend ausing them.
This meant that web designers were often left with little time to concentrate on the designing of web pages.
The introduction of JSTL has helped web designers overcome the shortcotags, by encapsulating the common functionalities included the use of tag libraries, such as core, SQL, and XML.
The main features of JSTL are:o Provides support for conditional processing and Uniform Resource Locator (URL)
related actions. o Provides the XML tag library, which helps you to manipulate XML documents.o Enables Web applications to be accessed globally by providing the
internationalization tag library.o Enables interaction with relational databases by using various SQL commands.o Provides series of functions to perform manipulations.
Tag Libraries in JSTL:
Tag Library Function
Core tag library Variable support
Flow Control
Iterator
URL management
Miscellaneous
XML tag library Flow control
Transformation
Locale
Internationalizatio
n tag library
Message
formatting
Number and date
formatting
SQL tag library Database
manipulation
Unit 4 – Java
| 2160707– Advanced Java
Explain JSP standard tag library (JSTL) with examples.
Initially, web designers used scriplets in JSP pages to generate dynamic content.
bility issues and also made it difficult to maintain the JSP page.
Custom tags were introduced to overcome the problems faced in using scriplets, they had
Web designers had to spend a lot of time in coding, packaging, and testing these tags before
This meant that web designers were often left with little time to concentrate on the
The introduction of JSTL has helped web designers overcome the shortcotags, by encapsulating the common functionalities included the use of tag libraries, such as
The main features of JSTL are: Provides support for conditional processing and Uniform Resource Locator (URL)
Provides the XML tag library, which helps you to manipulate XML documents.Enables Web applications to be accessed globally by providing the internationalization tag library. Enables interaction with relational databases by using various SQL commands.
ides series of functions to perform manipulations.
Function URI
Variable support
Flow Control
Iterator
URL management
Miscellaneous
http://java.sun.com/jsp/jstl/core
control
Transformation
Locale
http://java.sun.com/jsp/jstl/xml
Message
formatting
Number and date
formatting
http://java.sun.com/jsp/jstl/fmt
Database
manipulation
http://java.sun.com/jsp/jstl/sql
ava Server Page
38
Explain JSP standard tag library (JSTL) with examples.
to generate dynamic content.
bility issues and also made it difficult to maintain the JSP page.
Custom tags were introduced to overcome the problems faced in using scriplets, they had
lot of time in coding, packaging, and testing these tags before
This meant that web designers were often left with little time to concentrate on the
The introduction of JSTL has helped web designers overcome the shortcomings of custom tags, by encapsulating the common functionalities included the use of tag libraries, such as
Provides support for conditional processing and Uniform Resource Locator (URL)-
Provides the XML tag library, which helps you to manipulate XML documents. Enables Web applications to be accessed globally by providing the
Enables interaction with relational databases by using various SQL commands.
prefix
http://java.sun.com/jsp/jstl/core c
http://java.sun.com/jsp/jstl/xml x
fmt
sql
Prashant Maheta, CE Department | 2160707
Functions Library Collection length
String
manipulation
Example of Core tag library:<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><html> <head> <title><c:choose> Tag Example</title></head> <body> <c:set var="salary" scope="session" value="${2000*2}"/><p>Your salary is : <c:out value="${salary}"/></p><c:choose> <c:when test="${salary <= 0}"> Salary is very low to survive. </c:when> <c:when test="${salary > 1000}"> Salary is very good. </c:when> <c:otherwise> No comment... </c:otherwise> </c:choose> </body> </html>
4 What is XML tag library? Explain the XML core tags and show their use.
The JSTL XML tags provide a JSP
Following is the syntax to include JSTL XML library in your JSP.
The JSTL XML tag library has custom tags for interacting with XML data. This includes parsing XML, transforming XML
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
Before you proceed with the examples, you would need to copy following two XML and
XPath related libraries into your <Tomcat
Unit 4 – Java
| 2160707– Advanced Java
Collection length
manipulation
http://java.sun.com/jsp/jstl/functi
ons
Example of Core tag library: <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:choose> Tag Example</title>
<c:set var="salary" scope="session" value="${2000*2}"/> <p>Your salary is : <c:out value="${salary}"/></p>
<c:when test="${salary <= 0}"> Salary is very low to survive.
c:when test="${salary > 1000}">
What is XML tag library? Explain the XML core tags and show
tags provide a JSP-centric way of creating and manipulating XML documents. Following is the syntax to include JSTL XML library in your JSP.
The JSTL XML tag library has custom tags for interacting with XML data. This includes parsing XML, transforming XML data, and flow control based on XPath expressions.
uri="http://java.sun.com/jsp/jstl/xml" %>
Before you proceed with the examples, you would need to copy following two XML and XPath related libraries into your <Tomcat Installation Directory>\lib:
ava Server Page
39
http://java.sun.com/jsp/jstl/functi fn
What is XML tag library? Explain the XML core tags and show
centric way of creating and manipulating XML documents.
The JSTL XML tag library has custom tags for interacting with XML data. This includes data, and flow control based on XPath expressions.
Before you proceed with the examples, you would need to copy following two XML and
Prashant Maheta, CE Department | 2160707
XercesImpl.jar: Download it from xalan.jar: Download it from
Following is the list of XML JSTL Tags:
Tag
<x:out> Like <%= ... >, but for XPath expressions.
<x:parse> Use to parse XML data specified either via an attribute or in the tag body.
<x:set > Sets a variable to the
<x:if >
Evaluates a test XPath expression and if it is true, it processes its body. If the test condition is false, the body is ignored.
<x:forEach> To loop over nodes in an XML document.
<x:choose>
Simple conditional tag that establishes a context conditional operations, marked by <when> and <otherwise>
<x:when > Subtag of <choose> that includes its body if its expression evalutes to 'true'
<x:otherwise >
Subtag of <choose> that follows <when> tags and runs only if all of the prior conditions evaluated to 'false'
<x:transform > Applies an XSL transformation on a XML document
<x:param > Use along with the transform tag to set a parameter in the XSLT stylesheet
5 Explain SQL Tab Libraries
The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs) such as Oracle, mySQL, or Microsoft SQL Server.
Following is the syntax to include JSTL SQL library in your JSP:<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
Following is the list of SQL JSTL Tags:
Tag Description
<sql:setDataSource> Creates a simple DataSource suitable only for
<sql:query> Executes the SQL query defined in its body or through the sql attribute.
<sql:update> Executes the SQL update defined in its body or through the sql attribute.
<sql:param> Sets a parameter in an SQL statement to the specified value.
<sql:dateParam> Sets a parameter in an SQL statement to the specified java.util.Date
<sql:transaction > Provides nested database action
Unit 4 – Java
| 2160707– Advanced Java
Download it from http://www.apache.org/dist/xerces/j/Download it from http://xml.apache.org/xalan-j/index.html
Following is the list of XML JSTL Tags:
Description
Like <%= ... >, but for XPath expressions.
Use to parse XML data specified either via an attribute or in the tag body.
Sets a variable to the value of an XPath expression.
Evaluates a test XPath expression and if it is true, it processes its body. If the test condition is false, the body is ignored.
To loop over nodes in an XML document.
Simple conditional tag that establishes a context for mutually exclusive conditional operations, marked by <when> and <otherwise>
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 prior conditions evaluated to 'false'
Applies an XSL transformation on a XML document
Use along with the transform tag to set a parameter in the XSLT stylesheet
Libraries.
The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs) such as Oracle, mySQL, or Microsoft SQL Server. Following is the syntax to include JSTL SQL library in your JSP:
i="http://java.sun.com/jsp/jstl/sql" %>
Following is the list of SQL JSTL Tags:
Description
Creates a simple DataSource suitable only for prototyping
Executes the SQL query defined in its body or through the sql attribute.
Executes the SQL update defined in its body or through the sql attribute.
Sets a parameter in an SQL statement to the specified value.
Sets a parameter in an SQL statement to the specified java.util.Date
Provides nested database action elements with a shared Connection
ava Server Page
40
http://www.apache.org/dist/xerces/j/ j/index.html
Use to parse XML data specified either via an attribute or in the tag body.
Evaluates a test XPath expression and if it is true, it processes its body. If the
for mutually exclusive conditional operations, marked by <when> and <otherwise>
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 prior
Use along with the transform tag to set a parameter in the XSLT stylesheet
The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs)
prototyping
Executes the SQL query defined in its body or through the sql attribute.
Executes the SQL update defined in its body or through the sql attribute.
Sets a parameter in an SQL statement to the specified value.
Sets a parameter in an SQL statement to the specified java.util.Date
elements with a shared Connection.
Prashant Maheta, CE Department | 2160707
6 Explain Core JSTL Tags
The core group of tags are the most frequently used JSTL tags. Following is the syntax to include JSTL Core library in your JSP:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
There are following Core JSTL Tags:
Tag
<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 pa
<c:catch> Catches any Throwable that occurs in its body and optionally exposes it.
<c:if> Simple conditional tag which evalutes its body if the supplied condition is true.
<c:choose>
Simple conditional tag that establishes a context for mutually exclusive conditional operations, marked by <when> and <otherwise>
<c:when> Subtag of <choose> that includes its body if its condition evalutes to 'true'.
<c:otherwise >
Subtag of <choose> that follows <when> tags and runs only if all of the prior conditions evaluated to 'false'.
<c:import>
Retrieves an absolute or relative URL and exposes its contents to either the page, a String in 'var', or a Reader in 'varReader'.
<c:forEach >
The basic iteration tag, accepting many different collection types 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.
<c:redirect > Redirects to a new URL.
<c:url> Creates a URL with optional query parameters
7 Explain Session Handling with example.
HTTP is a "stateless" protocol which means each time a client retrieves a Web page, client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request.
Still there are following three ways to maintain session between web client and web
server:
Unit 4 – Java
| 2160707– Advanced Java
Explain Core JSTL Tags
The core group of tags are the most frequently used JSTL tags. Following is the syntax to include JSTL Core library in your JSP: <%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>
There are following Core JSTL Tags:
Description
Like <%= ... >, but for expressions.
Sets the result of an expression evaluation in a 'scope'
Removes a scoped variable (from a particular scope, if specified).
Catches any Throwable that occurs in its body and optionally exposes it.
Simple conditional tag which evalutes its body if the supplied condition is true.
Simple conditional tag that establishes a context for mutually exclusive onal operations, marked by <when> and <otherwise>
Subtag of <choose> that includes its body if its condition evalutes to 'true'.
Subtag of <choose> that follows <when> tags and runs only if all of the prior conditions evaluated to 'false'.
Retrieves an absolute or relative URL and exposes its contents to either the page, a String in 'var', or a Reader in 'varReader'.
eration tag, accepting many different collection types and supporting subsetting and other functionality .
Iterates over tokens, separated by the supplied delimeters.
Adds a parameter to a containing 'import' tag's URL.
Redirects to a new URL.
Creates a URL with optional query parameters
Explain Session Handling with example.
HTTP is a "stateless" protocol which means each time a client retrieves a Web page, client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request. Still there are following three ways to maintain session between web client and web
ava Server Page
41
The core group of tags are the most frequently used JSTL tags. Following is the syntax to
rticular scope, if specified).
Catches any Throwable that occurs in its body and optionally exposes it.
Simple conditional tag which evalutes its body if the supplied condition is true.
Simple conditional tag that establishes a context for mutually exclusive onal operations, marked by <when> and <otherwise>
Subtag of <choose> that includes its body if its condition evalutes to 'true'.
Subtag of <choose> that follows <when> tags and runs only if all of the prior
Retrieves an absolute or relative URL and exposes its contents to either the
eration tag, accepting many different collection types and supporting
HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the client opens a separate connection to the Web server and the server automatically does
Still there are following three ways to maintain session between web client and web
Prashant Maheta, CE Department | 2160707
Cookies:
A webserver can assign a unique session ID as a cookie to each web client and for
subsequent requests from the client they can be recognized using the received cookie.
This may not be an effective way because many time browser does not support a cookie, so I would not recommend to use this procedure to maintain the sessions.
Hidden Form Fields:
A web server can send a hidden HTML form field along with a unique session ID as follows:
<input type="hidden"
This entry means that, when the form is submitted, the specified name and value are automatically included in the GET or POST data. Each time when web browser sends request back, then session_id value can be used to keep the track of different web browsers.
This could be an effective way of keeping track of the session but clicking on a regular (<A HREF...>) hypertext link does not result in a form submission, so hidden form fields also cannot support general session tracking.
URL Rewriting:
You can append some extra
the server can associate that session identifier with data it has stored about that session.
For example, with http://tutorialspoint.com/file.htm;sessionid=12345, the session identifier is attached as sessionid=12345 which can be accessed at the web server to identify the client.
URL rewriting is a better way to maintain sessions and works for the browsers when they don't support cookies but here drawback is that you would have generate every URL dynamically to assign a session ID though page is simple static HTML page.
Session Tracking Example :
Index.html
<html> <body> <form action="welcome.jsp"> <input type="text" name="uname"> <input type="submit" value="go"><br/> </form> </body> </html>
Unit 4 – Java
| 2160707– Advanced Java
webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie.
This may not be an effective way because many time browser does not support a cookie, would not recommend to use this procedure to maintain the sessions.
A web server can send a hidden HTML form field along with a unique session ID as
"hidden" name="sessionid" value="12345">
that, when the form is submitted, the specified name and value are automatically included in the GET or POST data. Each time when web browser sends request back, then session_id value can be used to keep the track of different web
n effective way of keeping track of the session but clicking on a regular (<A HREF...>) hypertext link does not result in a form submission, so hidden form fields also cannot support general session tracking.
You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session.
For example, with http://tutorialspoint.com/file.htm;sessionid=12345, the session ed as sessionid=12345 which can be accessed at the web server to
URL rewriting is a better way to maintain sessions and works for the browsers when they don't support cookies but here drawback is that you would have generate every URL dynamically to assign a session ID though page is simple static HTML page.
Session Tracking Example :
<form action="welcome.jsp"> <input type="text" name="uname"> <input type="submit" value="go"><br/>
ava Server Page
42
webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie.
This may not be an effective way because many time browser does not support a cookie, would not recommend to use this procedure to maintain the sessions.
A web server can send a hidden HTML form field along with a unique session ID as
that, when the form is submitted, the specified name and value are automatically included in the GET or POST data. Each time when web browser sends request back, then session_id value can be used to keep the track of different web
n effective way of keeping track of the session but clicking on a regular (<A HREF...>) hypertext link does not result in a form submission, so hidden form fields
data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session.
For example, with http://tutorialspoint.com/file.htm;sessionid=12345, the session ed as sessionid=12345 which can be accessed at the web server to
URL rewriting is a better way to maintain sessions and works for the browsers when they don't support cookies but here drawback is that you would have generate every URL dynamically to assign a session ID though page is simple static HTML page.
Prashant Maheta, CE Department | 2160707
Welcome.jsp
<html> <body> <% String name=request.getParameter("uname"); out.print("Welcome "+name); session.setAttribute("user",name); <a href="second.jsp">second jsp page</a> %> </body> </html>
Second.jsp
<html> <body> <% String name=(String)session.getAttribute("user"); out.print("Hello "+name); %> </body> </html>
8 Write a program to
<%@page contentType="text/html"%><%@page pageEncoding="UTF<%@page import="java.sql.*"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html> <head> <meta http-equiv="Content <title>Example of Java Server Page with JDBC</title> </head> <body> <%
Unit 4 – Java
| 2160707– Advanced Java
String name=request.getParameter("uname"); out.print("Welcome "+name);
session.setAttribute("user",name);
<a href="second.jsp">second jsp page</a>
String name=(String)session.getAttribute("user");
Write a program to insert records in a table using JSP.
<%@page contentType="text/html"%> pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%> //W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
equiv="Content-Type" content="text/html; charset=UTF-8"><title>Example of Java Server Page with JDBC</title>
ava Server Page
43
a table using JSP.
8">
Prashant Maheta, CE Department | 2160707
String u=request.getParameter("userid");String p=request.getParameter("password");String n=request.getParameter("sname");String e=request.getParameter("eid");String a=request.getParameter("addr");try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:sgc","","");/* Passing argument through the question mark */ PreparedStatement ps=con.prepareStateme ps.setString(2,p); ps.setString(3,n); ps.setString(4,a); ps.setString(5,e); int i=ps.executeUpdate(); /*Set the Update query command */ if(i!=0) { response.sendRedirect("index.jsp?msg=Thank You for registering with us in Mrbool !"); } else { response.sendRedirect("registerinsert.jsp?msg=Insertion Failed!! Please try again!!! "); } con.close(); } catch(Exception ex) { out.println(ex); } %> </body> </html>
Unit 4 – Java
| 2160707– Advanced Java
String u=request.getParameter("userid"); String p=request.getParameter("password"); String n=request.getParameter("sname"); String e=request.getParameter("eid");
a=request.getParameter("addr");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:sgc","","");
/* Passing argument through the question mark */ PreparedStatement ps=con.prepareStatement("insert into login values(?,?,?,?,?)") ;
int i=ps.executeUpdate(); /*Set the Update query command */
response.sendRedirect("index.jsp?msg=Thank You for registering with us in
response.sendRedirect("registerinsert.jsp?msg=Insertion Failed!! Please try
ava Server Page
44
Connection con=DriverManager.getConnection("jdbc:odbc:sgc","","");
nt("insert into login values(?,?,?,?,?)") ;
response.sendRedirect("index.jsp?msg=Thank You for registering with us in
response.sendRedirect("registerinsert.jsp?msg=Insertion Failed!! Please try
Prashant Maheta, CE Department | 2160707
1. Explain JSF Request Processing Life Cycle.
JSF application lifecycle consist of six phases which are as follows
o Restore view phase
o Apply request values phase; process events
o Process validations phase; process events
o Update model values phase; process events
o Invoke application phase; process events
o Render response phase
The six phases show the order in which JSF processes a form. The list shows the phases in their likely order of
Phase 1: Restore view
JSF begins the restore view phase as soon as a link or a button is clicked and JSF receives a request.
During this phase, the JSF builds the view, wires event handlers and validators to components and saves the view in the FacesContext instance. The FacesContext instance will now contains all the information required to process a request.
Unit 5 – Java Server Faces
| 2160707– Advanced Java
JSF Request Processing Life Cycle.
JSF application lifecycle consist of six phases which are as follows :
Restore view phase
Apply request values phase; process events
validations phase; process events
Update model values phase; process events
Invoke application phase; process events
Render response phase
The six phases show the order in which JSF processes a form. The list shows the phases execution with event processing at each phase.
JSF begins the restore view phase as soon as a link or a button is clicked and JSF receives
During this phase, the JSF builds the view, wires event handlers and validators to components and saves the view in the FacesContext instance. The FacesContext instance will now contains all the information required to process a request.
Java Server Faces
45
The six phases show the order in which JSF processes a form. The list shows the phases execution with event processing at each phase.
JSF begins the restore view phase as soon as a link or a button is clicked and JSF receives
During this phase, the JSF builds the view, wires event handlers and validators to UI components and saves the view in the FacesContext instance. The FacesContext instance
Prashant Maheta, CE Department | 2160707
Phase 2: Apply request values
After the component tree is created/restored, each component in codecode method to extract its new value from the request parameters. Component stores this value. If the conversion fails, an error message is generated and queued on FacesContext. This message will be displayed during the render response with any validation errors.
If any decode methods / event listeners called renderResponse on the current FacesContext instance, the JSF moves to the render response phase.
Phase 3: Process validation
During this phase, the JSF processes all examines the component attribute rules for the validation and compares these rules to the local value stored for the component.
If the local value is invalid, the JSF adds an error message to the FacesContext insand the life cycle advances to the render response phase and display the same page again with the error message.
Phase 4: Update model values
After the JSF checks that the data is valid, it walks over the component tree and set the corresponding server-update the bean properties corresponding to input component's value attribute.
If any updateModels methods called renderResponse on the current FacesContext instance, the JSF moves
Phase 5: Invoke application
During this phase, the JSF handles any applicationform / linking to another page.
Phase 6: Render response
During this phase, the JSF asks container/applicatapplication is using JSP pages. For initial request, the components represented on the page will be added to the component tree as the JSP container executes the page. If this is not an initial request, the component trbe added again. In either case, the components will render themselves as the JSP container/Application server traverses the tags in the page.
After the content of the view is rendered, the response state is savrequests can access it and it is available to the restore view phase.
Unit 5 – Java Server Faces
| 2160707– Advanced Java
Phase 2: Apply request values
After the component tree is created/restored, each component in codecode method to extract its new value from the request parameters. Component stores this value. If the conversion fails, an error message is generated and queued on FacesContext. This message will be displayed during the render response with any validation errors.
If any decode methods / event listeners called renderResponse on the current FacesContext instance, the JSF moves to the render response phase.
Phase 3: Process validation
During this phase, the JSF processes all validators registered on component tree. It examines the component attribute rules for the validation and compares these rules to the local value stored for the component.
If the local value is invalid, the JSF adds an error message to the FacesContext insand the life cycle advances to the render response phase and display the same page again with the error message.
Phase 4: Update model values
After the JSF checks that the data is valid, it walks over the component tree and set the -side object properties to the components' local values. The JSF will
update the bean properties corresponding to input component's value attribute.
If any updateModels methods called renderResponse on the current FacesContext instance, the JSF moves to the render response phase.
Phase 5: Invoke application
During this phase, the JSF handles any application-level events, such as submitting a form / linking to another page.
Phase 6: Render response
During this phase, the JSF asks container/application server to render the page if the application is using JSP pages. For initial request, the components represented on the page will be added to the component tree as the JSP container executes the page. If this is not an initial request, the component tree is already built so components need not to be added again. In either case, the components will render themselves as the JSP container/Application server traverses the tags in the page.
After the content of the view is rendered, the response state is saved so that subsequent requests can access it and it is available to the restore view phase.
Java Server Faces
46
After the component tree is created/restored, each component in component tree uses decode method to extract its new value from the request parameters. Component stores this value. If the conversion fails, an error message is generated and queued on FacesContext. This message will be displayed during the render response phase, along
If any decode methods / event listeners called renderResponse on the current
validators registered on component tree. It examines the component attribute rules for the validation and compares these rules to
If the local value is invalid, the JSF adds an error message to the FacesContext instance, and the life cycle advances to the render response phase and display the same page
After the JSF checks that the data is valid, it walks over the component tree and set the side object properties to the components' local values. The JSF will
update the bean properties corresponding to input component's value attribute.
If any updateModels methods called renderResponse on the current FacesContext
level events, such as submitting a
ion server to render the page if the application is using JSP pages. For initial request, the components represented on the page will be added to the component tree as the JSP container executes the page. If this
ee is already built so components need not to be added again. In either case, the components will render themselves as the JSP
ed so that subsequent
Prashant Maheta, CE Department | 2160707
2. Explain JSF Expression Language with Example.
JSF provides a rich expression language. We can write normal operations using #{operation-expression} are following.
Provides easy access to elements of a collection which can be a list, map or an array.
Provides easy access to predefined objects such as request. Arithmetic, logical, relational o Automatic type conversion. Shows missing values as empty strings instead of NullPointerException.
Let us understand it with example :
UserData.java
import java.io.Serializableimport java.util.Date; import javax.faces.beanimport javax.faces.bean @ManagedBean(name @SessionScoped public class UserData private static final long private Date createTime private String message public Date getCreateTime return(createTime } public String getMessage return(message); } }
home.xhtml
<?xml version="1.0" encoding<!DOCTYPE html PUBLIC ""http://www.w3.org/TR/xhtml1/DTD/xhtml1<html xmlns="http://www.w3.org/1999/xhtml"
Unit 5 – Java Server Faces
| 2160707– Advanced Java
Expression Language with Example.
JSF provides a rich expression language. We can write normal operations using expression} notation. Some of the advantages of JSF Expression languages
Provides easy access to elements of a collection which can be a list, map or an
Provides easy access to predefined objects such as request. Arithmetic, logical, relational operations can be done using expression language.Automatic type conversion. Shows missing values as empty strings instead of NullPointerException.
Let us understand it with example :
Serializable;
bean.ManagedBean; bean.SessionScoped;
name = "userData", eager = true)
implements Serializable {
long serialVersionUID = 1L;
createTime = new Date(); message = "Hello World!";
getCreateTime() { createTime);
getMessage() {
encoding="UTF-8"?> !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> "http://www.w3.org/1999/xhtml"
Java Server Faces
47
JSF provides a rich expression language. We can write normal operations using notation. Some of the advantages of JSF Expression languages
Provides easy access to elements of a collection which can be a list, map or an
perations can be done using expression language.
Shows missing values as empty strings instead of NullPointerException.
//W3C//DTD XHTML 1.0 Transitional//EN"
Prashant Maheta, CE Department | 2160707
xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" <h:head> <title>JSF Tutorial! </h:head> <h2>Expression Language Example Creation time: <h:outputText value <br/><br/>Message: <h:outputText value </h:body> </html>
3. Explain JSF Structure/Architecture.
Unit 5 – Java Server Faces
| 2160707– Advanced Java
"http://java.sun.com/jsf/core" "http://java.sun.com/jsf/html">
JSF Tutorial!</title>
Expression Language Example</h2>
value="#{userData.createTime}"/> Message:
value="#{userData.message}"/>
Structure/Architecture.
Java Server Faces
48
Prashant Maheta, CE Department | 2160707
Similar to most of the popular Web Application Frameworks, JSF implements MVC design pattern. The implementation of MVC design pattern helps to design different components separately, and each of logic.
For example, you can crate view component for presentation logic and model component for business logic implementation. A controller is another component, which controls the execution of various model manother in a Web Application.
In JSF, you have a single front controller, which handles all JSF requests mapped to it.
The controller part of the JSF architecture consists of a Controller Servlet, that is, FacesServlet, a centralized configuration file, faceshandlers for the Web Application.
The Model in JSF architecturefrom the model components such as the database these values.
The UI Components are rendered in different ways according to the type of the client. The view delegates this task to separate the renderers , each taking care of one specific output type, such as HTML.
JSF Structure/Architecture is consists of following components:
o The template (most commonly jsp) defines the interface
o The faces-config defines the navigation and the backing beans
o Backing beans handle action processing, navigation processing, and to the logic (business) layer
o Wrapper bean wraps the data POJOs for JSF handling
o Logic layer beans can be injected as defined in the faces
o Model is basic data POJO
JSP Template
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<f:view>
<html><head><title>Items</title></head><body>
<h:form id="items">
<h:dataTable id="itemlist” value="#{JsfBean.allItems}” var="entry">
<h:column>
Unit 5 – Java Server Faces
| 2160707– Advanced Java
Similar to most of the popular Web Application Frameworks, JSF implements MVC design pattern. The implementation of MVC design pattern helps to design different components separately, and each of these components implements different types of
, you can crate view component for presentation logic and model component for business logic implementation. A controller is another component, which controls the execution of various model methods and navigates from one view to another in a Web Application. In JSF, you have a single front controller, which handles all JSF requests mapped to it.
The controller part of the JSF architecture consists of a Controller Servlet, that is, FacesServlet, a centralized configuration file, faces-config.xml, and a set of event handlers for the Web Application.
The Model in JSF architecture is a set of server-side JavaBeans that retrieves the values from the model components such as the database and defines methods on the basis of
The UI Components are rendered in different ways according to the type of the client. The view delegates this task to separate the renderers , each taking care of one specific output type, such as HTML.
Structure/Architecture is consists of following components:
The template (most commonly jsp) defines the interface
config defines the navigation and the backing beans
Backing beans handle action processing, navigation processing, and to the logic (business) layer
Wrapper bean wraps the data POJOs for JSF handling
Logic layer beans can be injected as defined in the faces-config
Model is basic data POJO (Plain Old Java Object)
uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<html><head><title>Items</title></head><body>
<h:dataTable id="itemlist” value="#{JsfBean.allItems}” var="entry">
Java Server Faces
49
Similar to most of the popular Web Application Frameworks, JSF implements MVC design pattern. The implementation of MVC design pattern helps to design different
these components implements different types of
, you can crate view component for presentation logic and model component for business logic implementation. A controller is another component, which
ethods and navigates from one view to
In JSF, you have a single front controller, which handles all JSF requests mapped to it.
The controller part of the JSF architecture consists of a Controller Servlet, that is, config.xml, and a set of event
side JavaBeans that retrieves the values and defines methods on the basis of
The UI Components are rendered in different ways according to the type of the client. The view delegates this task to separate the renderers , each taking care of one specific
config defines the navigation and the backing beans
Backing beans handle action processing, navigation processing, and connections
config
Prashant Maheta, CE Department | 2160707
<f:facet name="header">
<h:outputText value=""/>
</f:facet>
<h:selectBooleanCheckbox id="itemSelect" value="#{entry.selected}"
rendered="#{entry.canDelete}"/>
<h:outputText value="" rendered="#{not entry.canDelete}"/>
</h:column>
</h:form>
</body></html>
</f:view>
faces-config.xml
Defines the backing beans
Syntax not like Spring
Name used in EL in template
Scope controlled (request, session, etc.)
Defines navigation rules
Based on views
Where from (view)
Which outcome (id)
Where to go (view)
Can match outcomes using wildcards
JSF backing beans
Typical bean with getters and setters and additional methods to handle actions
Store data needed for processing the user actions using setters
Retrieve data using getters and methods
Process actions
Often includes code to wrap data objects
Connects to the rest of the application
Typically via injection
Unit 5 – Java Server Faces
| 2160707– Advanced Java
<f:facet name="header">
<h:outputText value=""/>
<h:selectBooleanCheckbox id="itemSelect" value="#{entry.selected}"
rendered="#{entry.canDelete}"/>
<h:outputText value="" rendered="#{not entry.canDelete}"/>
Defines the backing beans
Syntax not like Spring
Name used in EL in template
Scope controlled (request, session, etc.)
Defines navigation rules
Based on views
Where from (view)
Which outcome (id)
Where to go (view)
Can match outcomes using wildcards
Typical bean with getters and setters and additional methods to handle actions
Store data needed for processing the user actions using setters
Retrieve data using getters and methods
Process actions using methods
Often includes code to wrap data objects
Connects to the rest of the application
Typically via injection
Java Server Faces
50
<h:selectBooleanCheckbox id="itemSelect" value="#{entry.selected}"
Typical bean with getters and setters and additional methods to handle actions
Store data needed for processing the user actions using setters
Prashant Maheta, CE Department | 2160707
JSF wrapper bean
Wraps basic data POJO
Required to avoid putting UI information in the data POJO
Often includes basic setters and
Can be methods as well
Also includes a setter and getter for the data POJO
4. JSF Standard Components
Following are important h:inputText : Renders a HTML input of type="text", text box. h:inputSecret : Renders a HTML input of type="password h:inputTextarea : Renders a HTML textarea field. h:inputHidden : Renders a HTML input of type=" h:selectBooleanCheckbox h:selectManyCheckbox h:selectOneRadio : Renders a single HTML radio button. h:selectOneListbox : Renders a HTML single list box. h:selectManyListbox : Renders a HTML multiple list box. h:selectOneMenu : Renders a HTML combo box.
h:outputText : Renders a HTML text.
5. JSF Facelet Tags
JSF provides special tags to create common layout for a web applicationtags. These tags gives flexibility to manage common parts of a multiple pages at one place.
Templates <ui:insert> <ui:define> <ui:include> <ui:define>
Parameters <ui:param>
Custom Remove
Unit 5 – Java Server Faces
| 2160707– Advanced Java
Wraps basic data POJO
Required to avoid putting UI information in the data POJO
Often includes basic setters and getters for the UI related properties
Can be methods as well
Also includes a setter and getter for the data POJO
JSF Standard Components
Following are important Basic Tags in JSF 2.0: : Renders a HTML input of type="text", text box.
: Renders a HTML input of type="password", text box. : Renders a HTML textarea field.
: Renders a HTML input of type="hidden". h:selectBooleanCheckbox : Renders a single HTML check box. h:selectManyCheckbox : Renders a group of HTML check boxes.
: Renders a single HTML radio button. : Renders a HTML single list box.
: Renders a HTML multiple list box. : Renders a HTML combo box.
: Renders a HTML text.
JSF provides special tags to create common layout for a web applicationtags. These tags gives flexibility to manage common parts of a multiple pages at one
Java Server Faces
51
JSF provides special tags to create common layout for a web application called facelets tags. These tags gives flexibility to manage common parts of a multiple pages at one
Prashant Maheta, CE Department | 2160707
6. JSF Validation Tags
f:validateLength : Validates length of a string f:validateLongRange : f:validateDoubleRange f:validateRegex : Validate JSF component with a given regular expression. Custom Validator : Creating a custom validator
7. JSF Database Access.
We can easily integrate JDBC with JSF for Database Access, let’s understand that with
example.
UserData.java
import java.io.Serializableimport java.sql.Connectionimport java.sql.DriverManagerimport java.sql.PreparedStatementimport java.sql.ResultSetimport java.sql.SQLExceptionimport java.util.ArrayListimport java.util.List; import javax.faces.beanimport javax.faces.beanimport javax.faces.event @ManagedBean(name @SessionScoped public class UserData private static final public List<Author ResultSet rs = null PreparedStatement Connection con = String stm = "Select * from authors" List<Author> records try { pst = con.prepareStatement
Unit 5 – Java Server Faces
| 2160707– Advanced Java
Validates length of a string : Validates range of numeric value
f:validateDoubleRange : Validates range of float value date JSF component with a given regular expression.
Creating a custom validator.
We can easily integrate JDBC with JSF for Database Access, let’s understand that with
Serializable; Connection; DriverManager; PreparedStatement; ResultSet; SQLException; ArrayList;
;
bean.ManagedBean; bean.SessionScoped; event.ComponentSystemEvent;
name = "userData", eager = true)
UserData implements Serializable {
final long serialVersionUID = 1L;
Author> getAuthors(){ null;
PreparedStatement pst = null; = getConnection();
"Select * from authors"; records = new ArrayList<Author>();
prepareStatement(stm);
Java Server Faces
52
date JSF component with a given regular expression.
We can easily integrate JDBC with JSF for Database Access, let’s understand that with
Prashant Maheta, CE Department | 2160707
pst.execute(); rs = pst.getResultSet while(rs.next()){ Author author author.setId( author.setName records.add(author } } catch (SQLException e.printStackTrace } return records; } public Connection Connection con = String url = "jdbc:postgresql://localhost/testdb" String user = "user1" String password try { con = DriverManager System.out.println } catch (SQLException System.out.println } finally{ } return con; } }
Home.xhtml
<?xml version="1.0" encoding<!DOCTYPE html PUBLIC ""http://www.w3.org/TR/xhtml1/DTD/xhtml1<html xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html"
Unit 5 – Java Server Faces
| 2160707– Advanced Java
getResultSet();
()){ author = new Author();
(rs.getInt(1)); setName(rs.getString(2));
author);
SQLException e) { printStackTrace();
Connection getConnection(){ = null;
"jdbc:postgresql://localhost/testdb"; "user1";
password = "user1";
DriverManager.getConnection(url, user, password); println("Connection completed.");
SQLException ex) { println(ex.getMessage());
encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
"http://www.w3.org/1999/xhtml" "http://java.sun.com/jsf/core" "http://java.sun.com/jsf/html">
Java Server Faces
53
//W3C//DTD XHTML 1.0 Transitional//EN"
Prashant Maheta, CE Department | 2160707
<h:head> <title>JSF Tutorial!</title> <h:outputStylesheet library </h:head> <h2>JDBC Integration Example <h:dataTable value="#{userData.authors}" styleClass="authorTable" headerClass="authorTableHeader" rowClasses="authorTableOddRow,authorTableEvenRow" <h:column><f:facet name #{c.id} </h:column> <h:column><f:facet name #{c.name} </h:column> </h:dataTable> </h:body> </html>
Unit 5 – Java Server Faces
| 2160707– Advanced Java
</title> library="css" name="styles.css" />
JDBC Integration Example</h2> "#{userData.authors}" var="c"
"authorTableHeader"
"authorTableOddRow,authorTableEvenRow"> name="header">Author ID</f:facet>
name="header">Name</f:facet>
Java Server Faces
54
Prashant Maheta, CE Department | 2160707
1. Write a note on Hibernate with its Architecture and Deach part in brief.
In order to persist data to a database, Hibernate create an
class mapped with database table).
This object is called Transient object as they are not yet associated with the session or not yet persisted to a database.
To persist the object to database, the instance of
SessionFactory is a singleton instance which implements Factory design pattern. SessionFactory loads hibernate.cfg.xml file and with the help of ConnectionProvider implements all the configuration settings on a d
Each database connection in Hibernate is created by creating an instance of Session interface.
Session represents a single connection with database.
Session objects are created from
Each transaction represents a single atomultiple transactions.
Here are some of the part of the hibernate architecture
Unit 8
2160707– Advanced Java
Write a note on Hibernate with its Architecture and D
Fig. 1 : Architecture of Hibernate
In order to persist data to a database, Hibernate create an instance of entity class (Java class mapped with database table).
This object is called Transient object as they are not yet associated with the session or not yet persisted to a database.
To persist the object to database, the instance of SessionFactory interface is created.
is a singleton instance which implements Factory design pattern. SessionFactory loads hibernate.cfg.xml file and with the help of TransactionFactory
implements all the configuration settings on a d
Each database connection in Hibernate is created by creating an instance of Session
Session represents a single connection with database.
Session objects are created from SessionFactory object.
Each transaction represents a single atomic unit of work. One Session can span through multiple transactions. Here are some of the part of the hibernate architecture
8 – Hibernate
55
Write a note on Hibernate with its Architecture and Discuss
instance of entity class (Java
This object is called Transient object as they are not yet associated with the session or
nterface is created.
is a singleton instance which implements Factory design pattern. TransactionFactory and
implements all the configuration settings on a database.
Each database connection in Hibernate is created by creating an instance of Session
mic unit of work. One Session can span through
Prashant Maheta, CE Department | 2160707
1. SessionFactory (org.hibernate.SessionFactory)
A thread-safe, immutable cache of compiled mappings for a single database. A factory for org.hibernate.Session instances.
A client of org.hibernate.connection.ConnectionProvider. Optionally maintains a second level cache of data that is reusable between
transactions at a process or cluster level.
2. Session (org.hibernate.Session)
A single-threaded, shortapplication and the persistent store.
Wraps a JDBC java.sql.Connection.
Factory for org.hibernate.Transaction.
Maintains a first level cache of persistent the application’s pecollections; this cache is used when navigating the object graph or looking up objects by identifier.
3. Persistent objects and collections
Short-lived, single threaded objects containing persistent state and business function.
These can be ordinary JavaBeans/POJOs.
They are associated with exactly one org.hibernate.Session.
Once the org.hibernate.Session is closed, they will be detached and free to use in any application layer.
4. Transient and detached objects and collections
Instances of persistent classes that are not currently associated with a org.hibernate.Session.
They may have been instantiated by the application and not yet persisted, or they may have been instantiated by a closed org.hibernate.Session.
5. Transaction (org.hibernate.Transaction)
A single-threaded, shortof work.
It abstracts the application from the underlying JDBC, JTA or CORBA transaction.
6. ConnectionProvider (org.hibernate.connection.ConnectionProvider)
A factory for, and pool of, JDBC connections.
It abstracts the application from underlying javax.sql.DataSource or java.sql.DriverManager.
7. TransactionFactory (org.hibernate.TransactionFactory)
A factory for org.hibernate.Transaction instances. It is not exposed to the application, but it can be extended and/or implemented by the developer.
Unit 8
2160707– Advanced Java
SessionFactory (org.hibernate.SessionFactory)
safe, immutable cache of compiled mappings for a single database. A factory for org.hibernate.Session instances.
A client of org.hibernate.connection.ConnectionProvider. Optionally maintains a second level cache of data that is reusable between transactions at a process or cluster level.
Session (org.hibernate.Session)
threaded, short-lived object representing a conversation between the application and the persistent store.
Wraps a JDBC java.sql.Connection.
Factory for org.hibernate.Transaction.
Maintains a first level cache of persistent the application’s pecollections; this cache is used when navigating the object graph or looking up objects
Persistent objects and collections
lived, single threaded objects containing persistent state and business
an be ordinary JavaBeans/POJOs.
They are associated with exactly one org.hibernate.Session.
Once the org.hibernate.Session is closed, they will be detached and free to use in any
Transient and detached objects and collections
Instances of persistent classes that are not currently associated with a org.hibernate.Session.
They may have been instantiated by the application and not yet persisted, or they may have been instantiated by a closed org.hibernate.Session.
org.hibernate.Transaction)
threaded, short-lived object used by the application to specify atomic units
It abstracts the application from the underlying JDBC, JTA or CORBA transaction. (org.hibernate.connection.ConnectionProvider)
A factory for, and pool of, JDBC connections.
It abstracts the application from underlying javax.sql.DataSource or java.sql.DriverManager.
TransactionFactory (org.hibernate.TransactionFactory)
org.hibernate.Transaction instances. It is not exposed to the application, but it can be extended and/or implemented by the developer.
8 – Hibernate
56
safe, immutable cache of compiled mappings for a single database. A
Optionally maintains a second level cache of data that is reusable between
lived object representing a conversation between the
Maintains a first level cache of persistent the application’s persistent objects and collections; this cache is used when navigating the object graph or looking up objects
lived, single threaded objects containing persistent state and business
Once the org.hibernate.Session is closed, they will be detached and free to use in any
Instances of persistent classes that are not currently associated with a
They may have been instantiated by the application and not yet persisted, or they
lived object used by the application to specify atomic units
It abstracts the application from the underlying JDBC, JTA or CORBA transaction. (org.hibernate.connection.ConnectionProvider)
It abstracts the application from underlying javax.sql.DataSource or
org.hibernate.Transaction instances. It is not exposed to the application,
Prashant Maheta, CE Department | 2160707
2. What is HQL? How does it differ from SQL? Give its advantages.
Hibernate Query Language HQL is an but instead of operating on tables and columns, HQL works with persistent objects and their properties.
The Hibernate Query Language (HQL) is an easylanguage designed as an
HQL queries are case insensitive; however, the names of java classes and properties
are case sensitive.If HQL is used in an application define a query for a database, the Hibernate framework automatically generates the S
HQL can also be used to retrieve objects from database through O/R mapping by
performing the following tasks:o Apply restrictions to properties of objectso Arrange the results returned by a query by using the order by clauseo Paginate the resultso Aggregate the records by using group by and having clauseso Use Joins o Create usero Execute subqueries
Following are some of the reasons why HQL is preferred over SQL:
o Provides full support for relation operationso Returns results as objectso Support polymorphic querieso Easy to learn and useo Supports for advanced featureso Provides database independency
HQL consists of the following elements:
o Clauses From : from object [as object_alias] Select : Where : where condition Order by : order by obj1.property1 [asc|desc] [obj2.property2] Group by : Group by obj1.property1,obj1.property2
o Association and Joins
Inner join Left outer join Right Full join
Unit 8
2160707– Advanced Java
What is HQL? How does it differ from SQL? Give its advantages.
Hibernate Query Language HQL is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. The Hibernate Query Language (HQL) is an easy-to-learn and powerful query language designed as an object-oriented extension to SQL. HQL queries are case insensitive; however, the names of java classes and properties are case sensitive.If HQL is used in an application define a query for a database, the Hibernate framework automatically generates the SQL query and execute it.
HQL can also be used to retrieve objects from database through O/R mapping by performing the following tasks:
Apply restrictions to properties of objects Arrange the results returned by a query by using the order by clausePaginate the results Aggregate the records by using group by and having clauses
Create user-defined functions Execute subqueries
Following are some of the reasons why HQL is preferred over SQL:Provides full support for relation operations
rns results as objects Support polymorphic queries Easy to learn and use Supports for advanced features Provides database independency
HQL consists of the following elements:
From : from object [as object_alias] Select : select [object.property] Where : where condition Order by : order by obj1.property1 [asc|desc] [obj2.property2]Group by : Group by obj1.property1,obj1.property2
Association and Joins Inner join Left outer join Right outer join Full join
8 – Hibernate
57
What is HQL? How does it differ from SQL? Give its advantages.
oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects
learn and powerful query
HQL queries are case insensitive; however, the names of java classes and properties are case sensitive.If HQL is used in an application define a query for a database, the
QL query and execute it.
HQL can also be used to retrieve objects from database through O/R mapping by
Arrange the results returned by a query by using the order by clause
Aggregate the records by using group by and having clauses
Following are some of the reasons why HQL is preferred over SQL:
Order by : order by obj1.property1 [asc|desc] [obj2.property2] Group by : Group by obj1.property1,obj1.property2
Prashant Maheta, CE Department | 2160707
o Aggregate functions
avg(…) sum(…) min(…) max(…) count(…)
o Expressions Mathematical operators : +, Binary comparison operators : =,>=,<=,<>,!= Logical operators : String concatenation : ||
o Subquerieso A query within query is known as subquery and is surrounded by
parentheses.
FROM Clause :
You will use FROM clause if you want to load a complete persistent objects into memory. Following is the simple syntax of using FROM clause: String hql = "FROM Employee"; Query query = session.createQuery(hql); List results = query.list()
SELECT Clause :
The SELECT clause provides more control over the result set than the from clause.you want to obtain few properties of objects instead of the complete object, use the SELECT clause. String hql = "SELECT E.firstName FROM Employee E"; Query query = session.createQuery(hql); List results = query.list();
ORDER BY Clause :
To sort your HQL query's results, you will need to use the ORDER BY clause. String hql = "FROM Employee E WHERE E.id > 10 ORDER BY E.salary DESC";Query query = session.createQuery(hql); List results = query.list();
Unit 8
2160707– Advanced Java
Aggregate functions avg(…) sum(…) min(…) max(…) count(…)
Expressions Mathematical operators : +,-,*,/ Binary comparison operators : =,>=,<=,<>,!= Logical operators : and,or,not String concatenation : ||
Subqueries A query within query is known as subquery and is surrounded by parentheses.
You will use FROM clause if you want to load a complete persistent objects into memory. Following is the simple syntax of using FROM clause:
String hql = "FROM Employee"; Query query = session.createQuery(hql); List results = query.list()
The SELECT clause provides more control over the result set than the from clause.you want to obtain few properties of objects instead of the complete object, use the
String hql = "SELECT E.firstName FROM Employee E"; ry = session.createQuery(hql);
List results = query.list();
ORDER BY Clause : To sort your HQL query's results, you will need to use the ORDER BY clause.
String hql = "FROM Employee E WHERE E.id > 10 ORDER BY E.salary DESC";Query query = session.createQuery(hql); List results = query.list();
8 – Hibernate
58
A query within query is known as subquery and is surrounded by
You will use FROM clause if you want to load a complete persistent objects into
The SELECT clause provides more control over the result set than the from clause. If you want to obtain few properties of objects instead of the complete object, use the
To sort your HQL query's results, you will need to use the ORDER BY clause.
String hql = "FROM Employee E WHERE E.id > 10 ORDER BY E.salary DESC";
Prashant Maheta, CE Department | 2160707
USING NAMED Parameters :
Hibernate supports named parameters in its HQL queries.This makes writing HQL queries that accept input from the user String hql = "FROM Employee E WHERE E.id = :employee_id"; Query query = session.createQuery(hql); query.setParameter("employee_id",10); List results = query.list();
UPDATE Clause :
The UPDATE clause can be used to update one or more properties of an one or more objects. String hql = "UPDATE Employee set salary = :salary WHERE id = :employee_id"; Query query = session.createQuery(hql); query.setParameter("salary", 1000); query.setParameter("employee_id", 10); int result = query.executeUpdate(); System.out.println("Rows affected: " + result);
Pagination Using Query :
Query setFirstResult your result set, starting with row 0. Query setMaxResult maxResults of objects. String hql = "FROM Employee"; Query query = session.createQuery(hql); query.setFirstResult(1); query.setMaxResults(10); List results = query.list();
3. Explain the OR Mapping in H
ORM is technique to map object
In other words, it is used to convert the datatype supported in objectprogramming language to a datatype supported by a database.
ORM is also known as O/RM & O/R mapping.
Unit 8
2160707– Advanced Java
USING NAMED Parameters : Hibernate supports named parameters in its HQL queries.This makes writing HQL queries that accept input from the user.
String hql = "FROM Employee E WHERE E.id = :employee_id"; Query query = session.createQuery(hql); query.setParameter("employee_id",10); List results = query.list();
The UPDATE clause can be used to update one or more properties of an one or more
String hql = "UPDATE Employee set salary = :salary WHERE id = :employee_id"; Query query = session.createQuery(hql); query.setParameter("salary", 1000); query.setParameter("employee_id", 10); int result = query.executeUpdate(); System.out.println("Rows affected: " + result);
Pagination Using Query : Query setFirstResult - This method takes an integer that represents the first row in
starting with row 0.
Query setMaxResult - This method tells Hibernate to retrieve a fixed number maxResults of objects.
String hql = "FROM Employee"; Query query = session.createQuery(hql); query.setFirstResult(1); query.setMaxResults(10); List results = query.list();
OR Mapping in Hibernate.
ORM is technique to map object-oriented data with relational data.
In other words, it is used to convert the datatype supported in objectprogramming language to a datatype supported by a database. ORM is also known as O/RM & O/R mapping.
8 – Hibernate
59
Hibernate supports named parameters in its HQL queries.This makes writing HQL
Query query = session.createQuery(hql); query.setParameter("employee_id",10);
The UPDATE clause can be used to update one or more properties of an one or more
String hql = "UPDATE Employee set salary = :salary WHERE id = :employee_id";
This method takes an integer that represents the first row in
This method tells Hibernate to retrieve a fixed number
In other words, it is used to convert the datatype supported in object-oriented
Prashant Maheta, CE Department | 2160707
Mapping should be in the format that can define the mapping of the
o classes with tableso properties with columnso foreign key with associationso and SQL types with Java types.
Mapping can be done with Oracle, DB2, MySql, Sybase and any other relational
databases.
Mapping will be done in the form of XML Document.
In complex applications, a class can be inherited by other classes, which may lead to the
problem of class mismatching. To overcome such problem, the following approach can be used.
o Table-per-classcompletely from the relational model
o Table-per-subclass(normalized mapping):and enables polymorphism.
o Table-per-concreterelationships.
Multiple objects can be
strategies are as follows,o Many-to-one:
a foreign key association.o One-to-many:
to a foreign key association.o Many-to-many:
transparently mapped to a match table.
The important elements of the Hibernate m
o DOCTYPE: Refers to the Hibernate mapping Document Type Declaration (DTD) that should be declared in every mapping file for syntactic validation of the XML.
o <hibernate-mapping> element: inside <hibernate
o <class> element:
database. o <id> element :
the database table.
o <generator> element:
following are some of the commonly used generators. Increment , Sequence, Assigned, Identity, Hilo, Native
o <property> element: database schema.
Unit 8
2160707– Advanced Java
Mapping should be in the format that can define the mapping of the classes with tables properties with columns foreign key with associations and SQL types with Java types.
Mapping can be done with Oracle, DB2, MySql, Sybase and any other relational
Mapping will be done in the form of XML Document.
x applications, a class can be inherited by other classes, which may lead to the problem of class mismatching. To overcome such problem, the following approach can
class-hierarchy: Removes polymorphism and inheritance relationship tely from the relational model
subclass(normalized mapping): De-Normalizes the relational model and enables polymorphism.
concrete-class: Represents inheritance relationship as foreign key
Multiple objects can be mapped to a single row. Polymorphic associations for the 3 strategies are as follows,
Serves as an association in which an object reference is mapped to a foreign key association.
Serves as an association in which a collection of objects is mapped to a foreign key association.
many: Serves as an association in which a collection of objects is transparently mapped to a match table.
The important elements of the Hibernate mapping file are as follows.Refers to the Hibernate mapping Document Type Declaration (DTD)
that should be declared in every mapping file for syntactic validation of the XML.mapping> element: Refers as the first or root element of
inside <hibernate-mapping> tag any number of class may be present.<class> element: Maps a class object with its corresponding entity in the
<id> element : Serves as a unique identifier used to map primary key column of table.
<generator> element: Helps in generation of the primary key for the new record, following are some of the commonly used generators.
Increment , Sequence, Assigned, Identity, Hilo, Native <property> element: Defines standard Java attributes and thedatabase schema.
8 – Hibernate
60
Mapping can be done with Oracle, DB2, MySql, Sybase and any other relational
x applications, a class can be inherited by other classes, which may lead to the problem of class mismatching. To overcome such problem, the following approach can
Removes polymorphism and inheritance relationship
Normalizes the relational model
Represents inheritance relationship as foreign key
mapped to a single row. Polymorphic associations for the 3
Serves as an association in which an object reference is mapped to
Serves as an association in which a collection of objects is mapped
Serves as an association in which a collection of objects is
apping file are as follows. Refers to the Hibernate mapping Document Type Declaration (DTD)
that should be declared in every mapping file for syntactic validation of the XML. Refers as the first or root element of Hibernate,
mapping> tag any number of class may be present. Maps a class object with its corresponding entity in the
Serves as a unique identifier used to map primary key column of
Helps in generation of the primary key for the new record,
Defines standard Java attributes and their mapping into
Prashant Maheta, CE Department | 2160707
Example :
Employee.java public class Employee private int employeeId; private String name,email; private Address //setters and getters}
Address.java
public class Address { private int addressId; private String addressLine1,city,state,country; private int pincode; private Employee//setters and getters }
Employee.hbm.xml
<?xml version='1.0' encoding='UTF<!DOCTYPE hibernate- "-//Hibernate/Hibernate "http://hibernate.sourceforge.net/hibernate
<hibernate-mapping> <class name="Employee" <id name="employeeId"> <generator class="increment"></generator>
</id> <property name="name"></property> <property name="email"></property> <many-to-one name="address" </class> </hibernate-mapping>
Unit 8
2160707– Advanced Java
Employee { employeeId;
name,email; Address address;
getters
addressId;
addressLine1,city,state,country; pincode;
Employee employee;
encoding='UTF-8'?>
-mapping PUBLIC //Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
name="Employee" table="emp211"> name="employeeId">
="increment"></generator>
name="name"></property> name="email"></property>
name="address" unique="true" cascade="all"></many-to
8 – Hibernate
61
3.0.dtd">
to-one>
Prashant Maheta, CE Department | 2160707
Address.hbm.xml
<?xml version='1.0' encoding='UTF<!DOCTYPE hibernate- "-//Hibernate/Hibernate "http://hibernate.sourceforge.net/hibernate
<hibernate-mapping> <class name="com.javatpoint.Address" <id name="addressId"> <generator class="increment"></gene </id> <property name="addressLine1"></property> <property name="city"></property> <property name="state"></property> <property name="country"></property> </class> </hibernate-mapping>
Hibernate.cfg.xml <?xml version='1.0' encoding='UTF<!DOCTYPE hibernate-configuration "-//Hibernate/Hibernate "http://hibernate.sourceforge.net/hibernate<hibernate-configuration> <session-factory> <property name="hbm2ddl.auto">update</property> <property name="connection.url">jdbc:oracle:thin:@loca <property name="connection.username">system</property> <property name="connection.password">oracle</property> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <mapping resource="employee.hbm.xml"/> <mapping resource="address.hbm.xml"/> </session-factory> </hibernate-configuration>
Unit 8
2160707– Advanced Java
encoding='UTF-8'?> -mapping PUBLIC
//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
name="com.javatpoint.Address" table="address211">
="increment"></generator>
name="addressLine1"></property> name="city"></property> name="state"></property> name="country"></property>
encoding='UTF-8'?> configuration PUBLIC
//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
configuration>
name="hbm2ddl.auto">update</property> name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>name="connection.username">system</property> name="connection.password">oracle</property> name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
resource="employee.hbm.xml"/> resource="address.hbm.xml"/>
configuration>
8 – Hibernate
62
3.0.dtd">
3.0.dtd">
lhost:1521:xe</property>
name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
Prashant Maheta, CE Department | 2160707
StoreData.java
import org.hibernate.cfg.*;import org.hibernate.*; public class Store {
public static void Configuration cfg.configure("hibernate.cfg.xml"); SessionFactory Session session=sf.openSession(); Transaction Employee e1= e1.setName("Ravi e1.setEmail("[email protected]"); Address address1= address1.setAddressLine1("G address1.setCity("Ghaziabad"); address1.setState("UP"); address1.setCountry("India"); address1.setPincode(201301); e1.setAddress(address1); address1.setEmployee(e1); session.save(e1); session.save(address1); tx.commit(); session.close();}
}
FetchData.java
public class Fetch { public static void Configuration cfg.configure("hibernate.cfg.xml"); SessionFactory Session session=sf.openSession(); Query query=session.createQuery("from List<Employee>
Unit 8
2160707– Advanced Java
org.hibernate.cfg.*; org.hibernate.*;
void main(String[] args) { Configuration cfg=new Configuration(); cfg.configure("hibernate.cfg.xml"); SessionFactory sf=cfg.buildSessionFactory();
session=sf.openSession(); tx=session.beginTransaction();
e1=new Employee(); e1.setName("Ravi Malik"); e1.setEmail("[email protected]");
address1=new Address(); address1.setAddressLine1("G-21,Lohia nagar"); address1.setCity("Ghaziabad"); address1.setState("UP"); address1.setCountry("India"); address1.setPincode(201301);
e1.setAddress(address1); address1.setEmployee(e1);
session.save(e1); session.save(address1); tx.commit();
session.close();
void main(String[] args) { Configuration cfg=new Configuration(); cfg.configure("hibernate.cfg.xml"); SessionFactory sf=cfg.buildSessionFactory();
session=sf.openSession(); query=session.createQuery("from Employee e");
List<Employee> list=query.list();
8 – Hibernate
63
Prashant Maheta, CE Department | 2160707
Query query=session.createQuery("from List<Employee> Iterator<Employee> while(itr.hasNext()){
Employee System.out.println(emp.getEmployeeId()+".getEmail()); Address System.out.println(address.getAddressLine1()+"+ address.getState()+"
} session.close(); System.out.println("success");}
}
4 Explain Hibernate Annotation.
Hibernate Annotations is the powerful way to provide the metadata for the Object and
Relational Table mapping.
Consider we are going to use following EMPLOYEE table to store our objects:
create table EMPLOYEE ( id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL, PRIMARY KEY (id) );
Following is the mapping of Employee class with annotations to map objects with the
defined EMPLOYEE table:
import javax.persistence.*; @Entity @Table(name = "EMPLOYEE") public class Employee { @Id @GeneratedValue @Column(name = "id") private int id;
Unit 8
2160707– Advanced Java
query=session.createQuery("from Employee e"); List<Employee> list=query.list(); Iterator<Employee> itr=list.iterator(); while(itr.hasNext()){
Employee emp=itr.next(); System.out.println(emp.getEmployeeId()+" "+emp.getName()+"
.getEmail()); Address address=emp.getAddress(); System.out.println(address.getAddressLine1()+" "+address.getCity()+"
address.getState()+" "+address.getCountry());
session.close(); System.out.println("success");
Annotation.
Hibernate Annotations is the powerful way to provide the metadata for the Object and Relational Table mapping.
Consider we are going to use following EMPLOYEE table to store our objects:
create table EMPLOYEE ( id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL,
Following is the mapping of Employee class with annotations to map objects with the EMPLOYEE table:
import javax.persistence.*;
@Table(name = "EMPLOYEE")
8 – Hibernate
64
"+emp.getName()+" "+emp
"+address.getCity()+" "
Hibernate Annotations is the powerful way to provide the metadata for the Object and
Consider we are going to use following EMPLOYEE table to store our objects:
Following is the mapping of Employee class with annotations to map objects with the
Prashant Maheta, CE Department | 2160707
@Column(name = "first_name") private String firstName; @Column(name = "last_name") private String lastName; @Column(name = "salary") private int salary;
public Employee() {} public int getId() {
return id; }
public void setId( int id ) { this.id = id; }
public String getFirstName() { return firstName; }
public void setFirstName( String first_name ) { this.firstName = first_name; }
public String getLastName() { return lastName; }
public void setLastName( String last_name ) { this.lastName = last_name; }
public int getSalary() { return salary; }
public void setSalary( int salary ) { this.salary = salary; }
}
@Entity Annotation:
Employee class which marks this class as an entity bean
@Table Annotation: The @Table annotation allows you to specify the details of the table that will be
used to persist the entity in the database.
@Id and @GeneratedValue Annotations: Each entity bean will have a primary key, which you annotate on the class with
the @Id annot @GeneratedValue
Unit 8
2160707– Advanced Java
@Column(name = "first_name")
@Column(name = "last_name")
@Column(name = "salary")
public void setId( int id ) {
public String getFirstName() {
public void setFirstName( String first_name ) { this.firstName = first_name;
public String getLastName() {
public void setLastName( String last_name ) { this.lastName = last_name;
public void setSalary( int salary ) {
Employee class which marks this class as an entity bean
The @Table annotation allows you to specify the details of the table that will be used to persist the entity in the database.
@Id and @GeneratedValue Annotations: Each entity bean will have a primary key, which you annotate on the class with
annotation @GeneratedValue is same as Auto Increment
8 – Hibernate
65
The @Table annotation allows you to specify the details of the table that will be
Each entity bean will have a primary key, which you annotate on the class with
Prashant Maheta, CE Department | 2160707
@Column Annotation:
The @Column annotation is used to specify the details of the column to which a field or property will be mapped. You can use column annotation with the following most commonly used
name attribute permits the name of the column to be explicitly specified. length attribute permits the size of the column used to map a value particularly
for a String value. nullable attribute permits the column to be marked NOT NULL when the
is generated. unique attribute permits the column to be marked as containing only unique
values.
Unit 8
2160707– Advanced Java
@Column Annotation: The @Column annotation is used to specify the details of the column to which a field or property will be mapped. You can use column annotation with the following most commonly used attributes:
attribute permits the name of the column to be explicitly specified.attribute permits the size of the column used to map a value particularly
for a String value. attribute permits the column to be marked NOT NULL when the
attribute permits the column to be marked as containing only unique
8 – Hibernate
66
The @Column annotation is used to specify the details of the column to which a field or property will be mapped. You can use column annotation with the
attribute permits the name of the column to be explicitly specified. attribute permits the size of the column used to map a value particularly
attribute permits the column to be marked NOT NULL when the schema
attribute permits the column to be marked as containing only unique
Prashant Maheta, CE Department | 2160707
1. Explain Spring MVC
Spring’s web MVC framework is, like many other web MVC frameworks, requestdesigned around a central other functionality that facilitates the development of web applications.
Spring’s DispatcherServlet is completely integrated with Spring IoC container and allows us to use every other feature of S
Following is the Request process lifecycle of Spring 3.0 MVC:
1. The client sends a request to web container in the form of http request.2. This incoming request is intercepted by Front controller (DispatcherServlet) and it
will then tries to find out 3. With the help of Handler Mappings, the DispatcherServlet will dispatch the request
to appropriate Controller.4. The Controller tries to process the request and returns the Model and View object in
form of ModelAndView instance t5. The Front Controller then tries to resolve the View (which can be JSP, Freemarker,
Velocity etc) by consulting the View Resolver object.6. The selected view is then rendered back to client.
Unit 7 –
| 2160707– Advanced Java
MVC Architecture
Fig. 1 : Spring MVC Architecture
Spring’s web MVC framework is, like many other web MVC frameworks, requestdesigned around a central servlet that dispatches requests to controllers and offers other functionality that facilitates the development of web applications.
Spring’s DispatcherServlet is completely integrated with Spring IoC container and allows us to use every other feature of Spring. Following is the Request process lifecycle of Spring 3.0 MVC:
The client sends a request to web container in the form of http request.This incoming request is intercepted by Front controller (DispatcherServlet) and it will then tries to find out appropriate Handler Mappings. With the help of Handler Mappings, the DispatcherServlet will dispatch the request to appropriate Controller. The Controller tries to process the request and returns the Model and View object in form of ModelAndView instance to the Front Controller. The Front Controller then tries to resolve the View (which can be JSP, Freemarker, Velocity etc) by consulting the View Resolver object. The selected view is then rendered back to client.
– Spring MVC
67
Spring’s web MVC framework is, like many other web MVC frameworks, request-driven, servlet that dispatches requests to controllers and offers
other functionality that facilitates the development of web applications. Spring’s DispatcherServlet is completely integrated with Spring IoC container and allows
The client sends a request to web container in the form of http request. This incoming request is intercepted by Front controller (DispatcherServlet) and it
With the help of Handler Mappings, the DispatcherServlet will dispatch the request
The Controller tries to process the request and returns the Model and View object in
The Front Controller then tries to resolve the View (which can be JSP, Freemarker,
Prashant Maheta, CE Department | 2160707
Features of Spring 3.0 : Spring 3.0 framework supports Java 5. It provides annotation based configuration
support. Java 5 features such as generics, annotations, varargs etc can be used in Spring.
A new expression language Spring Expression Language SpEL is being introduced. The Spring Expression Language can be used while defining the XML and Annotation based bean definition.
Spring 3.0 framework supports REST web services.
Data formatting can never be so easy. Spring 3.0 supports annotation based formatting. We can now use the @DateFimeForm@NumberFormat(style=Style.CURRENCY) annotations to convert the date and currency formats.
Spring 3.0 has started support to JPA 2.0.
Configuring Spring 3.0 MVC : The entry point of Spring 3.0 MVC is the DispatcherServlet.
servlet class which implements HttpServlet base class. Thus we need to configure it in web.xml.
<web-app> <servlet> <servlet-name>example <servlet-class>org.springframework.web.servlet.DispatcherServlet <load-on-startup> </servlet> <servlet-mapping> <servlet-name>example <url-pattern>*.html </servlet-mapping></web-app>
In above code snippet, we have configure DispatcherServlet in web.xml. Note that we
have mapped *.html url pattern with example DispatcherServlet. Thus any url with *.html pattern will call Spring MVC Front controller.
Once the DispatcherServlet is initialized, it will looks for a file names [servlet
servlet.xml in WEB-INF folder of web application. In above example, the framework will look for file called example
Unit 7 –
| 2160707– Advanced Java
framework supports Java 5. It provides annotation based configuration
support. Java 5 features such as generics, annotations, varargs etc can be used in Spring.
A new expression language Spring Expression Language SpEL is being introduced. The ssion Language can be used while defining the XML and Annotation based
Spring 3.0 framework supports REST web services.
Data formatting can never be so easy. Spring 3.0 supports annotation based formatting. We can now use the @DateFimeFormat(iso=ISO.DATE) and @NumberFormat(style=Style.CURRENCY) annotations to convert the date and currency
Spring 3.0 has started support to JPA 2.0.
Configuring Spring 3.0 MVC : The entry point of Spring 3.0 MVC is the DispatcherServlet. DispatcherServlet is a normal servlet class which implements HttpServlet base class. Thus we need to configure it in
example</servlet-name> org.springframework.web.servlet.DispatcherServlet
startup>1</load-on-startup>
example</servlet-name>
*.html</url-pattern> ng>
In above code snippet, we have configure DispatcherServlet in web.xml. Note that we have mapped *.html url pattern with example DispatcherServlet. Thus any url with *.html pattern will call Spring MVC Front controller.
DispatcherServlet is initialized, it will looks for a file names [servletINF folder of web application. In above example, the framework will
look for file called example-servlet.xml.
– Spring MVC
68
framework supports Java 5. It provides annotation based configuration support. Java 5 features such as generics, annotations, varargs etc can be used in Spring.
A new expression language Spring Expression Language SpEL is being introduced. The ssion Language can be used while defining the XML and Annotation based
Data formatting can never be so easy. Spring 3.0 supports annotation based formatting. at(iso=ISO.DATE) and
@NumberFormat(style=Style.CURRENCY) annotations to convert the date and currency
DispatcherServlet is a normal servlet class which implements HttpServlet base class. Thus we need to configure it in
org.springframework.web.servlet.DispatcherServlet</servlet-class>
In above code snippet, we have configure DispatcherServlet in web.xml. Note that we have mapped *.html url pattern with example DispatcherServlet. Thus any url with
DispatcherServlet is initialized, it will looks for a file names [servlet-name]-INF folder of web application. In above example, the framework will
Prashant Maheta, CE Department | 2160707
2. Explain 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 brequired.
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 tiinitialization and its destruction.
To define setup and teardown for a bean, we simply declare the <bean> with initmethod and/or destroymethod that is to be called on the bean immediateldestroy-method specifies a method that is called just before a bean is removed from the container.
Here is the content of
public class HelloWorld { private String message; public void setMessage( this.message = message } public void getMessage(){ System.out.println("Your Message : " } public void init(){ System.out.println("Bean is going through init." } public void destroy(){ System.out.println("Bean will destroy now." } }
Following is the content of the
hook registerShutdownHook()AbstractApplicationContext class. This will ensures a graceful shutdown and calls the relevant destroy methods.
Unit 7 –
| 2160707– Advanced Java
Explain Bean Life Cycle.
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 b
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 tiinitialization and its destruction.
To define setup and teardown for a bean, we simply declare the <bean> with initmethod and/or destroy-method parameters. The init-method attribute specifies a method that is to be called on the bean immediately upon instantiation. Similarly,
method specifies a method that is called just before a bean is removed from the
Here is the content of HelloWorld.java file:
(String message){ message;
(){ "Your Message : " + message);
"Bean is going through init.");
"Bean will destroy now.");
Following is the content of the MainApp.java file. Here you need to register a shutdown registerShutdownHook() method that is declared on the
AbstractApplicationContext class. This will ensures a graceful shutdown and calls the relevant destroy methods.
– Spring MVC
69
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
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
To define setup and teardown for a bean, we simply declare the <bean> with init-method attribute specifies a
y upon instantiation. Similarly, method specifies a method that is called just before a bean is removed from the
file. Here you need to register a shutdown method that is declared on the
AbstractApplicationContext class. This will ensures a graceful shutdown and calls the
Prashant Maheta, CE Department | 2160707
import org.springframeworkimport org.springframework public class MainApp { public static void main AbstractApplicationContextClassPathXmlApplicationContext HelloWorld obj = (HelloWorld obj.getMessage(); context.registerShutdownHook } }
Following is the configuration file Beans.xml required for init and destroy methods:
<?xml version="1.0" encoding <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema xsi:schemaLocation= http://www.springframework.org/schema/beans/spring
<bean id="helloWorld" class="com.HelloWorld" init-method="init" <property name </bean>
</beans>
3. Explain Transaction Management in Spring MVC.
A database transaction is a sequence of actions that are treated as a single unit of work. These actions should either complete entirely or take no effect at all. Transaction management is an important part of and RDBMS oriented enterprise applications to ensure data integrity and consistency. The concept of transactions can be described with following four key properties described as
o Atomicity: A transaction should be treated as a single unit of operation which
means either the entire sequence of oo Consistency: This represents the consistency of the referential integrity of the
database, unique primary keys in tables etc.
Unit 7 –
| 2160707– Advanced Java
springframework.context.support.AbstractApplicationContextspringframework.context.support.ClassPathXmlApplicationContext
{ main(String[] args) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld) context.getBean("helloWorld");
registerShutdownHook();
Following is the configuration file Beans.xml required for init and destroy methods:
encoding="UTF-8"?>
"http://www.springframework.org/schema/beans" "http://www.w3.org/2001/XMLSchema-instance"
="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
helloWorld" "com.HelloWorld"
"init" destroy-method="destroy"> name="message" value="Hello World!"/>
Explain Transaction Management in Spring MVC.
A database transaction is a sequence of actions that are treated as a single unit of work. These actions should either complete entirely or take no effect at all. Transaction management is an important part of and RDBMS oriented enterprise applications to ensure data integrity and consistency. The concept of transactions can be described with following four key properties described as ACID:
A transaction should be treated as a single unit of operation which means either the entire sequence of operations is successful or unsuccessful.
This represents the consistency of the referential integrity of the database, unique primary keys in tables etc.
– Spring MVC
70
AbstractApplicationContext; ClassPathXmlApplicationContext;
Following is the configuration file Beans.xml required for init and destroy methods:
"http://www.springframework.org/schema/beans 3.0.xsd">
A database transaction is a sequence of actions that are treated as a single unit of work. These actions should either complete entirely or take no effect at all. Transaction management is an important part of and RDBMS oriented enterprise applications to ensure data integrity and consistency. The concept of transactions can be described with
A transaction should be treated as a single unit of operation which perations is successful or unsuccessful.
This represents the consistency of the referential integrity of the
Prashant Maheta, CE Department | 2160707
o Isolation: There may be many transactions processing with the same data set at the same time, each transaction should be isolated from others to prevent data corruption.
o Durability: Once a transaction has completed, the results of this transaction have to be made permanent and cannot be erased from the database due to system failure.
Spring supports two types of transaction management:
o Programmatic transaction management:transaction with the help of programming. That gives you eit is difficult to maintain.
o Declarative transaction management:management from the business code. You only use annotations or XML based configuration to manage the transactions.
Declarative transaction management is preferable over programmatic transaction
management though it iswhich allows you to control transactions through your code.
Spring Transaction Abstractions The key to the Spring transaction abstraction is defined by the
org.springframework.transaction.PlatformTransactionManager interface, which is as follows:
public interface PlatformTransactionManager
TransactionStatus getTransaction throws TransactionExceptionvoid commit(TransactionStatusvoid rollback(TransactionStatus
}
Sr. No. Method & Description
1 TransactionStatus getTransaction(TransactionDefinition definition)
This method returns a currently active transaction or create a new one, according to the specified propagation behavior.
2 void commit(TransactionStatus status)
This method commits the given transaction, with regard to its status.
3 void rollback(TransactionStatus s
This method performs a rollback of the given transaction.
Unit 7 –
| 2160707– Advanced Java
There may be many transactions processing with the same data set at ime, each transaction should be isolated from others to prevent data
Once a transaction has completed, the results of this transaction have to be made permanent and cannot be erased from the database due to system
supports two types of transaction management: Programmatic transaction management: This means that you have manage the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain. Declarative transaction management: This means you separate transaction management from the business code. You only use annotations or XML based configuration to manage the transactions.
Declarative transaction management is preferable over programmatic transaction management though it is less flexible than programmatic transaction management, which allows you to control transactions through your code.
Spring Transaction Abstractions The key to the Spring transaction abstraction is defined by the org.springframework.transaction.PlatformTransactionManager interface, which is as
PlatformTransactionManager { getTransaction(TransactionDefinition definition);
TransactionException; TransactionStatus status) throws TransactionException;TransactionStatus status) throws TransactionException;
Method & Description TransactionStatus getTransaction(TransactionDefinition definition)
returns a currently active transaction or create a new one, according to the specified propagation behavior. void commit(TransactionStatus status)
This method commits the given transaction, with regard to its status.void rollback(TransactionStatus status)
This method performs a rollback of the given transaction.
– Spring MVC
71
There may be many transactions processing with the same data set at ime, each transaction should be isolated from others to prevent data
Once a transaction has completed, the results of this transaction have to be made permanent and cannot be erased from the database due to system
This means that you have manage the xtreme flexibility, but
This means you separate transaction management from the business code. You only use annotations or XML based
Declarative transaction management is preferable over programmatic transaction less flexible than programmatic transaction management,
The key to the Spring transaction abstraction is defined by the org.springframework.transaction.PlatformTransactionManager interface, which is as
; ;
TransactionStatus getTransaction(TransactionDefinition definition)
returns a currently active transaction or create a new one,
This method commits the given transaction, with regard to its status.