Advanced Java
Advanced Java
A D VA NCE D
J A VA
For T.Y.B.B.A. (C.A.) : Semester - VI
[Course Code CA - 603 : Credits - 03]
CBCS Pattern
As Per New Syllabus, Effective from June 2021
Price ` 270.00
N6189
ADVANCED JAVA ISBN 978-93-5451-523-1
First Edition : March 2022
© : Author
The text of this publication, or any part thereof, should not be reproduced or transmitted in any form or stored in any
computer storage system or device for distribution including photocopy, recording, taping or information retrieval system or
reproduced on any disc, tape, perforated media or other information storage device etc., without the written permission of Author
with whom the rights are reserved. Breach of this condition is liable for legal action.
Every effort has been made to avoid errors or omissions in this publication. In spite of this, errors may have crept in. Any
mistake, error or discrepancy so noted and shall be brought to our notice shall be taken care of in the next edition. It is notified
that neither the publisher nor the author or seller shall be responsible for any damage or loss of action to any one, of any kind, in
any manner, therefrom. The reader must cross check all the facts and contents with original Government notification or
publications.
DISTRIBUTION CENTRES
PUNE
Nirali Prakashan Nirali Prakashan
(For orders outside Pune) (For orders within Pune)
S. No. 28/27, Dhayari Narhe Road, Near Asian College 119, Budhwar Peth, Jogeshwari Mandir Lane
Pune 411041, Maharashtra Pune 411002, Maharashtra
Tel : (020) 24690204; Mobile : 9657703143 Tel : (020) 2445 2044; Mobile : 9657703145
Email : [email protected] Email : [email protected]
MUMBAI
Nirali Prakashan
Rasdhara Co-op. Hsg. Society Ltd., 'D' Wing Ground Floor, 385 S.V.P. Road
Girgaum, Mumbai 400004, Maharashtra
Mobile : 7045821020, Tel : (022) 2385 6339 / 2386 9976
Email : [email protected]
DISTRIBUTION BRANCHES
DELHI BENGALURU NAGPUR
Nirali Prakashan Nirali Prakashan Nirali Prakashan
Room No. 2 Ground Floor Maitri Ground Floor, Jaya Apartments, Above Maratha Mandir, Shop No. 3,
4575/15 Omkar Tower, Agarwal Road No. 99, 6th Cross, 6th Main, First Floor, Rani Jhanshi Square,
Darya Ganj, New Delhi 110002 Malleswaram, Bengaluru 560003 Sitabuldi Nagpur 440012 (MAH)
Mobile : 9555778814/9818561840 Karnataka; Mob : 9686821074 Tel : (0712) 254 7129
Email : [email protected] Email : [email protected] Email : [email protected]
[email protected] | www.pragationline.com
Also find us on www.facebook.com/niralibooks
Preface
Preface …
We take this opportunity to present this book entitled as "Advanced Java" to the
students of Sixth Semester – T.Y.B.B.A (C.A.). The object of this book is to present the subject
matter in a most concise and simple manner. The book is written strictly according to the
New Syllabus (CBCS Pattern-2019).
The book has its own unique features. It covers theory of JDBC, Multithreading,
Networking, Servlet and JSP and Spring and Hibernate.
We sincerely thank Shri. Dineshbhai Furia and Shri. Jignesh Furia of Nirali Prakashan, for
the confidence reposed in us and giving us this opportunity to reach out to the students of
BBA (CA) studies.
We have given our best inputs for this book. Any suggestions towards the improvement
of this book and sincere comments are most welcome on [email protected].
Authors
Syllabus …
1. JDBC [08 Hrs]
1.1 Introduction
1.2 JDBC Architecture
1.3 JDBC Process
1.4 Working with ResultSet Interface
2. Multithreading [12 Hrs]
2.1 Introduction to Multithreading
2.2 Thread creation: Thread Class, Runnable Interface
2.3 Life cycle of Thread
2.4 Thread Priority
2.5 Execution of Thread Application
2.6 Synchronization and Interthread Communication
3. Networking [05 Hrs]
3.1 Overview of Networking.
3.2 Networking Basics: Port Number, Protocols and classes
3.3 Sockets, Reading from and Writing to a Socket
4. Servlet and JSP [12 Hrs]
Servlet
4.1 Introduction to Servlet
4.2 Types of Servlet: Generic Servlet and Http Servlet
4.3 Life Cycle of Servlet
4.4 Session Tracking
4.5 Servlet with Database
JSP
4.6 Introduction to JSP
4.7 JSP Life Cycle
4.8 Components of JSP
4.9 JSP with Database
5. Spring and Hibernate [1 Hrs]
Spring:
5.1 Introduction
5.2 Applications and Benefits of Spring
5.3 Architecture and Environment Setup
5.4 Hello World Example
5.5 Core Spring - IoC Containers, Spring Bean Definition, Scope, Lifecycle
Hibernate:
5.6 Architecture and Environment
5.7 Configuration, Sessions, Persistent Class
5.8 Mapping Files, Mapping Types
5.9 Examples
Contents …
1. JDBC 1.1 − 1.38
1.1 INTRODUCTION
• Java interacts with database using a common database application programming
interface called as JDBC (Java DataBase Connectivity).
• JDBC is a Java API to connect and execute the query with the database. JDBC API uses
JDBC drivers (JDBC-ODBC Bridge Driver, Native Driver etc.) to connect with the
database.
• The Java JDBC API is part of the core JavaSE (Java Standard Edition) SDK, making
JDBC available to all Java applications that want to use it. The API (Application
Programming Interface) is a document that contains description of all the features
of a product or software.
• JDBC is a standard Java API for database-independent connectivity between the Java
programming language and a wide range of databases such as Oracle, PostgreSQL,
Microsoft Access, DB2, Sybase, MySQL etc.
• The JDBC library includes APIs for each of the tasks mentioned below that are
commonly associated with database usage.
1. Making a connection to a database.
2. Creating SQL or MySQL statements.
3. Executing SQL or MySQL queries in the database.
4. Viewing and modifying the resulting records.
• Fundamentally, JDBC is a specification that provides a complete set of interfaces that
allows for portable access to an underlying database.
(1.1)
Advanced Java [BBA (CA) : Sem. VI] 1.2 JDBC
• JDBC API enables the java application to interact with different database. This is
shown in Fig. 1.1.
User
program JDBC Network
(application) API interface
Database
server
Network
Database
Java Application
JDBC API
JDBC Driver
Manager
SQL ODBC
Oracle Data
Server
Source
• Fig. 1.3 shows components for JDBC design. These components are explained below:
1. Application: Application in JDBC like Java Applet or a Servlet that communicates
with a data source. Application is the data processing application that intends to
access the data from the different databases.
2. JDBC API: JDBC API provides classes, methods, and interfaces that allow Java
programs to execute SQL statements and retrieve results from the database. JDBC
API provides various interfaces and methods to establish easy connection with
different databases. JDBC API provides connection from Application to JDBC
Manager. The JDBC API ensures that a stable connection is established between
the data storage unit and the JDBC application.
3. Driver Manager: The Driver Manager plays an important role in the JDBC design.
JDBC Driver manager loads the database-specific driver into an application in
order to establish the connection with the database. The JDBC driver manager
makes sure that the correct driver is being used to access the databases. It is also
capable of handling multiple drivers connected to multiple databases
simultaneously.
4. JDBC Drivers: JDBC drivers help us to communicate with a data source (database)
through JDBC. We need a JDBC driver that can intelligently interact with the
respective data source.
Java Application
JDBC Drivers
DB
• For example, using JDBC drivers enable you to open database connections and to
interact with it by sending SQL or database commands then receiving results with
Java.
• Fig. 1.4 provides a high-level overview of the various types of drivers.
• The Types 1 and 2 Drivers rely heavily on additional software, (typically C/C++ DLLs)
installed on the client computer to provide database connectivity. Java and JDBC use
these components to interact with the database.
• The Types 3 and 4 Drivers are pure Java implementations and require no additional
software to be installed on the client, except for the JDBC driver.
Client
Type 1 ODBC
ODBC Bridge Drivers
Type 2 Native
Native API API
Database
Type 3 Middleware
JDBC Network Server
Type 4
100%PureJava
Java application
JDBC API
Vendor-
JDBC/ODBC supplied
bridge JDBC driver
ODBC Database
driver
Database
Fig. 1.5
Advanced Java [BBA (CA) : Sem. VI] 1.6 JDBC
Local Computer
Java Application DB
Vendor
Driver
Application Code
Type 1 ODBC
JDBC ODBC Bridge Driver Local
DBMS
Database Server
Fig. 1.6: JDBC - ODBC Bridge Driver
• The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of
driver.
Advantages:
1. Easy to use.
2. Can be easily connected to any database if that database has installed ODBC
driver.
Advanced Java [BBA (CA) : Sem. VI] 1.7 JDBC
Disadvantages:
1. Performance degraded because JDBC method call is converted into the ODBC
function calls.
2. The ODBC driver needs to be installed on the client machine.
3. As it is not written fully in java, so these drivers are not portable.
4. They are not much suitable for Web applications.
Type 2: JDBC-Native API Driver:
• It is also referred as Native-API partly-Java driver. This driver converts JDBC calls
into calls on the client API for Oracle, Sybase, Db2, informix or other DBMS.
• In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are
unique to the database. These drivers are typically provided by the database vendors
and used in the same manner as the JDBC-ODBC Bridge. The vendor-specific driver
must be installed on each client machine.
• If we change the Database, we have to change the native API, as it is specific to a
database and they are mostly obsolete now, but they are fast as compare to Type 1
driver as Type 2 driver has no ODBC's overhead.
• Fig. 1.7 shows JDBC-Native API driver.
Local Computer
Application Code
Local
Type 2 DBMS
Native API
Database Server
Fig. 1.7: JDBC-Native API Driver
• The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.
Advantages:
1. Faster as compared to Type 1 Driver as Type 2 drivers are database specific as well
as they do not require translation.
2. Contains additional features.
Advanced Java [BBA (CA) : Sem. VI] 1.8 JDBC
Disadvantages:
1. Requires installation of native API on client machine so not suitable for web
applications.
2. Type 2 drivers are also not written in java so they having portability issue.
3. Increased cost of application.
4. As we need to install database specific Native API on client machine, so if
database change we need to change Native API.
Type 3: JDBC-Net Pure Java Driver:
• In a Type 3 driver, a Three-tier approach is used to access databases. The JDBC clients
use standard network sockets to communicate with a middleware application server.
• The socket information is then translated by the middleware application server into
the call format required by the DBMS, and forwarded to the database server.
• This kind of driver is extremely flexible, since it requires no code installed on the
client and a single driver can actually provide access to multiple databases.
• Fig. 1.8 shows JDBC-Net Pure Java Driver.
Java Application
Database Server
Fig. 1.8: JDBC-Net Pure Java Driver
• We can think of the application server as a JDBC "proxy", meaning that it makes calls
for the client application.
• As a result, we need some knowledge of the application server's configuration in
order to effectively use this driver type.
• The application server might use a Type 1, 2, or 4 drivers to communicate with the
database, understanding the nuances will prove helpful.
Advanced Java [BBA (CA) : Sem. VI] 1.9 JDBC
Advantages:
1. It does not require any native library to be installed on the client.
2. It has database independency.
3. It provides facility to switch over from one database to another database.
4. They support several networking options, such as HTTP tunneling.
5. They are suitable for web applications.
6. They are most suitable driver type amongst all.
Disadvantages:
1. Slow due to increase number of network call.
2. They can be difficult to set up since; the architecture is complicated by the
network interface.
3. It is costliest JDBC driver.
Type 4: Native Protocol Pure Java Drivers (100% Pure Java):
• In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's
database through socket connection.
• This is the highest performance driver available for the database and is usually
provided by the vendor itself.
• This kind of driver is extremely flexible; you don't need to install special software on
the client or server. Further, these drivers can be downloaded dynamically.
• Fig. 1.9 shows Native Protocol Pure Java driver.
Local Computer
Java Application
Application Code
Type 4
100% Pure Java Local
DBMS
Database Server
Fig. 1.9: Native Protocol Pure Java Drivers
• MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of
their network protocols, database vendors usually supply type 4 drivers.
Advanced Java [BBA (CA) : Sem. VI] 1.10 JDBC
Advantages:
1. These are 100% pure java drivers so they are portable in nature.
2. Better performance than all other drivers.
3. No translation is requires.
4. No software is required at client side or server side.
Disadvantage:
1. Drivers are depending on the Database.
JDBC Packages:
• JDBC API is contained in two packages:
1. java.sql: This package provides basic classes which are used to connect with
database and used to load and store data in database.
2. javax.sql: It extends the java.sql and provides classes that are used to interact
with Java Naming and Directory Interface (JNDI) and manages connection
pooling among other advanced JDBC features.
1.4 JDBC PROCESS
• Steps to create connectivity to the database MS-ACCESS/PostgreSQL/Mysql:
Step 1 : Load the driver and establish a database connection to the MS-Access/
PostgreSQL/mysql server.
Step 2 : Create an instance of the Statement object.
Step 3 : Execute a statement to get a ResultSet object.
Step 4 : Process the ResultSet object.
Step 5 : Close the database connection.
Step 1: Establishing a Database Connection:
(a) To connect to the PostgreSQL database, you need to provide account
information such as username, password, and the connection string.
For example, method connects to a PostgreSQL database EMP and returns a
Connection object:
Class.forName("postgresql.Driver");
public Connection connect() throws SQLException
{
return DriverManager.getConnection(url, user, password);
}
The URL, user and password are as follows:
private final String url = "jdbc:postgresql://localhost/EMP";
private final String user = "postgres";
private final String password = "postgres";
(b) To connect to the MS-ACCESS database, you need to provide account
information such as username, password, and the connection string.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:EMP", "root", "xyz");
Advanced Java [BBA (CA) : Sem. VI] 1.11 JDBC
• The execute() is used when there may be multiple results returned and
executeUpdate() method is used when query contains update or delete operation that
you want to perform on database.
• The executeUpdate() returns an integer value specifying the number of rows that are
affected by query.
• Use of executeQuery() Method: (using MS-ACCESS database)
private Connection con;
statement st;
ResultSet rs;
try
{
class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:EMP", "root", "xyz");
String query = "Select * from employee";
st=con.createStatement();
rs=st.executeQuery(query);
con.close();
}
• Use of executeQuery() Method: (using Mysql database)
1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the mysql database is
jdbc:mysql://localhost:3400/EMP where jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP
address, 3400 is the port number and EMP is the database name. We may use any
database, in such cases, we need to replace the EMP with our database name.
3. Username: The default username for the mysql database is root.
4. Password: It is the password given by the user at the time of installing the mysql
database. In this example, we are going to use root as the password.
private Connection con;
statement st;
ResultSet rs;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection( "jdbc:mysql://localhost
:3400/EMP","root","root");
String query="Select * from employee";
st=con.createStatement();
rs=st.executeQuery(query);
con.close();
}
Advanced Java [BBA (CA) : Sem. VI] 1.13 JDBC
con = DriverManager.getConnection
("jdbc:odbc:EMP", "root", "xyz");
String query = "Select * from employee where eid=?";
pst=con.preparedStatement(query);
pst.setString(1, "10");
rs=pst.executeQuery();
pst.close();
con.close();
}
Program 1.2: Program for PreparedStatement.
import java.sql.*;
public class jdbcConn
{
public static void main(String[] args) throws Exception
{
Connection con;
Statement stmt = null;
class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:EMP", "root", "xyz");
System.out.println("Opened database successfully");
PreparedStatement updateemp = con.prepareStatement
("insert into emp values(?,?,?)");
updateemp.setInt(1, 23);
updateemp.setString(2, "Deepak");
updateemp.setString(3, "Programmer");
updateemp.executeUpdate();
Statement stmt = con.createStatement();
String query = "select * from emp";
ResultSet rs = stmt.executeQuery(query);
System.out.println("Id Name Job");
while (rs.next())
{
int id = rs.getInt("id");
String name = rs.getString("name");
String job = rs.getString("job");
System.out.println(id + " " + name+" "+job);
}
}
}
Advanced Java [BBA (CA) : Sem. VI] 1.16 JDBC
Output:
Opened database successfully
id Name Job
23 Deepak Programmer
3. Callable Statement:
• This statement is used to call stored procedure from java component.
• Callable statement object uses three types of parameters when calling a stored
procedure, i.e. IN, OUT, INOUT.
• The IN parameter is used to pass input value to the procedure, for which again we
use setxxx() method, where xxx is data type.
• The OUT parameter is used to store any value return by procedure. For this OUT
parameter should be registered using registerOutParameter() method.
• The INOUT parameter is a single parameter that is used for both, passing as well as
retrieving information from procedure.
• The prepareCall() method is used to create an object of CallableStatement.
For example:
private Connection con;
CallableStatement cst;
ResultSet rs;
try
{
class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:EMP", "root", "xyz");
String query = "{ call EMPSALARY (?) } ";
cst = con. prepareCall(query);
cst.registerOutParameter(1, java.sql.Types. VARCHAR);
rs=cst.execute ();
EMPSALARY=cst.getString(1);
cst.close();
con.close();
}
Program 1.3: Program for Callable Statement.
import java.sql.*;
public class Sumval
{
public static void main(String[] args) throws Exception
{
Connection con;
Statement stmt = null;
class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:EMP", "root", "xyz");
Advanced Java [BBA (CA) : Sem. VI] 1.17 JDBC
catch(Exception e)
{
System.out.println("Error"+e);
}
}//main
}//end of class
Output:
Driver Loaded...
Connection Established...
Create statement...
Retrieved data
Student no student Name Student Per
10 amit 91.0
20 shubham 75.0
30 aditya 77.0
40 omkar 82.0
90 vandana 87.0
100 shruti 97.0
1.6 METADATA
• JDBC MetaData is the collective information about the data structure and property of
a column available in table.
• The metadata of any table tells us the name of the columns, datatype used in column
and constraint used to enter the value of data into column of the table.
• With the following interfaces we can retrieve some basic Metadata:
DatabaseMetaData:
• Applications sometime need to know something about the underlying database. For
example, an application might want to know the version of JDBC, even the maximum
number of open connections such as information can be retrieved using
DatabaseMetaData.
• It provides data about a database’s structure, such as the table names, primary and
foreign keys, and data types etc. In addition, you can use a DatabaseMetaData object
to probe the database to determine its attributes.
• The DatabaseMetaData object has many methods and properties that provide a lot of
information about a database.
Creating DatabaseMetaData Objects:
• A Connection object represents a database connection and also instantiates a
DatabaseMetaData object with the getMetaData() method.
• The DatabaseMetaData object holds information for the database to which the
Connection object is connected.
• The following code shows how to create a DatabaseMetaData object:
DatabaseMetaData dmd = conn.getMetaData();
Methods of DatabaseMetaData:
(i) getTables() method retrieve information about the tables.
(ii) getColumns() method retrieve information about table columns in a database.
(iii) getTypeInfo() method determines what data types your target database
supports.
Advanced Java [BBA (CA) : Sem. VI] 1.21 JDBC
Additional Programs
Program 1.6: Program to insert data into table student (using command Line) and
search a record and display the information of students.
import java.sql.*;
import java.io.*;
class Studinfo
{
public static void main(String a[])
{
try
{
int sno = Integer.parseInt(a[0]);
String sname = a[1];
Float sper = Float.parseFloat(a[2]);
int no = Integer.parseInt(a[3]);
System.out.println("Student No = "+sno);
System.out.println("Student Name = "+sname);
System.out.println("Student Percentage = "+sper);
class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:EMP", "root", "xyz");
System.out.println("Connection Established");
PreparedStatement ps = con.prepareStatement
("insert into student values(?,?,?)");
ps.setInt(1,sno);
ps.setString(2,sname);
ps.setFloat(3,sper);
Advanced Java [BBA (CA) : Sem. VI] 1.24 JDBC
int i = ps.executeUpdate();
System.out.println("Value ="+i);
System.out.println("Insert Data Successfully ...");
Statement st = con.createStatement();
System.out.println("Statement Created...");
ResultSet rs = st.executeQuery("select * from student");
System.out.println("Student No \t Student Name \t Student Per");
while(rs.next())
{
System.out.print(""+rs.getInt(1));
System.out.print("\t\t"+rs.getString(2));
System.out.print("\t\t"+rs.getFloat(3));
System.out.println();
} //while
//searching using Constant
Statement st1 = con.createStatement();
System.out.println("Statement Created...");
ResultSet rs1 = st.executeQuery
("select * from student where sno=20");
System.out.println("FOUND...");
System.out.println("Student No \t Student Name \t Student Per");
while(rs1.next())
{
System.out.print(""+rs1.getInt(1));
System.out.print("\t\t"+rs1.getString(2));
System.out.print("\t\t"+rs1.getFloat(3));
System.out.println();
} //while
}//try
catch(Exception e)
{
System.out.println("Error "+e);
}//catch
}//end of main
} //end of class
Output:
80 manisha 90.0
Student No = 20
Student Name = Shubham
Student Percentage = 75.0
Connection Established
Value =1
Insert Data Successfully ...
Statement Created...
Advanced Java [BBA (CA) : Sem. VI] 1.25 JDBC
//insert
PreparedStatement ps = con.prepareStatement
("insert into emp values(?,?,?)");
ps.setInt(1,eno);
ps.setString(2,ename);
ps.setInt(3,esal);
int j = ps.executeUpdate();
System.out.println("j = "+j);
}//for */
//Display (select )
Statement st = con.createStatement();
System.out.println("Statement Created...");
Connection con=null;
Statement sm=null;
ResultSet rs=null;
BufferedReader br=new BufferedReader
(new InputStreamReader(System.in));
try
{
class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:EMP", "root", "xyz");
// Step 3 create connectin
System.out.println("Connection Established...");
sm=con.createStatement();
do
{
System.out.println("1.Insert");
System.out.println("2.Modify");
System.out.println("1.Delete");
System.out.println("4.Search");
System.out.println("5.View All");
System.out.println("6.Exit");
System.out.println("Enter Your Choice:\t");
choice=Integer.parseInt(br.readLine());
switch (choice)
{
case 1:
System.out.println("Enter Roll No:\t");
int r=Integer.parseInt(br.readLine());
System.out.println("Enter Name:\t");
String name=br.readLine();
System.out.println("Enter Percentage:\t");
float f=Float.parseFloat(br.readLine());
int result=sm.executeUpdate("insert into
Student values("+r+",'"+name+"',"+f+");");
if(result>0)
System.out.println("Insert Successfully");
else
System.out.println("error");
break;
case 2:
System.out.println("Enter Roll No:\t");
r=Integer.parseInt(br.readLine());
System.out.println("1.Name");
Advanced Java [BBA (CA) : Sem. VI] 1.30 JDBC
System.out.println("2.Percentage");
System.out.println("Enter Your Choice:\t");
choice1=Integer.parseInt(br.readLine());
switch (choice1)
{
case 1:
System.out.println("Enter Name:\t");
name=br.readLine();
result=sm.executeUpdate("update Student set
sname='"+name+"'where sno="+r);
if(result>0)
System.out.println("Update Successfully");
else
System.out.println("error");
break;
case 2:
System.out.println("Enter Percentage:\t");
f=Float.parseFloat(br.readLine());
result=sm.executeUpdate("update Student
set per="+f+"where sno="+r);
if(result>0)
System.out.println("Update Successfully");
else
System.out.println("error");
break;
}
break;
case 3:
System.out.println("Enter Roll No:\t");
r=Integer.parseInt(br.readLine());
result=sm.executeUpdate("delete from
Student where sno="+r+";");
if(result>0)
System.out.println("Deleted Successfully");
else
System.out.println("error");
break;
case 4:
System.out.println("Enter Roll No:\t");
r=Integer.parseInt(br.readLine());
rs=sm.executeQuery
("select * from Student where sno="+r+";");
ResultSetMetaData rsmd=rs.getMetaData();
int col=rsmd.getColumnCount();
Advanced Java [BBA (CA) : Sem. VI] 1.31 JDBC
for(int i=1;i<=col;i++)
System.out.print(rsmd.getColumnLabel(i) +"\t");
System.out.println();
while(rs.next())
{
for(int i=1;i<=col;i++)
System.out.print(rs.getString(i)+"\t");
System.out.println();
}
break;
case 5:
rs=sm.executeQuery("select * from Student;");
rsmd=rs.getMetaData();
col=rsmd.getColumnCount();
for(int i=1;i<=col;i++)
System.out.print(rsmd.getColumnLabel(i)+"\t");
System.out.println();
while(rs.next())
{
for(int i=1;i<=col;i++)
System.out.print(rs.getString(i)+"\t");
System.out.println();
}
break;
case 6:System.exit(0);
}
}while(true);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
1.Insert
2.Modify
3.Delete
4.Search
5.View All
6.Exit
Advanced Java [BBA (CA) : Sem. VI] 1.32 JDBC
Enter Percentage:
75
Insert Successfully
1.Insert
2.Modify
3.Delete
4.Search
5.View All
6.Exit
Enter Your Choice:
5
sno sname sper
2 BBB 89
3 ZZZ 92
1 AAA 75
1.Insert
2.Modify
3.Delete
4.Search
5.View All
6.Exit
Enter Your Choice:
2
Enter Roll No:
1
1.Name
2.Percentage
Enter Your Choice:
1
Enter Name:
XXX
Update Successfully
1.Insert
2.Modify
3.Delete
4.Search
5.View All
6.Exit
Enter Your Choice:
5
Advanced Java [BBA (CA) : Sem. VI] 1.35 JDBC
Practice Questions
Q.I Answer the following questions in short:
1. What is the use of SetAutoCommit()?
2. Write short note on: JDBC API Packages.
3. What is database?
4. What is meant by JDBC driver?
5. What is the use of JDBC API?
6. What is ResultSetMetaData?
7. What is DatabaseMetaData?
Advanced Java [BBA (CA) : Sem. VI] 1.38 JDBC
2.1 INTRODUCTION
• Multithreading is one of the most important feature of Java. Multithreading in Java is
a process of executing multiple threads simultaneously. Java provides built-in
support for multi-threaded programming.
• Java is a multi-threaded programming language which means we can develop multi-
threaded program using Java.
• A multi-threaded program contains two or more parts that can run concurrently and
each part can handle different task at the same time making optimal use of the
available resources especially when your computer has multiple CPUs.
• By definition multitasking is when multiple processes share common processing
resources such as a CPU.
• Multithreading extends the idea of multitasking into applications where you can
subdivide specific operations within a single application into individual threads. Each
of the threads can run in parallel.
• The OS (Operating System) divides processing time not only among different
applications, but also among each thread within an application.
• Multithreading enables us to write in a way where multiple activities can proceed
concurrently in the same program.
(2.1)
Advanced Java [BBA (CA) : Sem. VI] 2.2 Multithreading
Process 2
t2
t3
t1
Process 1
Process 3
.
Fig. 2.1: Thread Process
• As shown in the Fig. 2.1, thread is executed inside the process. There is context-
switching between the threads. There can be multiple processes inside the OS and one
process can have multiple threads.
• Conceptually, 'a thread is a basic unit of CPU utilization'. A thread is similar to the
sequential programs.
• A single-thread has a beginning, a sequence and an end. A thread comprises a thread
ID, a program counter, a register set and a stack.
• A thread shares the code section, data section and other operating system resources
[like open files] with other threads belonging to the same process.
• Multi-threaded application has many threads executing concurrently. This is the
facility given by Java virtual machine.
• Fig. 2.2 (a) illustrates single-threaded process and Fig. 2.2 (b) illustrates multi-
threaded process.
Advanced Java [BBA (CA) : Sem. VI] 2.3 Multithreading
Thread
New
Non-Runnable
(Blocked)
Running
sleep, block on I/O, wait
run() method for lock, suspend, wait
exits
Terminated
Thread
Extends Implements
Thread Runnable
(class) (interface)
Override
run( )
method
6. public final void join(long millisec): The current thread invokes this
method on a second thread, causing the current thread to block until the second
thread terminates or the specified number of milliseconds passes.
7. public void interrupt(): Interrupts this thread, causing it to continue
execution if it was blocked for any reason.
8. public final boolean isAlive(): Returns true if the thread is alive, which is
any time after the thread has been started but before it runs to completion.
• The previous methods are invoked on a particular Thread object. The following
methods in the Thread class are static. Invoking one of the static methods performs
the operation on the currently running thread.
1. public static void yield(): Causes the currently running thread to yield to
any other threads of the same priority that are waiting to be scheduled.
2. public static void sleep(long millisec): Causes the currently running
thread to block for at least the specified number of milliseconds.
3. public static boolean holdsLock(Object x): Returns true if the current thread
holds the lock on the given Object.
4. public static Thread currentThread(): Returns a reference to the currently
running thread, which is the thread that invokes this method.
Program 2.1: Program for creating a thread.
public class DemoThread extends Thread
{
public static void main(String[] args)
{
Thread thread1 = new Thread("My Thread1");
Thread thread2 = new Thread("My Thread2");
thread1.start();
thread2.start();
System.out.println("Thread names are following:");
System.out.println(thread1.getName());
System.out.println(thread2.getName());
}
public void run()
{
}
}
Output:
Thread names are following:
My Thread1
My Thread2
Advanced Java [BBA (CA) : Sem. VI] 2.7 Multithreading
(b)
Fig. 2.6: (a) main thread, (b) created thread (when object is created)
Program 2.5: Illustrates the usage of setName() and getPriority() methods.
import java.lang.*;
class MytestThread
{
public static void main(String args[])
{
Thread thread = Thread.currentThread();
System.out.println("current Thread is " + thread);
thread.setName("mythread");
System.out.println("New name " + thread);
int priority = thread.getPriority();
thread.setPriority(10);
System.out.println("The priority is : " + thread.getPriority());
}
}
Output:
current Thread is Thread[main,5,main]
New name Thread[mythread,5,main]
The priority is : 10
Advanced Java [BBA (CA) : Sem. VI] 2.11 Multithreading
catch (InterruptedException e)
{
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start ()
{
System.out.println("Starting " + threadName );
if(t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}
}
public class TestMyThread
{
public static void main(String args[])
{
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();
RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2.start();
}
}
Output:
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-2
Running Thread-1
Thread: Thread-2, 4
Thread: Thread-1, 4
Thread: Thread-2, 3
Advanced Java [BBA (CA) : Sem. VI] 2.13 Multithreading
Thread: Thread-1, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-2 exiting.
Thread Thread-1 exiting.
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
Output:
Running thread name is: Thread-1
Running thread priority is: 10
Running thread name is: Thread-0
Running thread priority is: 1
mythread3
Main Thread2
mythread4
mythread5
Main Thread3
Thread exists
Main Thread4
Main Thread5
main Thread Exists
• This output may change PC to PC. In this program, two threads main thread and
mythread (coun) runs simultaneously.
• In the above example, mythread suspends threads for 500 millisecond by calling its
sleep method. The mainthread first get control of CPU and count as 1 and then
suspended for 1000 milliseconds.
• The Program 2.9 illustrates the calling of the start method from main method and not
from constructor. In a constructor, we will use a super method. It gets one argument
as string which is name of a thread. In this program, we will create three different
objects.
Program 2.9: Program to use of super in threading.
class mythread extends Thread
{
mythread(String name)
{
super(name);
}
public void run()
{
try
{
for(int k=5;k>0;k--)
{
System.out.println(getName() + k);
Thread.sleep(500);
}
}
Advanced Java [BBA (CA) : Sem. VI] 2.17 Multithreading
catch(InterruptedException e)
{
System.out.println("Thread interrupted");
}
System.out.println("Thread exists");
} //end run()
} //end mythread
//Main class for thread object
class Mainthread1
{
public static void main(String args[])
{
mythread ob1 = new mythread ("First");
mythread ob2 = new mythread ("Second");
mythread ob3 = new mythread ("Third");
ob1.start();
ob2.start();
ob3.start();
try
{
for(int k=5;k>0;k--)
{
System.out.println("main thread" +k);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println("interrupted thread");
}
System.out.println("main thread exists");
} //end main
} //end class mainthread
Output:
main thread5
Third5
First5
Second5
Advanced Java [BBA (CA) : Sem. VI] 2.18 Multithreading
Third4
First4
Second4
main thread4
Third3
Second3
First3
main thread3
Third2
First2
Second2
main thread2
Third1
Second1
First1
main thread1
Thread exists
main thread exists
Thread exists
Thread exists
• In above Program 2.9, the constructor is parameterized which takes one argument of
type string. This argument is the name of thread.
• First, second and third are the names of thread. So in this program, four threads are
running simultaneously. This is shown in Fig. 2.7.
code data files
2.7 SYNCHRONIZATION
• In this section we will study synchronization and inter-thread communication in
Java.
Advanced Java [BBA (CA) : Sem. VI] 2.19 Multithreading
2.7.1 Synchronization
• Multithreading introduces asynchronous behavior to the programs. If a thread is
writing some data another thread may be reading the same data at that time. This
may bring inconsistency.
• When two or more threads wants to access a shared resource, then it must ensure
that the resource will be used by only one thread at an instant of time. The
mechanism of this process is called synchronization.
• Synchronization is the concept of the monitor or semaphore. Monitor works as mutex
and restrict to one thread to own a monitor at a given time.
• As the thread acquires the lock, all the threads that want to acquire the monitor will
be suspended.
• As the first thread exits from the monitor, one thread will acquire monitor from the
waiting list of threads.
• Java programming language provides a very handy way of creating threads and
synchronizing their task by using synchronized blocks.
• We keep shared resources within this block. Following is the general form of the
synchronized statement:
synchronized(objectidentifier) {
// Access shared variables and other shared resources
}
• Here, the objectidentifier is a reference to an object whose lock associates with the
monitor that the synchronized statement represents.
• Synchronization in java is the capability to control the access of multiple threads to
any shared resource.
• Java Synchronization is better option where we want to allow only one thread to
access the shared resource.
Program 2.10: Program for synchronization.
class mythread extends Thread
{
String msg[]={"Java", "Supports", "Multithreading", "Concept"};
mythread(String name)
{
super(name);
}
public void run()
{
display(getName());
System.out.println("Exit from "+getName());
}
Advanced Java [BBA (CA) : Sem. VI] 2.20 Multithreading
1. wait(): It is used to tell the calling thread to give up the lock and go to sleep until
some other thread enters the same lock and calls notify( ).
Syntax: public final void wait(long timeout)
2. notify(): It wakes up the first thread that called wait( ) on the same
object.
Syntax: public final void notify()
3. notifyAll(): It wakes up all the threads that called wait( ) on the same object.
Here, the highest priority thread will run first.
Syntax: public final void notifyAll()
Program 2.11: Program shows how two thread can communicate using wait() and notify()
method. We can create a complex system using the same concept.
class Chat
{
boolean flag = false;
public synchronized void Question(String msg)
{
if (flag)
{
try
{
wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println(msg);
flag = true;
notify();
}
public synchronized void Answer(String msg)
{
if (!flag)
{
try
{
wait();
}
Advanced Java [BBA (CA) : Sem. VI] 2.22 Multithreading
catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println(msg);
flag = false;
notify();
}
}
class T1 implements Runnable
{
Chat m;
String[] s1 = { "Hi", "How are you?", "I am also doing fine!" };
public T1(Chat m1)
{
this.m = m1;
new Thread(this, "Question").start();
}
public void run()
{
for (int i = 0; i < s1.length; i++)
{
m.Question(s1[i]);
}
}
}
class T2 implements Runnable
{
Chat m;
String[] s2 = { "Hi", "I am good, what about you?", "Great!" };
public T2(Chat m2)
{
this.m = m2;
new Thread(this, "Answer").start();
}
Advanced Java [BBA (CA) : Sem. VI] 2.23 Multithreading
Additional Programs
Program 2.12: Program to display the 100, 99, 98…… 1 using thread.
class MyThredDemo1
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println("Current thread is: " + t);
t.setName("Demo Thread");
System.out.println("After changing the name thread is: " + t);
try
{
for(int n = 100; n> 0; n--)
Advanced Java [BBA (CA) : Sem. VI] 2.24 Multithreading
{
System.out.println(n);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Thread interrupted");
}
}
}
Output:
Current thread is: Thread[main,5,main]
After changing the name thread is: Thread[Demo Thread,5,main]
100
99
98
97
96
95
94
93
92
91
90
89
88
87
86
85
84
83
82
81
80
79
78
Advanced Java [BBA (CA) : Sem. VI] 2.25 Multithreading
77
76
75
74
73
72
71
70
69
68
67
66
65
64
63
62
61
60
59
58
57
56
55
54
53
52
51
50
49
48
47
46
45
44
43
42
41
40
Advanced Java [BBA (CA) : Sem. VI] 2.26 Multithreading
39
38
37
36
35
34
33
32
31
30
29
28
27
26
25
24
23
22
21
20
19
18
17
16
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
Advanced Java [BBA (CA) : Sem. VI] 2.27 Multithreading
try
{
for (int i = 0; i < 5; i++)
{
System.out.println("Child Thread: " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println("Child Thread Interrupted");
}
System.out.println("Exiting child thread");
}
}
class DemoMyThread3
{
public static void main(String args[])
{
new NewThread();
try
{
for (int i = 0; i < 5; i++)
{
System.out.println("Main Thread: " + i);
Thread.sleep(500);
}
}
catch (InterruptedException e)
{
System.out.println("Main Thread Interrupted");
}
System.out.println("Exiting main thread");
}
}
Advanced Java [BBA (CA) : Sem. VI] 2.30 Multithreading
Output:
Child Thread: Thread[Demo Thread,5,main]
Main Thread: 0
Child Thread: 0
Main Thread: 1
Child Thread: 1
Main Thread: 2
Main Thread: 3
Child Thread: 2
Main Thread: 4
Exiting main thread
Child Thread: 3
Child Thread: 4
Exiting child thread
Program 2.15: Java program to display "BYE CORONA…" message n times using Runnable
Interface.
import java.io.*;
public class DemoMyThread4 implements Runnable
{
int i, no;
DemoMyThread4(int n)
{
no = n;
}
public void run()
{
for(i = 1; i<=no; i++)
{
System.out.println("BYE CORONA...");
try
{
Thread.sleep(50);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Advanced Java [BBA (CA) : Sem. VI] 2.31 Multithreading
import java.io.*;
import java.lang.String.*;
class TestPrint extends Thread
{
String msg="";
int n;
TestPrint(String msg, int n)
{
this.msg=msg;
this.n=n;
}
public void run()
{
try
{
for(int i=1;i<=n;i++)
{
System.out.println(msg+" "+i+" times");
}
System.out.println("\n ");
}
catch(Exception e)
{
}
}
}
public class DemoMyThread5
{
public static void main(String args[])
{
int n=Integer.parseInt(args[0]);
TestPrint t1=new TestPrint("COVID19",n);
t1.start();
TestPrint t2=new TestPrint("LOCKDOWN2020",n+10);
t2.start();
TestPrint t3=new TestPrint("VACCINATED2021",n+20);
t3.start();
}
}
Advanced Java [BBA (CA) : Sem. VI] 2.33 Multithreading
Output:
VACCINATED2021 1 times
LOCKDOWN2020 1 times
COVID19 1 times
LOCKDOWN2020 2 times
VACCINATED2021 2 times
LOCKDOWN2020 3 times
COVID19 2 times
LOCKDOWN2020 4 times
VACCINATED2021 3 times
LOCKDOWN2020 5 times
COVID19 3 times
LOCKDOWN2020 6 times
VACCINATED2021 4 times
LOCKDOWN2020 7 times
COVID19 4 times
LOCKDOWN2020 8 times
VACCINATED2021 5 times
LOCKDOWN2020 9 times
COVID19 5 times
LOCKDOWN2020 10 times
VACCINATED2021 6 times
LOCKDOWN2020 11 times
COVID19 6 times
LOCKDOWN2020 12 times
VACCINATED2021 7 times
LOCKDOWN2020 13 times
COVID19 7 times
LOCKDOWN2020 14 times
VACCINATED2021 8 times
LOCKDOWN2020 15 times
LOCKDOWN2020 16 times
VACCINATED2021 9 times
VACCINATED2021 10 times
LOCKDOWN2020 17 times
VACCINATED2021 11 times
Advanced Java [BBA (CA) : Sem. VI] 2.34 Multithreading
VACCINATED2021 12 times
VACCINATED2021 13 times
VACCINATED2021 14 times
VACCINATED2021 15 times
VACCINATED2021 16 times
VACCINATED2021 17 times
VACCINATED2021 18 times
VACCINATED2021 19 times
VACCINATED2021 20 times
VACCINATED2021 21 times
VACCINATED2021 22 times
VACCINATED2021 23 times
VACCINATED2021 24 times
VACCINATED2021 25 times
VACCINATED2021 26 times
VACCINATED2021 27 times
Program 2.17: Program to use the method to suspend thread.
class NewThread implements Runnable
{
String thName;
Thread t;
NewThread(String name)
{
thName = name;
t = new Thread(this);
System.out.println("Thread started: " + t);
t.start();
}
public void run()
{
try
{
for (int i = 0; i <10; i++)
{
System.out.println(t.getName() + " " + i);
Thread.sleep(200);
}
}
Advanced Java [BBA (CA) : Sem. VI] 2.35 Multithreading
catch (InterruptedException e)
{
System.out.println(t + " Interrupted");
}
System.out.println(thName + " Exiting");
}
}
class DemoThread6
{
public static void main(String args[])
{
NewThread th1 = new NewThread("First");
NewThread th2 = new NewThread("Second");
try
{
Thread.sleep(600);
th1.t.suspend();
System.out.println("Thread 1 suspended");
Thread.sleep(600);
th1.t.resume();
System.out.println("Thread 1 resumed");
th2.t.suspend();
System.out.println("Thread 2 suspended");
Thread.sleep(600);
th2.t.resume();
System.out.println("Thread 2 resumed");
}
catch (InterruptedException e)
{
System.out.println("Main Thread Interrupted");
}
try
{
System.out.println("Waiting for threads to terminate");
th1.t.join();
th2.t.join();
}
Advanced Java [BBA (CA) : Sem. VI] 2.36 Multithreading
catch (InterruptedException e)
{
System.out.println("Main Thread Interrupted");
}
System.out.println("Exiting main thread");
}
}
Output:
Thread started: Thread[Thread-0,5,main]
Thread started: Thread[Thread-1,5,main]
Thread-0 0
Thread-1 0
Thread-0 1
Thread-1 1
Thread-0 2
Thread-1 2
Thread 1 suspended
Thread-1 3
Thread-1 4
Thread-1 5
Thread 1 resumed
Thread-0 3
Thread 2 suspended
Thread-0 4
Thread-0 5
Thread-0 6
Thread 2 resumed
Thread-1 6
Waiting for threads to terminate
Thread-1 7
Thread-0 7
Thread-0 8
Thread-1 8
Thread-0 9
Thread-1 9
Second Exiting
First Exiting
Exiting main thread
Advanced Java [BBA (CA) : Sem. VI] 2.37 Multithreading
Deadlock()
{
Thread.currentThread().setName("Main Thread");
Thread t = new Thread(this, "Child Thread");
t.start();
a.first(b);
System.out.println("Back in main thread");
}
public void run()
{
b.first(a);
System.out.println("Back in child thread");
}
public static void main(String args[]) throws IOException
{
new Deadlock();
}
}
Output:
Main ThreadExecuting A.first()
Main ThreadTrying to execute B.last()
Child ThreadExecuting B.first()
Child ThreadTrying to execute A.last()
-
-
-
Program 2.19: Program to use of wait(), notify() methods.
import java.io.*;
import java.lang.*;
class Shared
{
int a;
boolean valueChanged = false;
synchronized int get_data()
{
if (!valueChanged)
Advanced Java [BBA (CA) : Sem. VI] 2.39 Multithreading
try
{
wait();
}
catch (InterruptedException e)
{
System.out.println(" Interrupted");
}
System.out.println("Read: " + a);
valueChanged = false;
notify();
return a;
}
synchronized void put_data(int n)
{
if (valueChanged)
try
{
wait();
}
catch (InterruptedException e)
{
System.out.println( "Interrupted");
}
this.a = n;
valueChanged = true;
System.out.println("Written: " + a);
notify();
}
}//Shared End
class Producer implements Runnable
{
Shared ob;
Producer (Shared ob)
{
this.ob = ob;
new Thread(this, "Producer").start();
}
Advanced Java [BBA (CA) : Sem. VI] 2.40 Multithreading
Output:
Press Cntl+c to stop
Written: 0
Read: 0
Written: 1
Read: 1
Written: 2
Read: 2
Written: 3
Read: 3
Written: 4
Read: 4
Written: 5
Read: 5
Written: 6
Read: 6
Written: 7
Read: 7
Written: 8
Read: 8
Written: 9
Read: 9
Written: 10
Read: 10
Program 2.20: Program to use of join() methods.
import java.io.*;
class Maths_op
{
int a = 5;
void add_op(int b)
{
try
{
Thread.sleep(500);
}
Advanced Java [BBA (CA) : Sem. VI] 2.42 Multithreading
catch (InterruptedException e)
{
System.out.println(" Interrupted Thread");
}
a += b;
System.out.println("a = " + a);
}
}
class NewThread implements Runnable
{
Thread t;
Maths_op ob1;
int op2;
NewThread(Maths_op ob, int p)
{
ob1 = ob;
op2 = p;
t = new Thread(this);
t.start();
}
public void run()
{
synchronized (ob1)
{
ob1.add_op(op2);
}
}
}
class DemoThread9
{
public static void main(String args[])throws IOException
{
Maths_op ob = new Maths_op();
NewThread th1 = new NewThread(ob, 100);
NewThread th2 = new NewThread( ob, 200);
NewThread th3 = new NewThread( ob, 300);
Advanced Java [BBA (CA) : Sem. VI] 2.43 Multithreading
try
{
th1.t.join();
th2.t.join();
th3.t.join();
}
catch (InterruptedException e)
{
System.out.println("Main Thread Interrupted");
}
}
}
Output:
a = 105
a = 405
a = 605
Program 2.21: Program to use of priority thread.
class NewThread implements Runnable
{
Thread t;
NewThread(String thname, int p)
{
t = new Thread(this);
t.setName(thname);
t.setPriority(p);
}
void start()
{
t.start();
}
public void run()
{
try
{
for (int i = 0; i <10; i++)
{
Advanced Java [BBA (CA) : Sem. VI] 2.44 Multithreading
Output:
COVISHIELD 0
COVISHIELD 1
COVISHIELD 2
COVISHIELD 3
COVISHIELD 4
COVISHIELD 5
COVISHIELD 6
COVISHIELD 7
COVISHIELD 8
COVISHIELD 9
COVISHIELD Exiting
COVAXIN 0
COVAXIN 1
COVAXIN 2
COVAXIN 3
COVAXIN 4
COVAXIN 5
COVAXIN 6
COVAXIN 7
COVAXIN 8
COVAXIN 9
COVAXIN Exiting
Waiting for threads to terminate
Exiting main thread
Summary
• Multithreading is a specialized form of multitasking. Multitasking can be of two
types. These are Process based multi tasking and Thread based multitasking.
• Java runtime system depends on threads for many things. In a single threaded
environment, when a thread is blocked when it is waiting for a resource. Because of
this, the entire program stops running. The benefits of multithreading is that, one
thread can pause without stopping the other parts of your program. All other threads
continue to run. This helps in improving the efficiency by preventing the waste of
CPU cycles.
• When Java starts up, one thread begins running immediately. This thread is called a
main thread of a program. This main thread is the one when your program begins its
execution.
Advanced Java [BBA (CA) : Sem. VI] 2.46 Multithreading
• During the life time of a thread, it goes into several states mentioned below:
o Newborn state
o Runnable state
o Running state
o Block state
o Dead state.
• Thread is created by instantiating an object of type Thread. Java defines two ways for
creating a thread.
o By extending Thread class.
o By implementing the Runnable interface.
• In Java, Each thread is assigned a priority. Thread priorities are used by the thread
scheduler to decide when each thread should be allowed to run.
• To set the threads priority, use setPriority() method. This method is a member of
Thread class.
• Thread class also defines several priority constants
o MIN_PRIORITY = 1
o NORM_PRIORITY = 5 //default priority
o MAX_PRIORITY = 10
• When two or more threads wants to access a shared resource, then it must ensure
that the resource will be used by only one thread at an instant of time. The
mechanism of this process is called synchronization.
• Inter-thread communication is a mechanism in which a thread is paused running in
its critical section and another thread is allowed to enter (or lock) in the same critical
section to be executed. It is implemented by following methods like wait( ), notify( ),
notifyAll( ) of Object class.
Practice Questions
Q.I Answer the following questions in short:
1. What is a thread?
2. What are two different ways used to implement threading in java programs?
3. Explain the concept of thread synchronization?
4. Explain the following methods.
(a) Sleep()
(b) resume()
(c) getPriority()
(d) getName()
(e) wait()
(f) notify()
Q.II Answer the following questions:
1. Explain thread life cycle in detail.
2. Explain the thread priorities with an example.
3. What is synchronization? Why it is used?
Q.III Define Term:
1. Multithreading
2. Thread
3. Synchronization
3…
Networking
Learning Objectives …
Students will be able:
▣ To understand the Basics of Networking.
▣ To know about java.net Package.
▣ To study about Networking Classes and Interfaces.
▣ To implement TCP/IP based Server and Client.
3.2.1 Sockets
• Most networking java programs communicate using sockets.
• A network socket identifies an endpoint in the network.
• Sockets are the foundation of today’s networking world as it allows a single computer
to serve any clients. This can be accomplished with the help of a ‘port’.
• Port is a numbered socket on a particular machine.
• An IP port on a specific machine is called socket.
• Anything that understands the standard protocol can plug in to the socket and can
communicate.
• With electrical socket, it does not matter whether you plug in a lamp or television or
music system as long as they work with standard voltage.
• Connection oriented sockets make use of TCP and connection less sockets use UDP.
• TCP based sockets guarantee arrival of data and in correct order, whereas UDP based
sockets do not.
• When speaking about network sockets TCP/IP packets and IP addresses immediately
come to mind.
• Socket communication takes place via a protocol.
• IP (Internet Protocol) is a low level routing protocol that breaks data into small
packets and sends them to an address across a network.
• Transmission Control Protocol (TCP) is a higher level protocol that manages to string
together these packets, sorting and retransmitting them as necessary, to robustly and
reliably transmit data to an address across a network.
Advanced Java [BBA (CA) : Sem. VI] 3.3 Networking
• A third protocol User Datagram Protocol (UDP) does a similar job as TCP and can be
used directly to support fast, connectionless transport of packets from source to
destination.
3.2.2 Port Numbers
• A computer has a single physical connection to the network. All data destined for a
particular computer arrives through that connection. However, the data may be
intended for different applications running on the computer. So how does the
computer know to which application to forward the data? An answer is through the
use of ‘ports’.
• In connection-based communication such as TCP, a server application binds a socket
to a specific port number. This has the effect of registering the server with the system
to receive all data destined for that port. A client can then communicate with the
server at the server's port, as illustrated here:
P
server o
r TCP
t
client
TCP or UDP
Packet
port # Data
Data
Fig. 3.2: UDP Packet Routing
• Port number is a 16-digit number and so ranges from 0 to 65535.
• The port numbers ranging from 0 - 1023 are restricted; they are reserved for use by
well-known services such as HTTP and FTP and other system services. These ports are
called well-known ports for the use of well-known services like HTTP, FTP etc. Your
applications should not use the well known port numbers.
Advanced Java [BBA (CA) : Sem. VI] 3.4 Networking
3.2.3 Protocols
1. Internet Protocol (IP)
• The Internet Protocol (IP) is a Layer 3 protocol, (network layer) that is used to transmit
data packets over the Internet. It is undoubtedly the most widely used networking
protocol in the world and has spread prolifically.
• Regardless of what type of networking hardware is used, it will almost certainly
support IP networking.
• IP acts as a bridge between networks of different types, forming a worldwide network
of computers and smaller sub networks.
• The Internet Protocol is a packet-switching network protocol. Information is
exchanged between two hosts in the form of IP packets, also known as IP datagram’s.
• Each datagram is treated as a discrete unit, not related to any other previously sent
packet.
• Instead, a series of datagram’s are sent and higher-level protocols at the transport
layer provide connection services.
IP Address
• The addressing of IP datagram’s is an important issue, as applications require a way to
deliver packets to specific machines and to identify the sender. Each host machine
under the Internet Protocol has a unique address, the IP address.
• The IP address is a four-byte (32-bit) address, which is usually expressed in dotted
decimal format (For example, 192.163.0.6). Although a physical address will normally
be issued to a machine, it will not be very useful as the machine goes onto a network.
• Even if somehow every machine could be located by its physical address, if the
address changed for any reason (such as installation of a new networking connection
or reassignment of the network interface by the administrator), then the machine
would no longer be locatable.
• Instead, a new type of address is introduced, that is not bound to a particular physical
location. IP address is a numerical number that uniquely identifies a machine on the
Internet.
• Typically, one machine has a single IP address, but it can have multiple addresses. A
machine could, for example, have more than one network card, or could be assigned
multiple IP addresses, (known as virtual addresses) so that it can appear to the
outside world as many different machines.
• Machines connected to the Internet can send data to that IP address and routers and
gateways ensure delivery of the message. In normal programming, only the IP
address is needed, the physical address is neither useful nor accessible in Java.
Host Name:
• Numerical address values serve the purposes of computers but they are not designed
keeping people in mind. It is almost impossible for a human to remember thousands
of 32-bit IP addresses in dotted decimal format.
Advanced Java [BBA (CA) : Sem. VI] 3.5 Networking
Proxy Servers:
• A proxy server is software that runs on server that speaks the language of clients. This
software hides the actual server from clients that communicate with it.
• It is like a machine that acts as a proxy for application protocol. This is required when
client has restrictions on which servers they can connect to.
• This has two advantages: Direct access to internal machine is never established and
the proxy server can control the transaction.
• Thus, a client would connect to a proxy server, which did not have such restrictions
and the proxy server would in turn service the client while communicating back to
back with a server on which the resources required by the client side.
• Proxy server is a bridge between a client application and real server.
• It checks each request to real server, to see it, it can satisfy the request Otherwise,
forwards it to real server.
• Main goals of proxy server are:
o Improve performance: Proxy server saves the results of all the requests. So, after
some time it can improve the performance for group of users
o Proxy server is on the same network as the user and so if data is available on proxy
server, it can be fetched efficiently.
o Filter requests: It can also be used to filter the requests. This helps in preventing
access users to certain web-sites
Thus, proxy server sits between LAN and external network and provides security and
efficiency.
Firewalls are alternatives used now-a-days.
• A proxy server has the additional ability to filter clients request or cache the results of
those requests for future use. A caching proxy HTTP server can help reduce the
bandwidth demands and a local networks connection to the internet.
• When a popular web site is being hit by hundreds of uses, a proxy server can get the
contents of web server’s popular pages once and serve these in its cache, thus saving
expensive internet data transfers while providing fast access to the same pages on its
clients.
• Most proxy servers also keep a record of networking events, to allow network
administrators to track unusual communications and their origin in this way,
employees visiting inappropriate sites or grouting off during work can be easily
monitored.
• This might sound worrisome and introduce some very serious legal and privacy
issues, but there are some security concerns addressed by logging, such as identifying
disloyal employees who are visiting job-search sites or sending information to
competitors.
Advanced Java [BBA (CA) : Sem. VI] 3.8 Networking
Internet Addressing:
• The internet is the world’s largest network and it is growing bigger every day. Every
computer on the internet has a unique IP address.
• An internet address is the number that uniquely indentifies each computer on the
internet just like any other network.
• Internet addresses consist of 32 bit values, organized into 4 groups of 8 bits each
separated by dot[.].
• These addresses are represented in a format called dotted-decimal notation.
• In this notation each group of 8 bits, called as octet, is represented as decimal
equivalent.
• Along with IP address, we also need to specify port for accessing data from a
computer on internet e.g. port number for HTTP protocol is 80.
• Port number is specified using a colon after IP address.
• If port number is not specified default port for the protocol is used (e.g. port 80 for
HTTP).
• The first few bits of IP address define which class of network lettered as A, B, C, and D
or E, most internet users are on a class C network.
• The internet would not be a very friendly place to navigate if everyone had to refer to
their addresses as a series of numbers separated by a period.
• For example, it is hard to imagine seeing http://192.168.90.1 at the bottom of an
advertisement.
• A clearing house exists for a parallel hierarchy of names bound to each of these
unique numbers. It is called the Domain Naming Service (DNS).
• Just as the four numbers of an IP address describes a network hierarchy from left to
right, the name of an internet address, called its domain name, describes a machines
location in a name space, from right to left.
• Under java such addresses are represented by the java.net.InetAddress class. This
class can fill a variety of tasks, from resolving an IP address to looking up the
hostname.
3.3.1 Classes
• Java supports both TCP and UDP protocol families.
• URL and URLConnection classes provide a quick and easy way to access content using
uniform resource locators.
• The URLEncoder class provides a way to convert text for use as arguments for CGI
scripts.
• Server Socket, Datagram Socket and InetAddress are the classes that provide access to
plain bare-bone networking facilities. They are the building blocks for implementing
new protocols, talking to pre-existing servers and the like.
• The Content Handler and URLStreamHandler are the abstract classes used to extend
the capabilities of URL class.
• The following table lists all of the classes in the package along with a brief description
of what functionality each provides.
Class Purpose
URL Represents a Uniform Resource Locator.
URLConnection Retrieves content addressed by URL objects.
Socket Provides a TCP (connected, ordered stream) socket.
Sever Socket Provides a server (listening) TCP socket.
Datagram Socket Provides a UDP (connectionless datagram) socket.
Datagram Packet Represents a datagram to be sent using a Datagram Socket.
InetAddress Represents a host name and its corresponding IPnumber or
numbers.
URLEncoder Encodes text in the x-www-form-urlencoded format.
URLStreamHandler Subclasses implement communications streams for different URL
protocols.
ContentHandler Subclasses know how to turn MIME objects into corresponding
Java objects.
SocketImpl Subclasses provide access to TCP/IP facilities.
3.3.2 Interfaces
• The java.net package defines three interfaces. These primarily are used behind the
scenes by the other networking classes rather than by user classes.
• Unless you are porting Java to a new platform or are extending it to use a new socket
protocol, you probably will have no need to implement these interfaces in a class.
Advanced Java [BBA (CA) : Sem. VI] 3.10 Networking
• On rare occasions, you will need to connect to a machine that does not have a
hostname. In this case, you can pass a String containing the dotted quad form of the
IP address to,
InetAddress.getByName(): InetAddress address =
InetAddress.getByName("196.148.60.9");
Uses the IP address for www.yahoo.com instead of the name.
Program 3.3: Program that prints the address of 196.148.60.9.
import java.net.*;
public class ExampleByAddress
{
public static void main (String[] args)
{
try
{
InetAddress address = InetAddress.getByName("196.14860.9");
System.out.println(address);
}
catch (UnknownHostException e) {
System.out.println("Could not find 196.148.60.9");
}
}
}
• Some computers have more than one Internet address. Given a hostname,
InetAddress.getAllByName() returns an array that contains all the addresses
corresponding to that name. Its use is straightforward:
InetAddress[] addresses = InetAddress.getAllByName("www.microsoft.com");
Like InetAddress.getByName(), InetAddress.getAllByName()
It can throw an UnknownHostException, so you need to enclose it in a try block or
declare that your method throws UnknownHostException. Example below
demonstrates by returning a complete list of the IP addresses for
www.microsoft.com.
Program 3.4: Program that prints all the addresses of www.microsoft.com
import java.net.*;
public class AllAddressesOfMicrosoft
{
public static void main (String[] args)
{
Advanced Java [BBA (CA) : Sem. VI] 3.14 Networking
try
{
InetAddress[] addresses = InetAddress.getAllByName("www.microsoft.com");
for (int i = 0; i < addresses.length; i++)
{
System.out.println(addresses[i]);
}
}
catch (UnknownHostException e)
{
System.out.println("Could not find www.microsoft.com");
}
}
}
• In addition, there is a special type of socket that provides a service that will bind to a
specific port number. This type of socket is normally used only in servers and can
perform the following operations.
3.4.3 TCP and Client/Server Paradigm
• In network programming, (and often in other forms of communication, such as
database programming), applications that use sockets are divided into two categories,
the client and the server.
• You are probably familiar with the phrase client/server programming, although the
exact meaning of the phrase may be unclear to you. This paradigm is the subject of
the discussion below.
3.4.3.1 Client/Server Paradigm
• The client/server paradigm divides software into two categories, clients and servers.
• A client is software that initiates a connection and sends requests, whereas a server is
software that listens for connections and processes requests.
• In the context of UDP programming, no actual connection is established and UDP
applications may both initiate and receive requests on the same socket.
• In the context of TCP, where connections are established between machines, the
client/server paradigm is much more relevant.
3.4.4 TCP Sockets
• Java offers good support for TCP sockets, in the form of two socket classes,
java.net.Socket and java.net.ServerSocket. When writing client software that
connects to an existing service, the Socket class should be used. When writing server
software that binds to a local port in order to provide a service, the ServerSocket class
should be employed.
3.4.4.1 Socket Class
• The Socket class represents client sockets and is a communication channel between
two TCP communications ports belonging to one or two machines.
• A socket may connect to a port on the local system, avoiding the need for a second
machine, but most network software will usually involve two machines.
• TCP sockets cannot communicate with more than two machines. If this functionality
is required, a client application should establish multiple socket connections, one for
each machine.
• Constructors: The constructor for the java.net.Socket class is,
Socket (String ipaddress, int portno)
• The easiest way to create a socket is to specify the hostname of the machine and the
port of the service.
Advanced Java [BBA (CA) : Sem. VI] 3.17 Networking
• For example, to connect to a Web server on port 80, the following code might be used:
try
{
// Connect to the specified host and port
Socket mySocket = new Socket ("www.awl.com", 80);
// ......
}
catch (Exception e)
{
System.err.println ("Err – " + e);
}
• However, a wide range of constructors is available, for different situations. Unless
otherwise specified, all constructors are public.
1. Protected Socket(): Creates an unconnected socket using the default
implementation provided by the current socket factory. Developers should not
normally use this method, as it does not allow a hostname or port to be specified.
2. Socket(InetAddress address int port) throws java.io.IO-Exception,
java.lang.SecurityException: Creates a socket connected to the specified IP
address and port. If a connection cannot be established, or if connecting to that
host violates a security restriction (such as when an applet tries to connect to a
machine other than the machine from which it was loaded), an exception is
thrown.
3. Socket(InetAddress address, int port, InetAddress local-Address int
localPort) throws ava.io.IOException, java.-lang.SecurityException:
Creates a socket connected to the specified address and port and is bound to the
specified local address and local port. By default, a free port is used, but this
method allows you to specify a specific port number, as well as a specific address,
in the case of multihomed hosts (i.e., a machine where the localhost is known by
two or more IP addresses).
4. Protected Socket(SocketImpl implementation): Creates an unconnected socket
using the specified socket implementation. Developers should not normally use
this method, as it does not allow a hostname or port to be specified.
5. Socket(String host, int port) throws java.net.UnknownHost-Exception,
java.io.IOException, java.lang.SecurityException: Creates a socket
connected to the specified host and port. This method allows a string to be
specified, rather than an InetAddress. If the hostname could not be resolved, a
connection could not be established, or a security restriction is violated, an
exception is thrown.
Advanced Java [BBA (CA) : Sem. VI] 3.18 Networking
• For example, a mail server that provides access to stored messages would listen to
commands and send back message contents.
• A TELNET server would listen for keystrokes and pass these to a log-in shell and send
back output to the network client. Protocol-specific actions are less network and more
programming-oriented.
• The following snippet shows how client sockets are accepted and how I/O streams
may be connected to the client:
// Perform a blocking read operation, to read the next socket
// connection
Socket nextSocket = someServerSocket.accept();
// Connect a filter reader and writer to the stream
BufferedReader reader = new BufferedReader (new InputStreamReader
(nextSocket.getInputStream()));
PrintWriter writer = new PrintWriter
(new OutputStreamWriter(nextSocket.getOutputStream()));
• From then on the server may conduct the tasks needed to process and respond to
client requests, or may choose to leave this task for code executing in another thread.
• Remember that just like any other form of I/O operation in Java, code will block
indefinitely while reading a response from a client, so to service multiple clients
concurrently, threads must be used.
• In simple cases, however, multiple threads of execution may not be necessary,
particularly if requests are responded to quickly and take little time to process.
• Creating fully-fledged client/server applications that implement popular Internet
protocols involves a fair amount of effort, especially for those new to network
programming.
• It also draws on other skills, such as multi-threaded programming, discussed in the
next chapter. For now, we will focus on a simple, bare-bones TCP server that executes
as a single-threaded application.
3.4.7 Creating a TCP Server
• One of the most enjoyable parts of networking is writing a network server.
• Clients send requests and respond to data sent back, but the server performs most of
the real work.
Program 3.6: Program for DaytimeServer.
import java.net.*;
import java.io.*;
public class DaytimeServer
{
public static final int SERVICE_PORT = 13;
Advanced Java [BBA (CA) : Sem. VI] 3.25 Networking
• UDP sockets can receive data from more than one host machine. If several machines
must be communicated with, then UDP may be more convenient than other
mechanisms such as TCP.
• Some network protocols specify UDP as the transport mechanism, requiring its use.
Java supports the User Datagram Protocol in the form of two classes:
java.net.DatagramPacket
java.net.DatagramSocket
3.5.1 DatagramPacket Class
• The DatagramPacket class represents a data packet intended for transmission using
the User Datagram Protocol (see Fig. 3.4).
• Packets are containers for a small sequence of bytes and include addressing
information such as an IP address and a port.
Datagram Packet
IP address (java,net,InetAddress)
Packet data
• Methods:
1. void close(): Closes a socket and unbinds it from the local port.
2. void connect(InetAddress remote_addr int remote_port): Restricts access to
the specified remote address and port. The designation is a misnomer, as UDP
does not actually create a "connection" between one machine and another.
However, if this method is used, it causes exceptions to be thrown if an attempt is
made to send packets to, or read packets from, any other host and port than
those specified.
3. void disconnect(): Disconnects the DatagramSocket and removes any
restrictions imposed on it by an earlier connect operation.
4. InetAddress getInetAddress(): Returns the remote address to which the socket
is connected, or null if no such connection exists.
5. int getPort(): Returns the remote port to which the socket is connected, or –1 if
no such connection exists.
6. InetAddress getLocalAddress(): Returns the local address to which the socket
is bound.
7. int getLocalPort(): Returns the local port to which the socket is bound.
8. int getReceiveBufferSize() throws java.net.SocketException: Returns the
maximum buffer size used for incoming UDP packets.
9. int getSendBufferSize() throws java.net.SocketException: Returns the
maximum buffer size used for outgoing UDP packets.
10. int getSoTimeout() throws java.net.SocketException: Returns the value of
the timeout socket option. This value is used to determine the number of
milliseconds a read operation will block before throwing a
java.io.InterruptedIOException. By default, this value will be zero, indicating that
blocking I/O will be used.
11. void receive(DatagramPacket packet) throws java.io.IO-Exception: Reads a
UDP packet and stores the contents in the specified packet. The address and port
fields of the packet will be overwritten with the sender address and port fields
and the length field of the packet will contain the length of the original packet,
which can be less than the size of the packet's byte-array. If a timeout value has
not been specified by using DatagramSocket.setSoTimeout(int duration), this
method will block indefinitely. If a timeout value has been specified, a
java.io.InterruptedIOException will be thrown if the time is exceeded.
12. void send(DatagramPacket packet) throws java.io.IOException: Sends a UDP
packet, represented by the specified packet parameter.
13. void setReceiveBufferSize(int length) throws java.net. Soc-
ketException: Sets the maximum buffer size used for incoming UDP packets.
Whether the specified length will be adhered to is dependent on the operating
system.
Advanced Java [BBA (CA) : Sem. VI] 3.32 Networking
IP address
Packet data
Fig. 3.5: Reading from a UDP packet is simplified by applying input streams
Advanced Java [BBA (CA) : Sem. VI] 3.33 Networking
Datagram Packet
while !finished
{
// Write data to packet buffer
.........
socket.send (packet);
// Do something else, like read other packets, or check to
// see if no more packets to send
.........
}
socket.close();
3.5.7.2 Example of User Datagram Protocol
• To demonstrate how UDP packets are sent and received, we will compile and run two
small examples.
• The first will bind to a local port, read a packet and display its contents and
addressing information. The second example will send the packet read by the first.
Program 3.8: Program for PacketReceiveDemo.
import java.net.*;
import java.io.*;
public class PacketReceiveDemo
{
public static void main (String args[])
{
try
{
System.out.println ("Binding to local port 2000");
// Create a datagram socket, bound to the
// specific port 2000
DatagramSocket socket = new DatagramSocket(2000);
System.out.println ("Bound to local port " + socket.getLocalPort());
// Create a datagram packet, containing a
// maximum buffer of 256 bytes
DatagramPacket packet = new DatagramPacket( new byte[256], 256 );
• In a second window, you then need to run the sender. This application could be run
from any computer on a local network or the Internet (providing there isn't a firewall
between the two hosts).
• If you'd like, you can also run it from the same machine. It takes a single parameter,
the hostname of the remote machine:
java PacketSendDemo myhostname
• For example,
try {
URL u = new URL("http://www.VIT.edu/schedule/timeTable.html");
System.out.println("The protocol is " + u.getProtocol());
System.out.println("The host is " + u.getHost());
System.out.println("The port is " + u.getPort());
System.out.println("The file is " + u.getFile());
System.out.println("The anchor is " + u.getRef());
}
catch (MalformedURLException ex) {
}
• If a port is not explicitly specified in the URL, it's set to -1. This does not mean that the
connection is attempted on port -1 (which does not exist) but rather that the default
port is to be used.
• If the ref does not exist, it's just null, so watch out for Null PointerExceptions.
3.6.2 URLConnection
• URLConnection is the general purpose class for accessing the attributes of a remote
resource.
• The abstract class URLConnection is the superclass of all classes that represent a
communications link between the application and a URL.
• Instances of this class can be used both to read from and to write to the resource
referenced by the URL.
• After you have successfully created a URL object, you can call the URL object's
openConnection method to get URLConnection Object.
• For example, the following code opens a connection to the site pragati.com:
try {
URL myURL = new URL("http://pragati.com");
URLConnection myURLConnection = myURL.openConnection();
myURLConnection.connect();
} catch (MalformedURLException e) { // new URL() failed
……………..
} catch (IOException e) { // openConnection() failed
……………..
}
• A new URLConnection object is created every time by calling the OpenConnection
method of the protocol handler for this URL.
• You are not always required to explicitly call the connect method to initiate the
connection. Now that you have successfully connected to your URL, you can use the
URLConnection object to perform actions such as reading from or writing to the
connection.
Advanced Java [BBA (CA) : Sem. VI] 3.44 Networking
8. Which method of URL class represents a URL and it has complete set of methods
to manipulate URL in Java?
(a) java.net.URL (b) java.net.URLConnection
(c) Both (a) and (b) (d) None of the above
9. Which of these class is used to encapsulate IP address and DNS?
(a) DatagramPacket (b) URL
(c) InetAddress (d) ContentHandler
10. In the socket programming, for an IP address, which can be used to find the host
name and IP address of a client/ server?
(a) The ServerSocket class (b) The Socket class
(c) The InetAddress class (d) The Connection interface
Answers
1. (c) 2. (c) 3. (d) 4. (b) 5. (c) 6. (a) 7. (a) 8. (a) 9. (c) 10. (c)
Practice Questions
Q.I Answer the following questions in short:
1. What is Networking?
2. What are the advantages of networking?
3. What is Protocol? List out at least two protocols.
4. What is Internet?
5. Define the following terms:
6. Explain use of Socket class.
7. What is the difference between TCP/IP and UDP?
8. Explain the use of ServerSocket class.
9. Explain the use of DatagramSocket class.
10. Define protocol list difference between TCP and UDP.
11. What is Internet Addressing? Give the purpose of InetAddress class?
12. Describe the use of following:
(i) Reserved sockets
(ii) DNS (Domain Naming Service)
13. Explain the use of following methods of DatagramPacket class with example:
(i) getPort()
(ii) getData()
14. What is proxy server? Give the purpose of proxy server.
Q.II Answer the following questions:
1. Explain with suitable diagram the HTTP communication between Web server and
web client.
2. What is Client Server Model?
3. Write short note on URL Programming.
4. Explain TCP/IP client sockets with suitable example.
5. Explain TCP/IP server sockets with suitable example.
6. Explain UDP Server sockets with suitable example.
Advanced Java [BBA (CA) : Sem. VI] 3.48 Networking
• When a user issues a request for a URL that corresponds to a java servlets, the server
hands the request off to the Servlet (program on server side) for processing.
• The Servlet dynamically produces a response to the request, typically an HTML web
page and sends it back to the requesting web browser.
• Servlets provide a component-based, platform-independent method for building web
based applications. Servlets provides an object-oriented and extensible middle tier for
Web server based applications.
• Web servers generally cannot talk to databases – a web server alone cannot create web
page content using data held in database.
• This information cannot make accessible to public through the web server. Here,
Servlets helps to extend the functionality of a web server.
• A dynamic page could be anything like a page that randomly chooses picture to
display or even a page that displays the current time.
request
communicate
Web
Browser Servlet
Is No
servlet
loaded
Yes
Is
servlet No
Load servlet
current
Yes
Process request
Send response
javax.servlet.GenericServlet
javax.servlet.http.HttpServlet
Userde!nePackage.UserDe!neServlet
Fig. 4.3
• The root interface of the servlet class is Servlet interface hierarchy. All Servlets need
to either directly or indirectly implement the Servlet interface.
• The GenericServlet class of the Servlet API implements the Servlet interface. In
addition to the Servlet interface, the GenericServlet class implements the
ServletConfig interface of the Servlet API and the Serializable interface of the
standard java.io.package.
• The object of the ServletConfig interface is used by the Web container to pass the
configuration information to a servlet when a Servlet is initialized.
• To develop a servlet that communicates using HTTP, we need to extend the
HttpServlet class in our servlet. The HttpServlet class extends the GenericServlet class
and provides built-in HTTP functionality.
• javax.servlet.Servlet Interface contains following methods:
1. public void destroy()
2. public ServletConfig getServletConfig()
3. public String getServletInfo()
4. public String getServletInfo()
• javax.servlet.ServletConfig Interface contains following methods:
1. public String getInitParameter(String param)
2. public Enumeration getInitParameterNames()
3. public ServletContext getServletContext()
Advanced Java [BBA (CA) : Sem. VI] 4.5 Servlet and JSP
GenericServlets HTTServlets
Fig. 4.4
1. Generic Servlets: It extends javax.servlet.GenericServlet. Generic Servlets are
protocol independent. They contain no inherent HTTP support or any other
transport protocol.
2. HTTP Servlets: It extends javax.servlet.HttpServlet. They have built-in HTTP
protocol support and are more useful in a Sun Java System Web Server
environment.
• For both Servlet types, you implement the constructor method init() and the
destructor method destroy() to initialize or deallocate resources.
• All Servlets must implement a service() method, which is responsible for handling
Servlet requests.
• For generic Servlets, simply override the service method to provide routines for
handling requests.
• HTTP Servlets provide a service method that automatically routes the request to
another method in the Servlet based on which HTTP transfer method is used.
• So, for HTTP servlets, override doPost() to process POST requests, doGet() to process
GET requests, and so on.
1. Generic Servlets:
GenericServlet Class:
o GenericServlet is an abstract class that provides implementation of most of the
basic servlet methods.
Methods of GenericServlet Class:
o public void init(ServletConfig)
o public abstract void service(ServletRequest request, ServletResposne
response)
o public void destroy()
o public ServletConfig getServletConfig()
o public String getServletInfo()
Advanced Java [BBA (CA) : Sem. VI] 4.6 Servlet and JSP
<Interface> <Interface>
HttpServlet
HttpServIetRequest HttpServIetResponse
getHeader(name) service() setHeader()
getHeadersNames() doGet() setDateHeader()
getIntHeader() doPost() setlntHeader()
getDateHeader()
Note:
MyServlet
extends implements class
Fig. 4.5
Advanced Java [BBA (CA) : Sem. VI] 4.7 Servlet and JSP
o The servlet container loads the servlet before invoking the service() method.
o Then the servlet container handles multiple requests by spawning multiple
threads, each thread executing the service() method of a single instance of the
servlet.
Loading and
Start Instantiation
init()
destroy()
End of
Life End
Cycle
Interfaces Classes
Servlet ServletInputStream
ServletContext ServletOutputStream
ServletConfig ServletRequestWrapper
ServletRequest ServletResponseWrapper
ServletResponse ServletRequestEvent
ServletContextListener ServletContextEvent
RequestDispatcher ServletRequestAttributeEvent
SingleThreadModel ServletContextAttributeEvent
Filter ServletException
FilterConfig UnavailableException
FilterChain GenericServlet
Classes and Interface of javax.servlet.http:
Classes Interfaces
HttpServlet HttpServletRequest
HttpServletResponse HttpSessionAttributeListener
HttpSession HttpSessionListener
Cookie HttpSessionEvent
Step 3 : Go to 'http://localhost:8080'. You should see the below page. It means you
successfully installed Tomcat Server. You should start the server before
opening the webpage.
Step 4 : Go to Tomcat/conf/tomcat-users.xml
Add Usernames, Passwords and Roles required. Without configuring these
Usernames, You will be able to access Server Status, Manager App and Host
Manager options on the Tomcat Home Page.
Advanced Java [BBA (CA) : Sem. VI] 4.12 Servlet and JSP
o <role rolename="manager-gui"/>
o <user username="admin" password="admin" roles="manager-gui"/>
o <role rolename="admin-gui"/>
o <user username="tomcat" password="tomcat" roles="admin-gui"/>
Sample Code for Hello World:
• Following is the sample source code structure of a Servlet example to write Hello
World:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloWorld extends HttpServlet
{
private String message;
public void init() throws ServletException
{
// Do required initialization
message = "Hello World 2022...";
}
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}
public void destroy()
{
// do nothing.
}
}
Compiling the Servlet:
• We will begin by building and testing a simple servlet. The basic steps are the
following:
1. Create and compile the servlet source code. Then, copy the servlet’s class file to
the proper directory, and add the servlet’s name and mappings to the proper
web.xml file.
2. Start Tomcat.
3. Start a web browser and request the servlet.
Advanced Java [BBA (CA) : Sem. VI] 4.13 Servlet and JSP
• Let us save the code in Helloservlet.java file and put this file in /root/apache-tomcat-
5.5.25/webapps/servlets-examples/WEB-INF/classes
• Assuming the environment is setup properly, go in ServletDemo directory and
compile Helloservlet.java.
• If the Servlet depends on any other libraries, we have to include those JAR files on our
CLASSPATH as well. We have included only servlet-api.jar JAR file because we are not
using any other library in Helloservlet program.
• This command line uses the built-in javac compiler that comes with the Sun
Microsystems Java Software Development Kit (JDK). For this command to work
properly, we have to include the location of the Java SDK that we are using in the
PATH environment variable.
• If everything goes fine, above compilation would produce Helloservlet.class file in the
same directory. Next section would explain how a compiled servlet would be deployed
in production.
Servlet Deployment:
• Create following entries in web.xml file located in /root/apache-tomcat-
5.5.25/webapps/servlets-examples/web.xml.
<servlet>
<servlet-name> Helloservlet </servlet-name>
<servlet-class> Helloservlet </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> Helloservlet </servlet-name>
<url-pattern>/servlet/Helloservlet </url-pattern>
</servlet-mapping>
• Above entries to be created inside <web-app>...</web-app> tags available in web.xml
file. There could be various entries in this table already available, but never mind.
• We are almost done, now let us start tomcat server using:
[root@localhost bin]# sh startup.sh
Using CATALINA_BASE: /root/apache-tomcat-5.5.25/
Using CATALINA_HOME: /root/apache-tomcat-5.5.25/
Using CATALINA_TMPDIR: /root/apache-tomcat-5.5.25//temp
Using JRE_HOME: /root/jdk1.5.0_05/
[root@localhost bin]# sh shutdown.sh
Using CATALINA_BASE: /root/apache-tomcat-5.5.25/
Using CATALINA_HOME: /root/apache-tomcat-5.5.25/
Using CATALINA_TMPDIR: /root/apache-tomcat-5.5.25//temp
Using JRE_HOME: /root/jdk1.5.0_05/
Advanced Java [BBA (CA) : Sem. VI] 4.14 Servlet and JSP
• A number of Web servers that support Servlets are available in the market. Some web
servers are freely downloadable and Tomcat is one of them.
• Apache Tomcat is an open source software implementation of the Java Servlet and
JavaServer Pages technologies and can act as a standalone server for testing servlets
and can be integrated with the Apache Web Server.
HTTP Response
Client
Server
Fig. 4.7: HTML Page to the Client, using HTTP
• Fig. 4.8 diagram shows the position of Servelts in a Web Application.
HTTP Methods:
• HTTP request can be made using a variety of methods, but most often used are GET
and POST.
• The method name tells the server the kind of request that is being made, and how the
rest of the message will be formatted.
Advanced Java [BBA (CA) : Sem. VI] 4.15 Servlet and JSP
HTTP
server
HTTP
protocol
Database
2. Post Method:
• A generally more reliable method of passing information to a backend program is the
POST method.
• This packages the information in exactly the same way as GET methods, but instead
of sending it as a text string after a ? in the URL it sends it as a separate message.
• This message comes to the backend program in the form of the standard input which
you can parse and use for your processing. Servlet handles this type of requests using
doPost() method.
• The syntax of doPost is as given below:
public void doPost (HttpServlet-Request req, HttpServletResponse resp)
throws ServletException, IOException
{ ....................................... }
Program 4.1: Program to use of doGet and display Hello Computer Servlet.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Hello1 extends HttpServlet
{
public void doGet(HttpServletRequest req,
HttpServletResponse resp) throws ServletException,IOException
{
PrintWriter out;
//set the content type
resp.setContentType("text/html");
out = resp.getWriter();
out.println("<HTML><HEAD><TITLE>");
out.println("Hellow World Servlet");
out.println("</TITLE></HEAD><BODY>");
out.println("<H1>Go Corona</H1>");
out.println("<BODY></HTML>");
out.close();
}
}
Output:
Advanced Java [BBA (CA) : Sem. VI] 4.17 Servlet and JSP
1. In case of Get request, only limited In case of post request, large amount
amount of data can be sent because of data can be sent because data is
data is sent in header. sent in body.
2. Get request is not secured because Post request is secured because data is
data is exposed in URL bar. not exposed in URL bar.
5. Get request is more efficient and used Post request is less efficient and used
more than Post. less than Get.
Interface Description
• Here is a simple URL which will pass two values to HelloForm program using GET
method.
http://localhost:8080/servlets-examples/servlet
/HelloForm?first_name=Arina&last_name=Willams
• Below is HelloForm.java servlet program to handle input given by web browser. We
are going to use getParameter() method which makes it very easy to access passed
information:
// Import required java libraries
import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
// ExtendHttpServlet class
Advanced Java [BBA (CA) : Sem. VI] 4.22 Servlet and JSP
• Try to enter First Name and Last Name and then click submit button to see the result
on your local machine where tomcat is running. Based on the input provided, it will
generate similar result as mentioned in the above example.
2. POST Method Example Using Form:
• Let us do little modification in the above servlet, so that it can handle GET as well as
POST methods. Below is HelloForm.java servlet program to handle input given by web
browser using GET or POST methods.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloForm1 extends HttpServlet
{
// Method to handle post method request.
public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Using Post Method to Read Form Data";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType + "<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
Advanced Java [BBA (CA) : Sem. VI] 4.24 Servlet and JSP
• Below is CheckBox.java Servlet program to handle input given by web browser for
checkbox button.
// Import required java libraries
import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
// ExtendHttpServlet class
public class CheckBoxTest extends HttpServlet
{
// Method to handle GET method request.
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Advanced Java [BBA (CA) : Sem. VI] 4.26 Servlet and JSP
• We can try above servlet to read any other form's data which is having other objects
like text box, radio button or drop down box etc.
• Following is the generic example which uses getParameterNames() method of
HttpServletRequest to read all the available form parameters. This method returns an
Enumeration that contains the parameter names in an unspecified order.
• Once, we have an Enumeration, we can loop down the Enumeration in the standard
manner, using hasMoreElements() method to determine when to stop and using
nextElement() method to get each parameter name.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
// Extend HttpServlet class
Advanced Java [BBA (CA) : Sem. VI] 4.28 Servlet and JSP
{
// Read multiple valued data
out.println("<ul>");
for(int i=0; i < paramValues.length; i++)
{
out.println("<li>" + paramValues[i]);
}
out.println("</ul>");
}
}
out.println("</tr>\n</table>\n</body></html>");
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException
{
doGet(request, response);
}
}
Output:
Web container
Request Session
Client 1
id=123 id=123
Servlet
Session
Request
id=134
Client 2 id=134
else
{
String[] items = getItemsFromCart(name);
}
• The biggest advantage of using user authorization to perform session tracking is that
it's easy to implement.
• Simply tell the server to protect a set of pages, and use getRemoteUser() to identify
each client. Another advantage is that the technique works even when the user
accesses the site from different machines. It also works even if the user strays from
your site or exits her browser before coming back.
• The biggest disadvantage of user authorization is that it requires each user to register
for an account and then log in each time she starts visiting your site.
• Most users will tolerate registering and logging in as a necessary evil when they are
accessing sensitive information, but it's overkill for simple session tracking. We
clearly need a better approach to support anonymous session tracking.
• Another small problem with user authorization is that a user cannot simultaneously
maintain more than one session at the same site.
4.7.2.2 URL Rewriting
• URL rewriting is another way to support anonymous session tracking. With URL
rewriting, every local URL the user might click on is dynamically modified or
rewritten, to include extra information.
• The extra information can be in the form of extra path information, added
parameters or some custom, server-specific URL change.
• Due to the limited space available in rewriting a URL, the extra information is usually
limited to a unique session ID.
• With URL rewriting, we append a token or identifier to the URL of the next Servlet or
the next resource.
• We can send parameter name/value pairs using the following format:
url?name1=value1&name2=value2&…
• A name and a value is separated using an equal sign (=) a parameter name/value pair
is separated from another parameter name/value pair using the ampersand (&).
• When the user clicks the hyperlink, the parameter name/value pairs will be passed to
the server.
• From a Servlet, you can use the HttpServletRequest interface's getParameter method
to obtain a parameter value.
• For instance, to obtain the value of the second parameter, we write the
following:
request.getParameter(name2);
Advanced Java [BBA (CA) : Sem. VI] 4.33 Servlet and JSP
• The use of URL rewriting is easy and simple. When using this technique, however, we
need to consider several things:
1. The number of characters that can be passed in a URL is limited. Typically, a
browser can pass up to 2,000 characters.
2. The value that we pass can be seen in the URL. Sometimes, this is not desirable.
For example, some people prefer their password not to appear on the URL.
3. We need to encode certain characters, such as & and ? characters and white
spaces, that you append to a URL.
URL Rewriting for Session Management:
• If the client has disabled cookie in the browser then session management using
cookie won’t work. In that case URL rewriting can be used as a backup.
• In URL rewriting, a token (parameter) is added at the end of the URL. The token
consist of name/value pair separated by an equal (=) sign.
• Fig. 4.11 shows an example of URL rewriting.
Parameter Parameter
name value
• In short, in Hidden Form Field a hidden (invisible) textfield is used for maintaining
the state of a user.
• In such case, we store the information in the hidden field and get it from another
Servlet. This approach is better if we have to submit form in all the pages and we don't
want to depend on the browser.
• Let's see the code to store value in hidden field.
<input type="hidden" name="uname" value="Vimal Joshi">
Here, uname is the hidden field name and Vimal Joshi is the hidden field value.
• In Fig. 4.12 we are storing the name of the user in a hidden textfield and getting that
value from another Servlet.
Name: Servlet1 Servlet2
go
Welcome, User
Hello, User
An invisible values
This site under
textfield construction
go
out.println("<HEAD>");
out.println("<TITLE>Cookie Test</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("Please click the button to see the cookies sent to you.");
out.println("<BR>");
out.println("<FORM METHOD=POST>");
out.println("<INPUT TYPE=SUBMIT VALUE=Submit>");
out.println("</FORM>");
out.println("</BODY>");
out.println("</HTML>");
• The form does not have any element other than a submit button. When the form is
submitted, the doPost method is invoked.
• To retrieve cookies, you use the getCookies method of the HttpServletRequest
interface. This method returns a Cookie array containing all cookies in the request. It
is your responsibility to loop through the array to get the cookie you want, as follows:
Cookie[] cookies = request.getCookies();
int length = cookies.length;
for (int i=0; i<length; i++)
{
Cookie cookie = cookies[i];
out.println("<B>Cookie Name:</B> " +cookie.getName() + "<BR>");
out.println("<B>Cookie Value:</B> " +cookie.getValue() + "<BR>");
}
Program 4.2: Program to sending and receiving cookies.
importjavax.servlet.*;
importjavax.servlet.http.*;
import java.io.*;
importjava.util.*;
public class CookieServlet extends HttpServlet
{
/*Process the HTTP Get request*/
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
Cookie c1 = new Cookie("userName", "tanmay");
Cookie c2 = new Cookie("password", "rashmi");
Advanced Java [BBA (CA) : Sem. VI] 4.37 Servlet and JSP
response.addCookie(c1);
response.addCookie(c2);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Cookie Test</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("Please click the button to see the cookies sent to
you.");
out.println("<BR>");
out.println("<FORM METHOD=POST>");
out.println("<INPUT TYPE=SUBMIT VALUE=Submit>");
out.println("</FORM>");
out.println("</BODY>");
out.println("</HTML>");
}
/**Process the HTTP Post request*/
public void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException,IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Cookie Test</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("<BR><BR><H2> Here are ALL the Cookies.</H2>");
Cookie[] cookies = request.getCookies();
int length = cookies.length;
for (int i=0; i<length; i++)
{
Cookie cookie = cookies[i];
out.println("<B>Cookie Name:</B>" + cookie.getName() + "<BR>");
out.println("<B>Cookie Value:</B>" + cookie.getValue() + "<BR>");
}
out.println("</BODY>");
out.println("</HTML>");
}
}
Advanced Java [BBA (CA) : Sem. VI] 4.38 Servlet and JSP
Output:
Advantages of Cookies:
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantages of Cookies:
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
Persisting Cookies:
• The cookies we created in the previous last as long as the browser is open. When the
browser is closed, the cookies are deleted.
• We can choose to persist cookies so that they last longer.
• The javax.servlet.http.Cookie class has the setMaxAge method that sets the maximum
age of the cookie in seconds.
4.7.2.5 HttpSession
• The HttpSession object is used to store entire session with a specific client. We can
store, retrieve and remove attribute from HttpSession object.
• Any servlet can have access to HttpSession object throughout the getSession() method
of the HttpServletRequest object.
• An object of HttpSession can be used to perform two tasks:
1. Bind objects.
2. View and manipulate information about a session, such as the session identifier,
creation time, and last accessed time.
Advanced Java [BBA (CA) : Sem. VI] 4.39 Servlet and JSP
Container
2.1)request 2.2)creates unique
session id
session id
ID# 101
"Amar"
<url-pattern>/servlet/Validate</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Welcome</servlet-name>
<url-pattern>/servlet/Welcome</url-pattern>
</servlet-mapping>
Validate.java
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");
String name = request.getParameter("user");
String pass = request.getParameter("pass");
if(pass.equals("1234"))
{
//creating a session
HttpSession session = request.getSession();
session.setAttribute("user", name);
response.sendRedirect("Welcome");
}
}
}
Welcome.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Welcome extends HttpServlet
{
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
Advanced Java [BBA (CA) : Sem. VI] 4.42 Servlet and JSP
To create table:
catch(SQLException se)
{
//Handle errors for JDBC
se.printStackTrace();
}
catch(Exception e)
{
//Handle errors for Class.forName
e.printStackTrace();
}
finally
{
//finally block used to close resources
try
{
if(stmt!=null)
stmt.close();
}
catch(SQLException se2)
{
}// nothing we can do
try
{
if(conn!=null)
conn.close();
}
catch(SQLException se)
{
se.printStackTrace();
}//end finally try
} //end try
}
}
• Now let us compile above servlet and create following entries in web.xml
....
<servlet>
<servlet-name>DatabaseAccess</servlet-name>
<servlet-class>DatabaseAccess</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DatabaseAccess</servlet-name>
<url-pattern>/servlet/DatabaseAccess</url-pattern>
</servlet-mapping>
....
Advanced Java [BBA (CA) : Sem. VI] 4.47 Servlet and JSP
3. JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also
has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP
etc.
4. JSP pages can be used in combination with servlets that handle the business logic,
the model supported by Java servlet template engines.
Comparison between JSP and Servlet:
Terms JSP Servlet
What are they? JSP is a webpage scripting Servlets are Java programs
language, generally used to that are already compiled
create the dynamic web and which also create
content. dynamic web content.
Typically JSP is typically more Servlet is more oriented
oriented towards towards processing
displaying information. information.
Role in MVC (Model View JSP acts as a viewer. Servlet acts as a controller.
Controller)
Applicable at the time of They are generally They are generally
preferred when there is not preferred when there is
much processing of data more processing and
required. manipulation involved.
Running speed JSP runs slower as Servlets run faster as
compared to a Servlet. JSP compared to JSP.
compiles into Java Servlets.
Code complications The code programming is The code programming is
easy as compared to that of difficult as compared to
Servlets. that of JSP.
Facility Here, we can build custom No such facility is available
tags which can directly call in servlets.
Java beans.
Consists of JSP are Java HTML Servlet are full functional
representation mixed with Java codes.
JAVA scriptlets.
Consistence of objects JSP has Implicit objects. Servlets does not have such
type of objects.
Examples To display a report. To process a user
submitted form.
Advanced Java [BBA (CA) : Sem. VI] 4.49 Servlet and JSP
Web
server
Mac OS
Internet
Database
Linux JSP
servlet Oracle
engine database
JSP files
stored here !
Windows 98
Fig. 4.16: JSP Architecture
• All the above mentioned steps can be shown below in the Fig. 4.17.
• Typically, the JSP engine checks to see whether a Servlet for a JSP file already exists
and whether the modification date on the JSP is older than the Servlet.
• If the JSP is older than its generated Servlet, the JSP container assumes that the JSP
hasn't changed and that the generated Servlet still matches the JSP's contents.
• This makes the process more efficient than with other scripting languages (such as
PHP) and therefore faster.
hello.jsp
Server with 2
JSP container
ad
Re Translation
phase
Client
1 GET/hello.jsp 3 Generate helloServlet.java
Fig. 4.17: Steps the Web Server creates Web Page using JSP
• So in a way, a JSP page is really just another way to write a servlet without having to
be a Java programming wiz. Except for the translation phase, a JSP page is handled
exactly like a regular Servlet.
4.9.3 Accessing Model of JSP
• JSP is a server side technology which helps to create a webpage dynamically using
java as the programming language.
• JSP is a specification from Sun Microsystems. It is an extension to Servlet API.
• The java server pages can be accessed in two different ways :
1. Access through a client request.
2. Access through a servlet request.
• Model 1: Architecture or Access through a Client Request: In this Model, JSP plays a
key role and it is responsible for of processing the request made by client. Client (Web
browser) makes a request; JSP then creates a bean object which then fulfills the
request and passes the response to JSP. JSP then sends the response back to client.
Unlike Model2 architecture in this Model, most of the processing is done by JSP itself.
Advanced Java [BBA (CA) : Sem. VI] 4.51 Servlet and JSP
1
Request
JSP
4
Response
Browser 2
3
Java Beam
1
Request (Controller)
Servlet
ins
Browser 3 tan 2
tia (Model)
te JavaBean
5 (View)
Response JSP 4
3. vs. Server-Side Includes (SSI): SSI is really only intended for simple inclusions,
not for "real" programs that use form data, make database connections, and the
like.
4. vs. JavaScript: JavaScript can generate HTML dynamically on the client but can
hardly interact with the web server to perform complex tasks like database access
and image processing etc.
5. vs. Static HTML: Regular HTML, of course, cannot contain dynamic information.
Initialization jsplnit()
request lifecycle
Request
Response
Shutdown jspDestroy()
2. JSP Initialization:
• When a container loads a JSP it invokes the jspInit() method before servicing any
requests.
• If you need to perform JSP-specific initialization, override the jspInit() method:
public void jspInit(){
// Initialization code...
}
• Typically initialization is performed only once and as with the servlet init method,
you generally initialize database connections, open files and create lookup tables in
the jspInit() method.
3. JSP Execution:
• This phase of the JSP life cycle represents all interactions with requests until the JSP is
destroyed.
• Whenever, a browser requests a JSP and the page has been loaded and initialized, the
JSP engine invokes the _jspService() method in the JSP.
• The _jspService() method takes an HttpServletRequest and an HttpServletResponse as
its parameters as follows:
void _jspService(HttpServletRequest request,
HttpServletResponse response)
{
// Service handling code...
}
• The _jspService() method of a JSP is invoked once per a request and is responsible for
generating the response for that request and this method is also responsible for
generating responses to all seven of the HTTP methods i.e. GET, POST, DELETE etc.
4. JSP Cleanup:
• The destruction phase of the JSP life cycle represents when a JSP is being removed
from use by a container.
• The jspDestroy() method is the JSP equivalent of the destroy method for servlets.
• Override jspDestroy() when you need to perform any cleanup, such as releasing
database connections or closing open files.
• There are total nine implicit objects available in JSP as given in following Table:
Sr.
Object Description
No.
1. request This is the HttpServletRequest object associated with the
request.
2. response This is the HttpServletResponse object associated with the
response to the client.
3. out This is the PrintWriter object used to send output to the client.
4. session This is the HttpSession object associated with the request.
5. application This is the ServletContext object associated with application
context.
6. config This is the ServletConfig object associated with the page.
7. pageContext This encapsulates use of server-specific features like higher
performance JspWriters.
8. page This is simply a synonym for this, and is used to call the
methods defined by the translated servlet class.
9. Exception The Exception object allows the exception data to be accessed
by designated JSP.
</head>
<body>
<%!
int sum(int num1, int num2, int num3){
return num1+num2+num3;
}
%>
<%= "Result is: " + sum(10,40,50) %>
</body>
</html>
Output:
4.13.2 Expressions
• Expression is used to insert values directly to the output. An expression tag places an
expression to be evaluated inside the java servlet class.
• A JSP expression element contains a scripting language expression that is evaluated,
converted to a String and inserted where the expression appears in the JSP file.
• Because the value of an expression is converted to a String, you can use an expression
within a line of text, whether or not it is tagged with HTML, in a JSP file.
• The expression element can contain any expression that is valid according to the Java
language specification but you cannot use a semicolon to end an expression.
• Following is the syntax of JSP Expression:
<%= expression %>
• You can write XML equivalent of the above syntax as follows:
<jsp:expression>
expression
</jsp:expression>
• Following is the simple example for JSP Expression:
<html>
<head><title>A Comment Test</title></head>
<body>
Advanced Java [BBA (CA) : Sem. VI] 4.58 Servlet and JSP
<p>
Today's date: <%=(new java.util.Date()).toLocaleString()%>
</p>
</body>
</html>
Output:
4.13.3 Scriptlets
• A scriptlet can contain any number of java language statements, variable or method
declarations, or expressions that are valid in the page scripting language.
• JSP Scriptlets begins with <% and ends %>. We can embed any amount of java code in
the JSP Scriptlets.
• Syntax for Scriptlet:
<% // any java source code here … %>
• A scriptlet is a fragment of Java code that is run when the user requests the page.
• For example, any Java if/for/while blocks opened in one scriptlet element must be
correctly closed in a later element for the page to successfully compile. Markup which
falls inside a split block of code is subject to that code, so markup inside an if block
will only appear in the output when the if condition evaluates to true; likewise,
markup inside a loop construct may appear multiple times in the output depending
upon how many times the loop body runs.
• The following would be a valid for loop in a JSP page:
<p>Counting to three:</p>
<% for(int i=1; i<4; i++){ %>
<p>This number is <%= i %> </p>
<% } %>
<p>OK</p>
• The output displayed in the user's web browser would be:
Counting to three:
This number is 1.
This number is 2.
This number is 3.
OK.
Advanced Java [BBA (CA) : Sem. VI] 4.59 Servlet and JSP
4.13.4 Comments
• JSP comment marks text or statements that the JSP container should ignore. A JSP
comment is useful when you want to hide or "comment out" part of your JSP page.
• Following is the syntax of JSP comments:
<%-- This is JSP comment … --%>
• Following is the simple example for JSP Comments:
<html>
<head><title>A Comment Test</title></head>
<body>
<h2>A Test of Comments</h2>
<%-- This comment will not be visible in the page source --%>
</body>
</html>
Output: A Test of Comments
• There are a small number of special constructs you can use in various cases to insert
comments or characters that would be treated specially. Here's a summary:
Syntax Purpose
<%-- comment --%> A JSP comment. Ignored by the JSP engine.
<!-- comment --> An HTML comment. Ignored by the browser.
<\% Represents static <% literal.
%\> Represents static %> literal.
\' A single quote in an attribute that uses single quotes.
\" A double quote in an attribute that uses double quotes.
<tr>
<td>Number</td>
<td><%= i+1 %></td>
</tr>
<%
}
%>
</table>
• We would have to supply an int variable "n" before it will work, and then it will
output a simple table with "n" rows.
• The important things to notice are how the %> and <% characters appear in the middle
of the "for" loop, to let you drop back into HTML and then to come back to the
Scriptlet.
• The concepts are simple here - as we can see, you can drop out of the scriptlets, write
normal HTML, and get back into the Scriptlet.
• Any control expressions such as a "while" or a "for" loop or an "if" expression will
control the HTML also. If the HTML is inside a loop, it will be emitted once for each
iteration of the loop.
• Another example of mixing Scriptlets and HTML is shown below - here it is assumed
that there is a Boolean variable named "hello" available. If we set it to true, you will
see one output, if we set it to false, we will see another output.
<%
if( hello ) {
%>
<p>Hello, world
<%
} else {
%>
<p>Goodbye, world
<%
}
%>
• It is little difficult to keep track of all open braces and scriptlet start and ends, but
with a little practice and some good formatting discipline, you will acquire
competence in doing it.
Advanced Java [BBA (CA) : Sem. VI] 4.63 Servlet and JSP
Output:
Emp ID First Name Last Name Age
100 sunil shetty 40
101 sara Khan 25
102 madhuri Dikshit 35
103 Akshay khanna 28
Insert command:
<%@ page import = "java.io.*,java.util.*,java.sql.*"%>
<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix = "c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix = "sql"%>
<html>
<head>
<title>JINSERT Operation</title>
</head>
<body>
<sql:setDataSource var = "snapshot" driver = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://localhost/TEST"
user = "root" password = "pass123"/>
<sql:update dataSource = "${snapshot}" var = "result">
INSERT INTO Employees VALUES (104, 32, 'saha', 'chopra');
</sql:update>
<sql:query dataSource = "${snapshot}" var = "result">
SELECT * from Employees;
</sql:query>
<table border = "1" width = "100%">
<tr>
<th>Emp ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<c:forEach var = "row" items = "${result.rows}">
<tr>
<td><c:out value = "${row.id}"/></td>
<td><c:out value = "${row.first}"/></td>
<td><c:out value = "${row.last}"/></td>
<td><c:out value = "${row.age}"/></td>
Advanced Java [BBA (CA) : Sem. VI] 4.65 Servlet and JSP
</tr>
</c:forEach>
</table>
</body>
</html>
Output:
Emp ID First Name Last Name Age
100 sunil shetty 40
101 sara Khan 25
102 madhuri Dikshit 35
103 Akshay khanna 28
104 saha chopra 32
ADDITIONAL PROGRAMS
Program 4.6: Program for displaying the message using Servlet.
// Firstservlet.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Firstservlet extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws IOException, ServletException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>MyServlet</title>");
out.println("</head>");
out.println("<body bgcolor=\"cyan\">");
out.println("<h1> My First Servlet Program...</h1>");
out.println("<h2>Welcome to Servlet World...");
out.println("</body>");
out.println("</html>");
}
}
Advanced Java [BBA (CA) : Sem. VI] 4.66 Servlet and JSP
Output:
out.println("<html>");
out.println("<head>");
out.println("<title>Date Progrom...</title>");
out.println("</head>");
out.println("<body bgcolor=\"cyan\">");
Date d = new Date();
out.println("<br><br><h1>Date = "+d+"</h1>");
out.println("</body>");
out.println("</html>");
}
}
Advanced Java [BBA (CA) : Sem. VI] 4.67 Servlet and JSP
Output:
Program 4.9: Program for displaying the sum of two numbers gets the inputs from user.
//Sum.html
<html>
<head>
<title>Addtion</title>
</head>
<body bgcolor = "cyan">
<form action = "http:
//localhost:8080/servlets-examples/servlet/AddNumServlet" method ="GET">
<br><br><br>
<h2> Sum of Numbers </h2>
Enter the Number 1 = <input type = "text" name = "n1"><br><br>
Enter the Number 2 = <input type = "text" name = "n2">
<br><br>
<input type = "submit" value = "Addition ">
<input type = "reset" value = "Cancel ">
</form>
</body>
</html>
// AddNumServlet.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddNumServlet extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws IOException, ServletException
{
int num1 = Integer.parseInt(req.getParameter("n1"));
int num2 = Integer.parseInt(req.getParameter("n2"));
int add = num1 + num2;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<html>");
out.println("<head>");
Advanced Java [BBA (CA) : Sem. VI] 4.69 Servlet and JSP
out.println("<title>Addition Progrom</title>");
out.println("</head>");
out.println("<body bgcolor=\"cyan\">");
out.println("<h2> Num1 = "+num1+"</h2>");
out.println("<h2> Num2 = "+num2+"</h2>");
out.println("<h2> Sum = "+add + "</h2>");
out.println("</body>");
out.println("</html>");
}
}
Output:
Program 4.10: Program to find the factorial of given number using Servlet program.
//fact.html
<html>
<head>
<title>Factorial</title>
</head>
Advanced Java [BBA (CA) : Sem. VI] 4.70 Servlet and JSP
Output:
Program 4.11: Program of add Cookie and get the information of Cookies.
//Addcookie.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class Addcookie extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
Cookie c1 = new Cookie("Cookie1","1");
res.addCookie(c1);
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
pw.println("Cookie added with value 1");
Cookie c2 = new Cookie("cookie2","2");
res.addCookie(c2);
pw.println("Cookie added with value 2");
Advanced Java [BBA (CA) : Sem. VI] 4.72 Servlet and JSP
Program 4.12: Program to display login successfully or not get the input from user and
check with respect to the admin table (use the PostgreSQL database).
//Login.html
<html>
<head>
<title>Login Form</title>
</head>
<body bgcolor = "pink">
<form action = "http://localhost:8080/
servlets-examples/servlet/Loginservlet" method ="GET">
<br><br><br>
<h2> Login Form</h2>
User Name = <input type = "text" name = "us"><br><br>
Password = <input type = "text" name = "pd">
<br><br>
<input type = "submit" value = "Login">
<input type = "reset" value = "Cancel ">
</form>
</body>
</html>
// Loginservlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Loginservlet extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws
IOException, ServletException
{
String uname = req.getParameter("us");
String pwd = req.getParameter("pd");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
try
{
out.println("<html>");
Advanced Java [BBA (CA) : Sem. VI] 4.74 Servlet and JSP
out.println("<body>");
Class.forName("postgresql.Driver");
out.println("<h1>Driver Loaded</h1>");
Connection c=DriverManager.getConnection
("jdbc:postgresql:mj","postgres","");
out.println("<br><h1>Connection Established</h1>");
Statement st=c.createStatement();
ResultSet rs=st.executeQuery("select * from admin");
while(rs.next())
{
if(uname.equals(rs.getString(1))&&pwd.equals(rs.getString(2)))
out.println("<h2>Login Successfully....</h2>");
else
out.println("<h3> NOT ! Try Again...</h3>");
}
}
catch(Exception e)
{
out.println("error"+e);
}
out.println("Successfully JDBC Done...");
out.println("</body>");
out.println("</html>");
}
}
Output:
Advanced Java [BBA (CA) : Sem. VI] 4.75 Servlet and JSP
{
HttpSession hs = req.getSession(true);
String uname = req.getParameter("us");
String pwd = req.getParameter("pd");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
if(uname.equals("tybcs")&&pwd.equals("tybcs123"))
{
out.println("<a href=
http://localhost:8080/servlets-examples/servlet/Sess.html> Login
Successfully </a>");
hs.setAttribute("LoginID",uname);
}
else
{
hs.setAttribute("LoginID",pwd);
}
}
}
Output:
Advanced Java [BBA (CA) : Sem. VI] 4.77 Servlet and JSP
Program 4.15: Program to displaying the information of Department which store in the
database (Servlet and PostgreSQL).
// Jdbcservlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Jdbcservlet extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws
IOException, ServletException
Advanced Java [BBA (CA) : Sem. VI] 4.79 Servlet and JSP
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
try
{
out.println("<html>");
out.println("<body>");
Class.forName("postgresql.Driver");
out.println("<h1>driver loaded</h1>");
Connection c=DriverManager.getConnection
("jdbc:postgresql:serv","postgres","");
out.println("<br><h1>connection created</h1>");
Statement st=c.createStatement();
ResultSet rs=st.executeQuery("select * from department");
while(rs.next())
{
out.println("<table border= 1>");
out.println("<tr>");
out.print("<td><h3>"+rs.getInt(1)+
"</td><td>"+rs.getString(2)+"</td></h3>");
out.println("</tr>");
out.println("</table>");
}
}
catch(Exception e)
{
out.println("error"+e);
}
out.println("Successfully JDBC Done...");
out.println("</body>");
out.println("</html>");
}
}
Advanced Java [BBA (CA) : Sem. VI] 4.80 Servlet and JSP
Output:
Program 4.18: Program to get the input from user and display the multiplication using
JSP.
//Mult.html
<html>
<body bgcolor="cyan">
<br>
<form action="http://localhost:8080/mult.jsp" method="GET">
<center>
<h2>Enter the First Number :<input type = text name ="t1">
<br>Enter the Second Number : <input type = text name= "t2">
<br>
<br>
<input type="Submit" value="Mult">
<input type="reset" value="Cancel">
</form>
</body>
</html>
//Mult.jsp
<%@ page language="java"%>
<html>
<body bgcolor="pink">
<%
int x = Integer.parseInt(request.getParameter("t1"));
int y = Integer.parseInt(request.getParameter("t2"));
Advanced Java [BBA (CA) : Sem. VI] 4.82 Servlet and JSP
int z = x * y;
out.println("Multiplication = "+z);
%>
</body>
</html>
Output:
<% }%>
<br>
<%
}
%>
</body>
</html>
Output:
while(no!=0)
{
rem=no%10;
no=no/10;
rev=rev*10+rem;
}
while(rev!=0)
{
n=rev%10;
rev=rev/10;
switch(n)
{
case 0:out.println("Zero");
break;
case 1:out.println("One");
break;
case 2:out.println("Two");
break;
case 3:out.println("Three");
break;
case 4:out.println("Four");
break;
case 5:out.println("Five");
break;
case 6:out.println("Six");
break;
case 7:out.println("Seven");
break;
case 8:out.println("Eight");
break;
case 9:out.println("Nine");
break;
}
}
}
Advanced Java [BBA (CA) : Sem. VI] 4.85 Servlet and JSP
catch(Exception e)
{
out.println("Please Enter No.");
}
%>
Output:
Program 4.21: Program to display the customer information like cust_no and cust_name
with store in the table customer using JSP (JSP and PostgreSQL).
<%@page language="java"
import="java.io.*"
import="java.sql.*"%>
<html>
<body>
<%!
Connection con;
Statement st;
ResultSet rs;
%>
<%
try
{
Class.forName("postgresql.Driver");
Advanced Java [BBA (CA) : Sem. VI] 4.86 Servlet and JSP
out.println("<h3>Driver Loaded</h3>");
con=DriverManager.getConnection
("jdbc:postgresql:TEST","postgres","");
out.println("<h3>Connection Created</h3>");
st=con.createStatement();
rs=st.executeQuery("select * from customer");
while(rs.next())
{
out.print("<h3>"+rs.getInt(1)
+" - "+rs.getString(2)+"</h3>");
out.println("<br>");
}
}
catch(Exception e)
{
out.println("error"+e);
}
%>
</body>
</html>
Output:
Advanced Java [BBA (CA) : Sem. VI] 4.87 Servlet and JSP
SUMMARY
• A Java Servlet is a server side program that services HTTP requests and returns the
result as HTTP responses.
• Servlet API consists of two important packages that encapsulate all the important
classes and interface, namely javax.servlet and javax.servlet.http.
• A Servlet is a java program that runs on web server. This program will start running
when there is request from client side. A servlet is loaded by the servlet container the
first time the Servlet is requested.
• There are two types of servlets: GenericServlet and HttpServlet. GenericServlet
defines the generic or protocol independent servlet. HttpServlet is subclass of
GenericServlet and provides some http specific functionality like doGet and doPost
methods.
• All Servlets must implement a service() method, which is responsible for handling
Servlet requests.
• For generic Servlets, simply override the service method to provide routines for
handling requests.
• HTTP Servlets provide a service method that automatically routes the request to
another method in the Servlet based on which HTTP transfer method is used. HTTP
servlets, override doPost() to process POST requests, doGet() to process GET requests,
• Servlet life cycle has three methods: init(), service() and destroy().
• HTTP request can be having two methods GET and POST.
• The GET method sends the encoded user information appended to the page request.
• A generally more reliable method of passing information to a backend program is the
POST method. This packages the information in exactly the same way as GET
methods, but instead of sending it as a text string after a ? in the URL it sends it as a
separate message.
• Servlets handles form data parsing automatically using the methods:
getParameter(), getParameterValues(), getParameterNames().
• There are following techniques used in session tracking:
1. User authorization.
2. Cookies.
3. Hidden Form Field.
4. URL Rewriting.
5. HttpSession.
• A cookie is a small piece of information that is passed back and forth in the HTTP
request and response.
• The HttpSession object is used to store entire session with a specific client. We can
store, retrieve and remove attribute from HttpSession object.
Advanced Java [BBA (CA) : Sem. VI] 4.88 Servlet and JSP
• JavaServer Pages (JSP) is a technology for developing web pages that support dynamic
content which helps developers insert java code in HTML pages by making use of
special JSP tags, most of which start with <% and end with %>.
• JSP life cycle has four phases: jspCompilation, jspInit, jspService, jspDestroy.
• The JSP page is built up using the following components: Directives, Declarations,
Scriptlets, Expressions, Standard Actions, Custom Tags.
Practice Questions
Q.I Answer the following questions in short:
1. What is Servlet? Explain the servlet types.
2. Differentiate between Get and Post.
3. Explain Generic Servlet and HttpServlet.
4. Explain session tracking.
5. Explain types of cookies.
6. Differentiate between Session and cookie.
7. Explain URL rewriting.
8. Explain hidden form field.
9. What is scriptlet in JSP?
Q.II Answer the following questions:
1. What is a servlet? Explain the lifecycle of servlet in detail.
2. Explain HTTPRequest and HTTPResponse.
3. Explain the lifecycle of JSP in detail.
4. Why is JSP fly compilation? Explain implicit object in JSP?
5. State the purpose of implicit objects. Explain any four implicit objects.
Q.III Define the Terms:
1. Servlet
2. Session
3. Cookies
4. scriptlet
5…
Spring and Hibernate
Learning Objectives …
Students will be able:
▣ To understand Basic Concept of Spring.
▣ To learn Spring Architecture and MVC.
▣ To study different Applications of Spring.
5.1 INTRODUCTION
• Spring is an open source framework created to address the complexity of enterprise
application development.
• Spring framework is an open source Java platform that provides comprehensive
infrastructure support for developing robust Java applications very easily and very
rapidly.
• Spring was initially written by Rod Johnson and was first released under the Apache
2.0 license in June 2003.
• Spring Framework is an open source framework that we use to develop Java
applications with very ease and with a rapid pace.
• Spring is a very lightweight framework which provides well-defined infrastructure
support for developing Java application.
• Hibernate is an open-source, non-invasive, light-weight java ORM(Object-Relational
Mapping) framework to develop objects which are independent of the database
software and make independent persistence logic in all JAVA, JEE.
• Hibernate is a framework which provides some abstraction layer, means the
programmer does not have to worry about the implementations, Hibernate does the
implementations for you internally like Establishing a connection with the database,
writing query to perform operations on the database.
(5.1)
Advanced Java [BBA (CA) : Sem. VI] 5.2 Spring and Hibernate
Business
Web Browser Application MyBatis
Spring MVC RDBMS
(Client) Spring Data JPA
Spring Framework
• Spring is modular, allowing us to pick and choose which modules are applicable to an
application, without having to bring in the rest.
• The core container consists of core, beans, context and expression language modules
that are fundamental to any Spring application.
• The core module is the core of the component model; it provides fundamental
features like dependency injection.
• The Bean module provides Bean Factory, which is a sophisticated implementation of
the factory pattern. The bean module is useful for the instantiation of the beans and
is used extensively by the Spring component framework.
• The context module is used on top of the core and bean modules for initializing the
context for the beans. The context module plays an important role in loading the
components defined and configured for the application.
• The Spring 3.0 introduces a new expression language – Spring Expression Language
(SpEL). It is a powerful expression language based on Java Server Pages (JSP)
Expression Language (EL). The EL module is used for dynamic querying of
components.
• The web container is built on top of the core container. The web and web servlet
modules that are part of the web container are useful for building the web
components for the enterprise applications using the spring framework. The web
module provides the basic features of a web application and the web servlet module
provides an implementation of the spring MVC architecture for web applications.
• The Web-Portlet module provides the MVC implementation to be used in a portlet
environment and mirrors the functionality of Web-Servlet module.
• Modules in the data layer help to provide data access from the web and business
components. The data layer container various modules is listed below:
o JDBC module: This module provides the JDBC abstraction layer and helps to avoid
tedious JDBC coding.
o ORM module: It provides integration for object relational mapping APIs such as
JPA, Hibernate, JDO, etc.
o JMS (Java Messaging Service) Module: It contains features for producing and
consuming messages.
o OXM module: This module provides Object/XML binding.
o Transaction Module: This model supports programmatic and declarative
transaction management for classes that implement special interfaces and for all
the POJOs.
Advanced Java [BBA (CA) : Sem. VI] 5.6 Spring and Hibernate
Spring Framework
JDBC ORM
WebSocket Servlet
OXM JMS
Web Portlet
Transactions
Core Container
Test
Fig. 5.3
Advanced Java [BBA (CA) : Sem. VI] 5.9 Spring and Hibernate
Then the project is created successfully, the following content in the Project
Explorer will be displayed as shown in Fig. 5.4.
Fig. 5.4
Step 2 : Let us add Spring Framework and common logging API libraries in our
project. To do this, right-click on the project name HelloSpringProject and
then follow the following option available in the context menu − Build Path
→ Configure Build Path to display the Java Build Path window as follows − as
shown in Fig. 5.5 to add Required Libraries.
Fig. 5.5
Advanced Java [BBA (CA) : Sem. VI] 5.10 Spring and Hibernate
Now use Add External JARs button available under the Libraries tab to add
the following core JARs from Spring Framework and Common Logging
installation directories:
o commons-logging-1.1.1
o spring-aop-4.1.6.RELEASE
o spring-aspects-4.1.6.RELEASE
o spring-beans-4.1.6.RELEASE
o spring-context-4.1.6.RELEASE
o spring-context-support-4.1.6.RELEASE
o spring-core-4.1.6.RELEASE
o spring-expression-4.1.6.RELEASE
o spring-instrument-4.1.6.RELEASE
o spring-instrument-tomcat-4.1.6.RELEASE
o spring-jdbc-4.1.6.RELEASE
o spring-jms-4.1.6.RELEASE
o spring-messaging-4.1.6.RELEASE
o spring-orm-4.1.6.RELEASE
o spring-oxm-4.1.6.RELEASE
o spring-test-4.1.6.RELEASE
o spring-tx-4.1.6.RELEASE
o spring-web-4.1.6.RELEASE
o spring-webmvc-4.1.6.RELEASE
o spring-webmvc-portlet-4.1.6.RELEASE
o spring-websocket-4.1.6.RELEASE
Step 3 : Now create actual source files under the HelloSpringProject. First we need
to create a package called com.TYBBA. To do this, right click on src in
package explorer section and follow the option − New → Package.
Next we will create HelloWorld.java and MainApp.java files under the com.
Advanced Java [BBA (CA) : Sem. VI] 5.11 Spring and Hibernate
Fig. 5.6
The HelloWorld.java file is as follows:
package com.TYBBA;
public class HelloWorld
{
private String msg;
public void setMessage(String msg)
{
this.msg = msg;
}
public void getMessage()
{
System.out.println("Your Message : " + msg);
}
}
Following is the content of the second file MainApp.java −
package com.TYBBA;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.
ClassPathXmlApplicationContext;
Advanced Java [BBA (CA) : Sem. VI] 5.12 Spring and Hibernate
Fig. 5.7
The name of the file is Beans.xml but we can change the name. We have to
make sure that this file is available in CLASSPATH and use the same name
in the main application while creating an application context as shown in
MainApp.java file.
The Beans.xml is used to assign unique IDs to different beans and to control
the creation of objects with different values without impacting any of the
Spring source files. For example: we can pass any value for "msg" variable
and we can print different values of message without impacting
Advanced Java [BBA (CA) : Sem. VI] 5.13 Spring and Hibernate
HelloWorld.java and MainApp.java files using the following file. We can use
<property> tag to pass the values of different variables used at the time of
object creation.
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation =
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans
3.0.xsd">
<bean id = "helloWorld" class = "com.TYBBA.HelloWorld">
<property name = "msg" value = "Hello World 2022!"/>
</bean>
</beans>
Step 5 : Once the source and beans configuration files are created, we can compile
and run the program. To do this, keep MainApp.Java file tab active and use
either Run option available in the Eclipse IDE or use Ctrl + F11 to compile
and run the MainApp application. The output will print the following
message in Eclipse IDE's console:
Your Message : Hello World 2022!
The Spring
Con!guration
Container
Metadata
Produces
• Spring configuration consists of at least one and typically more than one bean
definition that the container must manage. XML-based configuration metadata
shows these beans configured as <bean/> elements inside a top-level <beans/>
element.
• These bean definitions correspond to the actual objects that make up your
application. Typically you define service layer objects, data access objects (DAOs),
presentation objects such as Struts Action instances, infrastructure objects such as
Hibernate SessionFactories, JMS Queues, and so forth.
5.5.2 Spring Bean Definition
• A bean is an object that is instantiated, assembled, and otherwise managed by a
Spring IoC container.
• A Spring IoC container manages one or more beans. These beans are created with the
configuration metadata that you supply to the container, for example, in the form of
XML <bean/> definitions.
• Bean definition contains the information called configuration metadata, which is
needed for the container to know the following:
o How to create a bean
o Bean's life cycle details
o Bean's dependencies
• Within the container itself, these bean definitions are represented as BeanDefinition
objects, which contain (among other information) the following metadata:
o A package-qualified class name: typically the actual implementation class of the
bean being defined.
o Bean behavioral configuration elements, which state how the bean should behave
in the container (scope, life cycle callbacks, and so forth).
o References to other beans that are needed for the bean to do its work; these
references are also called collaborators or dependencies.
• Other configuration settings to set in the newly created object, for example, the
number of connections to use in a bean that manages a connection pool, or the size
limit of the pool.
• This metadata translates to a set of properties that make up each bean definition.
• The following table shows a set of the following properties that make up each bean
definition from the configuration metadata.
Advanced Java [BBA (CA) : Sem. VI] 5.16 Spring and Hibernate
• In the case of XML-based configuration metadata, you can use the destroy-method
attribute to specify the name of the method that has a void no-argument signature.
For example:
<bean id = "demoBean" class = "examples.demoBean" destroy-method =
"destroy"/>
• Following is the class definition:
public class demoBean
{
public void destroy()
{
// do some destruction work
}
}
• A sample bean implementing the above interfaces would look like this:
demoBean.java
package com.TYBBA;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class demoBean implements InitializingBean, DisposableBean
{
//Other bean attributes and methods
@Override
public void afterPropertiesSet() throws Exception
{
//Bean initialization code
}
@Override
public void destroy() throws Exception
{
//Bean destruction code
}
}
5.6 HIBERNATE
• Hibernate is a framework which is used to develop persistence logic which is
independent of Database software. In JDBC to develop persistence logic we deal with
primitive types. Whereas Hibernate framework we use Objects to develop persistence
logic which are independent of database software.
Advanced Java [BBA (CA) : Sem. VI] 5.20 Spring and Hibernate
Persistent
Object
HIBERNATE
Mapping File
Con!guration File
Database
Transaction
Session Factory JNDI
Factory
Connection
Provider
JDBC
Java Database
Persistent Session
Application
Object
JTA
Transaction
Transaction:
• The transaction object specifies the atomic unit of work. It is optional. The
org.hibernate.Transaction interface provides methods for transaction management.
ConnectionProvider:
• It is a factory of JDBC connections. It abstracts the application from DriverManager or
DataSource. It is optional.
TransactionFactory:
• It is a factory of Transaction. It is optional.
5.6.2 Hibernate Environment
1. First Download the latest version of Hibernate from
http://www.hibernate.org/downloads
2. Set classpath properly by copying all the library files from /lib into your
CLASSPATH, and change your classpath variable to include all the JARs and then
copy hibernate3.jar file into your CLASSPATH. This file lies in the root directory of
the installation.
3. Install the required packages as listed below:
o dom4j
o Xalan
o Xerces
o Cglib
o log4j
o Commons
o SLF4J
<property name="hibernate.dialect">update</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.url">com.mysql.jdbc.Driver</property>
<property name="connection.username">system</property>
<property name="connection.password">jtp</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver
</property>
<!-- List of XML mapping files -->
<mapping resource = "employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Note: For plsql databases dialect property type is:org.hibernate.dialect.PostgreSQLDialect
5.7.1 Hibernate Sessions
• A Session is used to get a physical connection with a database.
• The life cycle of a Session is bounded by the beginning and end of a logical
transaction.
• The main function of the Session is to offer create, read and delete operations for
instances of mapped entity classes. Instances may exist in one of three states:
o transient: never persistent, not associated with any Session.
o persistent: associated with a unique Session.
o detached: previously persistent, not associated with any Session.
• The session objects should not be kept open for a long time because they are not
usually thread safe and they should be created and destroyed them as needed.
• Transient instances may be made persistent by calling save(), persist() or
saveOrUpdate().
• Persistent instances may be made transient by calling delete(). Any instance returned
by a get() or load() method is persistent.
• Detached instances may be made persistent by calling update(), saveOrUpdate(),
lock() or replicate(). The state of a transient or detached instance may also be
made persistent as a new persistent instance by calling merge().
• save() and persist() result in an SQL INSERT, delete() in an SQL DELETE and
update() or merge() in an SQL UPDATE. Changes to persistent instances are detected at
flush time and also result in an SQL UPDATE. saveOrUpdate() and replicate() result
in either an INSERT or an UPDATE.
• If the Session throws an exception, the transaction must be rolled back and the
session discarded.
Advanced Java [BBA (CA) : Sem. VI] 5.25 Spring and Hibernate
o A central feature of Hibernate, proxies, depends upon the persistent class being
either non-final, or the implementation of an interface that declares all public
methods.
o All classes that do not extend or implement some specialized classes and
interfaces required by the EJB framework.
Simple POJO Example:
• Based on the few rules mentioned above, we can define a POJO class as follows:
public class Employee
{
private int id;
private String fstName;
private String lstName;
private int salary;
private int age;
public Employee() {}
public Employee(String fname, String lname, int sal, int age)
{
this.fstName = fname;
this.lstName = lname;
this.salary = sal;
this.age=age;
}
public int getId()
{
return id;
}
public void setId( int id )
{
this.id = id;
}
public String getFstName()
{
return fstName;
}
public void setFstName( String first_name )
{
this.fstName = first_name;
}
public String getLstName()
{
return lstName;
}
Advanced Java [BBA (CA) : Sem. VI] 5.28 Spring and Hibernate
• The following mapping file is defined which instructs Hibernate how to map the
defined class or classes to the database tables.
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name = "Employee" table = "EMPLOYEE">
<meta attribute = "class-description">
This class contains the employee detail.
</meta>
<id name = "id" type = "int" column = "id">
<generator class="native"/>
</id>
<property name = "fstName" column = "first_name" type = "string"/>
<property name = "lstName" column = "last_name" type = "string"/>
<property name = "salary" column = "sal" type = "int"/>
<property name = "age" column = "age" type = "int"/>
</class>
</hibernate-mapping>
• Now save the mapping document in a file with the format <classname>.hbm.xml. We
saved our mapping document in the file Employee.hbm.xml.
• The mapping elements used in the mapping file as follows:
o The mapping document is an XML document having <hibernate-mapping> as the
root element, which contains all the <class> elements.
o The <class> elements are used to define specific mappings from a Java classes to
the database tables. The Java class name is specified using the name attribute of
the class element and the database table name is specified using the table
attribute.
o The <meta> element is optional element and can be used to create the class
description.
o The <id> element maps the unique ID attribute in class to the primary key of the
database table. The name attribute of the id element refers to the property in the
class and the column attribute refers to the column in the database table. The type
attribute holds the hibernate mapping type, this mapping types will convert from
Java to SQL data type.
Advanced Java [BBA (CA) : Sem. VI] 5.30 Spring and Hibernate
o The <generator> element within the id element is used to generate the primary
key values automatically. The class attribute of the generator element is set to
native to let hibernate pick up either identity, sequence, or hilo algorithm to
create primary key depending upon the capabilities of the underlying database.
o The <property> element is used to map a Java class property to a column in the
database table. The name attribute of the element refers to the property in the
class and the column attribute refers to the column in the database table. The type
attribute holds the hibernate mapping type, this mapping types will convert from
Java to SQL data type.
5.8.1 Hibernate - Mapping Types
• The types declared and used in the mapping files are not Java data types; they are not
SQL database types either. These types are called Hibernate mapping types, which can
translate from Java to SQL data types and vice versa.
Mapping type Java type ANSI SQL Type
Integer int or java.lang.Integer INTEGER
Long long or java.lang.Long BIGINT
Short short or java.lang.Short SMALLINT
Float float or java.lang.Float FLOAT
Double double or java.lang.Double DOUBLE
big_decimal java.math.BigDecimal NUMERIC
character java.lang.String CHAR(1)
String java.lang.String VARCHAR
Byte byte or java.lang.Byte TINYINT
boolean boolean or java.lang.Boolean BIT
yes/no boolean or java.lang.Boolean CHAR(1) ('Y' or 'N')
true/false boolean or java.lang.Boolean CHAR(1) ('T' or 'F')
Date and time type:
Mapping type Java type ANSI SQL Type
Date java.util.Date or java.sql.Date DATE
Time java.util.Date or java.sql.Time TIME
timestamp java.util.Date or java.sql.Timestamp TIMESTAMP
calendar java.util.Calendar TIMESTAMP
calendar_date java.util.Calendar DATE
Advanced Java [BBA (CA) : Sem. VI] 5.31 Spring and Hibernate
try
{
tx = s.beginTransaction();
List employees = s.createQuery("FROM Employee").list();
for (Iterator iterator = employees.iterator();
iterator.hasNext();)
{
Employee employee = (Employee) iterator.next();
System.out.print("First Name: " + employee.getFstName());
System.out.print(" Last Name: " + employee.getLstName());
System.out.println(" Salary: " + employee.getSalary());
System.out.println(" Age: " + employee.getAge());
}
tx.commit();
}
catch (HibernateException e)
{
if (tx!=null) tx.rollback();
e.printStackTrace();
}
finally
{
s.close();
}
}
/* Method to UPDATE salary for an employee */
public void updateEmployee(Integer EmployeeID, int salary)
{
Session s = factory.openSession();
Transaction tx = null;
try
{
tx = s.beginTransaction();
Employee employee = (Employee)s.get(Employee.class, EmployeeID);
employee.setSalary( salary );
s.update(employee);
tx.commit();
}
catch (HibernateException e)
{
if (tx!=null) tx.rollback();
Advanced Java [BBA (CA) : Sem. VI] 5.34 Spring and Hibernate
e.printStackTrace();
} finally {
s.close();
}
}
/* Method to DELETE an employee from the records */
public void deleteEmployee(Integer EmployeeID)
{
Session s = factory.openSession();
Transaction tx = null;
try
{
tx = s.beginTransaction();
Employee employee = (Employee)s.get(Employee.class, EmployeeID);
s.delete(employee);
tx.commit();
}
catch (HibernateException e)
{
if (tx!=null) tx.rollback();
e.printStackTrace();
}
finally
{
s.close();
}
}
}
Compilation and Execution:
• Here are the steps to compile and run the above mentioned application. Make sure,
you have set PATH and CLASSPATH appropriately before proceeding for the
compilation and execution.
o Create hibernate.cfg.xml configuration file as explained in configuration
chapter.
o Create Employee.hbm.xml mapping file as shown above.
o Create Employee.java source file as shown above and compile it.
o Create ManageEmployee.java source file as shown above and compile it.
o Execute ManageEmployee binary to run the program.
Advanced Java [BBA (CA) : Sem. VI] 5.35 Spring and Hibernate
• You would get the following result, and records would be created in the EMPLOYEE
table.
$java ManageEmployee
.......VARIOUS LOG MESSAGES WILL DISPLAY HERE........
First Name: Ashu Last Name: Joshi Salary: 2000 age: 37
First Name: Lily Last Name: Das Salary: 5000 age: 40
First Name: Geeta Last Name: Patil Salary: 10000 age: 49
First Name: Ashu Last Name: Joshi Salary: 5000 age: 37
First Name: Geeta Last Name: Patil Salary: 10000 age: 49
If you check your EMPLOYEE table, it should have the following records −
mysql> select * from EMPLOYEE;
+----+------------+-----------+--------+----
| id | first_name | last_name | salary |age
+----+------------+-----------+--------+----
| 29 | Ashu | Joshi | 5000 |37
| 31 | Geeta | Patil | 10000 |49
+----+------------+-----------+--------+-----
2 rows in set (0.00 sec
mysql>
ADDITIONAL PROGRAMS
Program 5.1: Spring core example to print Welcome to Spring Program.
HelloBean.java
package springcore.example;
public classHelloBean
{
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public void sayHello()
{
System.out.println("Hello" + this.name);
}
}
Advanced Java [BBA (CA) : Sem. VI] 5.36 Spring and Hibernate
Main.java
package springcore.example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main
{
private static ApplicationContext context;
public static void main(String[] args)
{
context = new ClassPathXmlApplicationContext("beans.xml");
HelloBeanhelloBean = (HelloBean) context.getBean("HelloBean");
helloBean.sayHello();
}
}
Src/main/resources
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http
://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"xmlns:tx="http://ww
w.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<context:component-scanbase-package="com.programcreek.examples"/>
<beanid="HelloBean"class="springcore.example.HelloBean">
<propertyname="name"value="Spring Programe"/>
</bean>
</beans>
Advanced Java [BBA (CA) : Sem. VI] 5.37 Spring and Hibernate
Output:
HelloBean.java
package springcore.example;
public class HelloBean
{
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
Advanced Java [BBA (CA) : Sem. VI] 5.38 Spring and Hibernate
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<context:component-scanbase-package="com.programcreek.examples"/>
<beanid="HelloBean"class="springcore.example.HelloBean">
<propertyname="name"value="Spring Programe"/>
</bean>
</beans>
Output:
SUMMARY
• Spring framework is an open source Java platform that provides comprehensive
infrastructure support for developing robust Java applications very easily and very
rapidly.
• Hibernate is an open-source, non-invasive, light-weight java ORM(Object-Relational
Mapping) framework to develop objects which are independent of the database
software and make independent persistence logic in all JAVA, JEE.
• Spring is modular, allowing us to pick and choose which modules are applicable to an
application, without having to bring in the rest.
Advanced Java [BBA (CA) : Sem. VI] 5.40 Spring and Hibernate
• The core container consists of core, beans, context and expression language
modules that are fundamental to any Spring application.
• Modules in the data layer help to provide data access from the web and business
components. The data layer contain various modules are: JDBC module, ORM
module, JMS (Java Messaging Service) Module, OXM module, Transaction Module.
• The Spring IoC container is at the core of the Spring Framework. The container will
create the objects, wire them together, configure them, and manage their complete
life cycle from creation till destruction. The Spring container uses Dependency
Injection (DI) to manage the components that make up an application.
• Spring provides two types of containers:
1. BeanFactory container
2. ApplicationContext container
• A bean is an object that is instantiated, assembled, and otherwise managed by a
Spring IoC container.
• The Spring Framework supports the following five scopes, three of which are
available only if you use a web-aware ApplicationContext.
• The Spring bean factory is responsible for managing the life cycle callbacks of the
beans which are created in the spring containers.
• The Hibernate architecture includes many objects such as persistent object, session
factory, transaction factory, connection factory, session, transaction etc.
• The Hibernate architecture is categorized in four layers.
o Java application layer
o Hibernate framework layer
o Backhand API layer
o Database layer
• Hibernate Architecture Elements are SessionFactory, session, transaction,
connectionprovider
• Hibernate works best if these classes follow some simple rules, also known as the
Plain Old Java Object (POJO) programming model.
Check Your Understanding
1. What is spring?
(a) Proprietary framework
(b) Spring is a development framework for .Net applications
(c) Open source development framework for enterprise Java
(d) Spring is a development framework for PHP based applications
2. Attribute used to handle web flow requests.
(a) servlet-requests (b) servlet-attr
(c) servlet-flow (d) servlet-mapping
3. Component which additionally provides a pop-up date picker control for its
enclosed input field.
(a) dateValidator (b) clientValidator
(c) clientDateValidator (d) validator
Advanced Java [BBA (CA) : Sem. VI] 5.41 Spring and Hibernate
15. Which of the following method is used inside hibernate session only?
(a) merge() (b) update()
(c) end() (d) kill()
16. Which of the following is not a state of object in Hibernate?
(a) Attached() (b) Detached()
(c) Persistent() (d) Transient()
17. Which of the following is not an advantage of using Hibernate Query Language?
(a) Database independent (b) Easy to write query
(c) No need to learn SQL (d) Difficult to implement
Answers
1. (c) 2. (d) 3. (c) 4. (b) 5. (a) 6. (a) 7. (d) 8. (b) 9. (d) 10. (a)
11. (c) 12. (a) 13. (a) 14. (b) 15. (b) 16. (a) 17. (d)
Practice Questions
Q.I Answer the following questions in short:
1. What is hibernate?
2. What is ORM?
3. What are the core interfaces of Hibernate?
4. Mention some of the advantages of using ORM over JDBC.
5. List the key components of Hibernate.
6. Mention two components of Hibernate configuration object.
7. How is SQL query created in Hibernate?
8. What does HQL stand for?
9. How can we add criteria to a SQL query?
10. What is SessionFactory?
11. Is Session a thread-safe object?
12. What is the difference between session.save() and session.persist() method?
Q.II Answer the following Questions:
1. Explain hibernate architecture?
2. What is the difference between get and load method?
3. What is the difference between update and merge method?
4. What are the states of the object in hibernate?
5. What are the inheritance mapping strategies?
Q.III Define the terms:
1. Hibernate
2. Criteria
3. Persistent classes
4. Session