0% found this document useful (0 votes)
65 views100 pages

J2ee 1

Uploaded by

hasmukhsisodiya8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views100 pages

J2ee 1

Uploaded by

hasmukhsisodiya8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 100

B.C.A.

SEM – 5
INDEX
Sr. No. Subject Name Page No.

1 ADVANCED JAVA AND 1 TO 98


J2EE
2 WEB PROGRAMMING 99 TO 239
USING ASP.NET
3 BASIC PYTHON 240 TO 496

4 SYSTEM ANALYSIS AND 497 TO 528


DESIGN
ADVANCED JAVA
AND J2EE
Major-11
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Course Objectives:

Course Level 5.5 Internal Marks 50


Bachelor of Computer 50
Programme External Marks
Application
Semester V Practical Internal 0

Category of Course Major-11 Practical External 0


4 Prac. External Exam -
Course Credit Duration
Teaching Hours Theory-60 Practical-0 Total 100

Course Code Exam Duration 2:00 Hrs

Course Title Advanced Java and J2EE (Theory)


 To understand different enterprise architecture styles like Two-tier, Three-
tier, and N-tier architectures.
 To provide hands-on knowledge of Java database connectivity using JDBC.
 To build dynamic web applications using Servlets and JSP.
 To introduce key enterprise-level technologies like RMI, EJB, Hibernate, Spring,
and Struts.
 To enable development of full-stack Java enterprise applications using MVC
architecture.

Course Learning Outcomes: After completion of the course:


Understand the fundamentals and architecture of the J2EE platform.
Identify the components of J2EE and explain how they work together in enterprise
applications.
Explain the need for JDBC and its role in Java applications.
Understand the architecture and life cycle of Servlet and JSP.
Collaborate between servlets and JSP with JDBC for dynamic data processing.
Understand and implement MVC (Model-View-Controller) architecture in web
applications.
Explain the need and benefits of using Hibernate as an ORM tool.
Understand the architecture and core features of the Spring framework.
Understand the flow of control in the Struts framework.

P.K.M.COLLEGE 1
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Course Contents
UNIT Hours

Unit 1 Introduction to J2EE 15


Enterprise Architecture Styles:
o Two-Tier Architecture
o Three-Tier Architecture
o N-Tier Architecture
J2EE Architecture
The J2EE Platform
Introduction to J2EE APIs (Servlet, JSP, EJB, JMS)
Introduction to Containers
Introduction of JDBC
JDBC Architecture
Data types in JDBC
Database Exception Handling
JDBC Introduction and Need for JDBC
Types of JDBC Drivers
JDBC API for Database Connectivity (java.sql package)
Statement, PreparedStatement, CallableStatement
ResultSetMetaData
DatabaseMetaData
Connecting with Databases (MySQL, Access, Oracle)
Unit 2 Servlet Introduction 15
Architecture of a Servlet
Servlet API (Javax.servlet and Javax.servlet.http)
Servlet Life Cycle
Developing and Deploying Servlets
Handling Servlet Requests and Responses
Session Tracking Approaches (URL Rewriting, Hidden Form
Fields, Cookies, Session API)
Servlet Collaboration
Servlet with JDBC
RMI overview
RMI architecture
Stub and Skeleton

P.K.M.COLLEGE 2
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Unit 3 Introduction to JSP and JSP Basics 15


JSP vs. Servlet
JSP Architecture
Life cycle of JSP
JSP Elements: Directive Elements, Scripting Elements,
Action Elements
o Directives Elements (page, include)
o Scripting Elements (Declaration, scriptlet, expression)
o Action Elements (JSP:param, JSP:include,
JSP:Forward, JSP:plugin)
JSP Implicit Objects
Including and Forwarding from JSP Pages
include Action
forward Action
Working with Session & Cookie in JSP
Error Handling and Exception Handling with JSP
JDBC with JSP
Introduction to JavaBean
JavaBean Properties
JavaBean Methods
Unit 4 Introduction to MVC 15
Implementation of MVC Architecture
Introduction to EJB
Benefits of EJB
Types of EJB: Session Beans, Entity Beans, Message-driven beans
Introduction to Hibernate
Features of hibernate
Exploring Hibernate Architecture
Hibernate Configuration file
Hibernate Mapping file
Basic Example of Hibernate
Annotation
Hibernate Inheritance
Inheritance Annotations
Introduction of Spring Framework
Spring Architecture
Spring & MVC
Understanding Struts Framework
Struts Flow of Control

P.K.M.COLLEGE 3
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Suggested Reading:
References Book:
The Complete Reference Java 2 - Herbert Schildt and Patrick Naughton
Java Server Programming For Professionals, Ivan Bayross, Sharanam
Shah – Shroff Publication
Advanced Java Programming [ISBN: 978 - 93 - 81786 - 91 – 8]
by Bharat & Company
Developing Java Servlets – Techmedia
JSP Beginner’s Guide – Tata McGraw Hill by Gary Bolling, Bharathi Nataragan
Spring and Hibernate, K. Santosh Kumar, - Tata McGraw-Hill

Web site References:


1) https://www.w3schools.com/java
2) https://www.javatpoint.com/java-tutorial
3) https://www.tutorialspoint.c
om/java
https://www.guru99.com/java-
tutorial.html

P.K.M.COLLEGE 4
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

BCA SEMESTER-5
SUBJECT: Advanced Java and J2EE
1 The J2EE Platform,JDBC(Java Database Connectivity)

Topics Covered

1. Introduction to J2EE
2. Enterprise Architecture Style.
Two-Tier Architecture
Three-Tier Architecture
N-Tier Architecture
3. J2EE Platform.
4. J2EE Architecture
5. Introduction to J2EE APIs(Servlet, JSP, EJB, JMS)
6. Introduction to Container
7. Introduction to JDBC
8. JDBC Architecture
9. Datatypes in JDBC
10.Database exception handling
11.JDBC Introduction and Need for JDBC
12.Types of JDBC Drivers
13.JDBC API for Database Connectivity (java.sql package)
14.Statement, Prepared Statement, Callable Statement
15.Database Meta Data
16.Result set Meta Data
17.Connecting with Databases (MySQL, Oracle, Access)

 Introduction to J2EE
– J2EE (Java 2 Platform, Enterprise Edition) is a platform for developing and
running large-scale, multi-tiered, web-based enterprise applications.
– Core java application only provides facility to work with windows based applications.
– If we required developing the enterprise level application, it will not work.
– Advance java programming provides the facility to develop the Enterprise based and
Internet based Application.
– The J2EE is an open source.
– It reduces the cost of developing multi-tier applications.
– It provides a number of APIs to develop the different types of applications, such as
JDBC(Java Database Connectivity) used for making connection between the java programs
and database, JSP and servlets to create the dynamic web page, RMI(Remote Method
Invocation) to create the remote objects.
– J2EE platforms also include concept of containers to provide the interface between
the clients, server and the database.
– J2EE provides many framework such as JSF, spring, struts, hibernate to develop very
attractive, secure, user-friendly, database driven enterprise application.

P.K.M.COLLEGE 5
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Introduction to Enterprise Application Design Framework


– Enterprise Application is divided in to following six (6) logical layers which are
related to the client tier, middle tier, and database tier. It defines which layer belongs to
which tier.
Presentation Manager
• It defines User interface
• It is located on the client tier.
• Manages the information displayed to the user.
Presentation Logic
• Defines the Navigation system of the user interface
• Focused on how and what will be displayed to the user.
• It may locate with the client tier or business tier or the database tier, based on thin
client and thick client.
Application Logic
• Defines the actual application logic with it.
• It may be, connectivity with the database, validation over the various inputs etc.
• It may locate with the client tier or business tier or the database tier, based on thin
client and thick client.
Business Logic
• Contains business rules of applications.
• Should be shared with whole application.
• It may located with business tier or the database tier, based on thin client and thick
client.
Database Logic
• Defines the table structure and relation among the tables of database
• Includes various constraints of the table.
• Located with the database tier.
Database Manager
• Stores the persistent (constant) data.
• Always located with the database tier.

 Enterprise Architecture Style


1) Single tier Architecture
– When User inputs, its verifications, business logic, and data access all these are
combined together in a single computer such kind of architecture is known as Single tier
architecture.
– In this all layers are located on a single machine.
Advantages
 Easy to manage
 Data consistency is simple due to data stored at single location.
Disadvantages
 Single storage is not sufficient due to large number of data
 Sharing of data in large amount is not possible.
 Multiple user can’t be handled

P.K.M.COLLEGE 6
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

2) Two tier Architecture


– Two tier architecture is divided into two separate tiers, client machine and database
server machine (server).
– The application includes the presentation and business logic.
– Data accessed by connecting client machine to a database which is lying on another
machine (i.e. server)
– In this architecture there are various types of clients which are discussed below.
Advantages
 Any changes made in data access logic will not affect the presentation and the
business logic
 Using this type of architecture it is easy to develop an application.
Disadvantages
 Only supports limited number of users.
 Because each client requires its own connections and each connection requires CPU
and memory.
 So, when number of connection increases the database performance decreases.
Thin Client
 In two tier architecture, presentation manager resides only with the client tier then
such client is called Thin client, while other presentation logic, application logic, business
logic, data logic and database manager reside with the server side.

P.K.M.COLLEGE 7
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Thick Client
 In two tier architecture, presentation manager, presentation logic and application logic are
resides in client tier then such architecture is called thick client.
 Other like business logic, data logic and database manager resides with the server side

Normal Client
 In two tier architecture, if the presentation manager and presentation logic resides in the
client tier then the client is called Normal Client.
 Other like application logic, business logic, data logic and database manager resides with
the server side.

3) Three tier Architecture


– Applications which are divided into three tiers client tier, middle tier (business tier)
and database tier is known as three tier architecture application.
– Logic is physically divided into separate tier.
– The presentation layer and logic runs on the client machine.
– Application and business logic runs on J2EE server and database logic is there with
database layer.

P.K.M.COLLEGE 8
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Thin Client
– In three tier architecture if the
presentation manager is resides
only with the client tier then
client is called as thin client.
– Presentation logic, application
logic and business logic are with
the business tier
– Database logic and database
manager are with the database tier
(EIS – Enterprise Information
System.)

Thick Client
– In three tier architecture if the
presentation manager
,presentation logic, application
logic resides with the client tier
then client is called as thick
client.
– Business logic only with the business tier
– Database logic and database manager are with the database tier (EIS – Enterprise
Information System.)
Advantages
 Improves scalability since application server are deployed on many machines.
 Database connection not required longer from each and every client, only requires
connections from a smaller number of application server.
 Better reusability due to same logic can be initiated from many clients.
 Security is ensured because not direct access to the database.
Disadvantages
 Increases complexity

4) N-tier architecture
– Application divided into more than three tier can be called as N-tier architecture.
– In N-tier architecture it is not decided how many tier can be present.
– Number of tiers in application is depends on the computing and network hardware on
which application is to be deployed.
– Basically divided into client tier, web tier, business (EJB) tier and database tier (EIS).
Client tier
 Collection of user interface for user request and the print the response
 Runs on the client machine.
 Uses browser or applet as client side application.

P.K.M.COLLEGE 9
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Web tier
 Collection of JSP and servlet dynamic webpages to handle the HTTP specific request
logons, session , accesses the business services and response back to the client.
Business tier
 Collection of business logic for J2EE application. For example EJB (Enterprise
JavaBeans)
 Using such business tier, same business logic can support different types of client like
browser, WAP, other stand-alone application.
Database (EIS) tier
 EIS tier consist of the DBMS/RDBMS.
 Handles User SQL requests and generates appropriate response based on the queries.
 Stores all persistent data in database
Advantages
 Separation of User interface logic, business logic is done
 Business logic resides on small number of centralized machines.
 Easy to maintain, to manage, to scale, loosely coupled etc., Modification is easy
Disadvantages
 More complex structure
 Difficult to setup and maintain all separated layers

P.K.M.COLLEGE 10
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

 J2EE Architecture
Java 2 Enterprise edition is basically developed for commercial project and web-
solution.
Business solution for commercial project solved using multi-tier architecture.
The J2EE platform use multi-tier distributed application model for enterprise
application.
By dividing application logic into various component according to its tasks or
functions and various application components that are gathered J2EE application are installed
on different machine depending on the tier.
Following tiers are available for J2EE.
1. Client tier
2. Web tier
3. Business tier
4. EIS tier
Client tier (Client machine) :
It consists of programs that interact with the users.
These components prompt the user for the input conversion as a request to forward to
software on the component that processes the request and returns the result to the client
program.

Web tier (J2EE server):


It handle the intrection between client and business tier.
It provides the Internet functionality to the J2EE application.
The components on the web tier use HTTP to receive requests and send responses to
the client that resides on the tier. Web-Tier Provides services to Client-tier using HTTP.
Accepting info from other s/w sent using POST, GET, and PUT using HTTP.
Transmit data such as images and dynamic content.
Components of Web Tier: Two components that work on the web tier are mentioned
below:
Servlets
Java server pages (JSP)

P.K.M.COLLEGE 11
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Business tier ( J2EE server):


is handled by enterprise beans running in the business tier.
shows how an enterprise bean receives data from client programs, processes it (if
necessary), and sends it to the enterprise information system tier for storage.
An enterprise bean also retrieves data from storage, processes it (if necessary), and
sends it back to the client program.

EIS tier (database server):


The enterprise information system tier handles enterprise information system
software, and includes enterprise infrastructure systems such as enterprise resource planning
(ERP), mainframe transaction processing, database systems, and other legacy information
systems.
J2EE application components might need access to enterprise information systems for
database connectivity,

P.K.M.COLLEGE 12
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

 J2EE Platform
Introduction to editions of Java.
 J2SE – Java 2 standard edition normally used for developing desktop application.
 J2EE – Java 2 enterprise edition used for applications which are run on server
example websites.
 J2ME – Java 2 Micro Edition (mobile) used for developing small scale device like
mobile, PDA

What is J2EE ?
 J2EE is an open standard which is provided by Sun micro system (now Oracle) for
applications which runs on server.
 Provides Multi-tier architecture.
 Includes J2SE + most of other java technologies.
(JavaMail, Servlet, EJB, JMS, JSF)
 J2EE API’s
1) JDBC (Java Database Connectivity)
Used to connect Java Database application with any relational database.
Can access well know database like MySQL, Oracle, MS – access.
It provides a standard way for Java programs to establish connections, execute SQL
queries, and manage transactions with different database management systems (DBMS).
The major components of JDBC include the DriverManager for managing database
drivers, Connection for establishing and managing database connections, Statement for
executing SQL queries, and ResultSet for handling query results.
2) RMI (Remote Method Invocation)
Used to access object method running on different machine
RPC (Remote Procedure Call)
3) EJB (Enterprise JavaBeans)
Used to server side components
Consisting business logic for J2EE application
4) Servlet
Java Servlet API is a powerful tool for creating web applications.
It lets you build dynamic web pages that can interact with users & databases.
Servlets are Java classes that handle requests from web browsers & generate
responses.
A servlet is a Java class that extends HTTP servlet functionality.
5) JMS (Java Message Service)
The Java Message Service is a Java API that allows applications to create, send,
receive, and read messages.
Message is an information that communicates between different components in the
same system or different systems.
Message can be a text, XML document, and JSON data etc which take place either in
synchronous or asynchronous manner.
A client can create, send, receive and read the messages by using the messaging
agent.

P.K.M.COLLEGE 13
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

6) JNDI (Java Naming and Directory Interface)


The API allows developers to send, receive, and manage email messages within their
Java applications.
Provides different types of naming and directory service.
It allows Java applications to locate and retrieve objects (like database connections or
JMS message brokers) by their names, without needing to know the specific implementation
details of the underlaying naming service.
7) JM (Java Mail)
The API allows developers to send, receive, and manage email messages within their
Java applications.
The JavaMail API is a Java library that provides a framework for building mail and
messaging applications
8) JSP (JavaServer Pages)
Used for creating dynamic web pages, simplifying the development of web interfaces.
It defines the interaction between JSP pages and the runtime environment provided by
a JSP container, allowing developers to create web pages with embedded Java code and use
pre-built and custom tags for functionality.
9) JTA (Java Transaction API)
The Java Transaction API (JTA) provides a standard way for Java applications to
manage distributed transactions, which involve multiple resources or systems, like databases.
JTA allows applications to explicitly mark the start and end of a transaction, ensuring
that all operations within that transaction are treated as a single unit.

 Introduction to Container
Container
 Container is interface between a component and Client (lower level code) or platform
oriented functionality which supports component.
 Container provides communication between client and components.
Types of Container
 Applet Container
 Application Container
 EJB Container
 Web Container

P.K.M.COLLEGE 14
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Applet Container
 One kind of client container which is used to manage execution of the applet on the
browser.
Application Container
 It is client container which is used to manage application client and their component
EJB Container
 It is one kind of server container.
 Used to manage enterprise beans components.
Web container
 It is also sever container which is used to manage execution of JSP pages and servlet
components

 Introduction of JDBC
JDBC stands for Java Database Connectivity.
JDBC is bridge between Java Application and Database.
JDBC is an API that helps applications to communicate with databases, it allows Java
programs to connect to a database, run queries, retrieve, and manipulate data. Because of
JDBC, Java applications can easily work with different relational databases like MySQL,
Oracle, PostgreSQL, and more
The Java program invokes the method of the JDBC API. The JDBC API then calls the
JDBC driver and submits the queries to the SQL statements that a database can understand.
After the query has been performed, the JDBC driver retrieves the result of the query form
the database.
The result is converted into the JDBC API classes that are used by the java Program.
Then the java program obtain the result of the query.

 JDBC Architecture
The JDBC architecture describes the interaction of JDBC API with java application
and java applet. JDBC API consists of several call level interface with JDBC Driver Manager
and JDBC drivers for defining database.
JDBC API is responsible for transferring data between an application and a database.

P.K.M.COLLEGE 15
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Application: It can be a Java application or servlet that communicates with a data source.
The JDBC API: It allows Java programs to execute SQL queries and get results from the
database. Some key components of JDBC API include
o Interfaces like Driver, ResultSet, RowSet, PreparedStatement, and Connection that helps
managing different database tasks.
o Classes like DriverManager, Types, Blob, and Clob that helps managing database
connections.
o JDBC API is a collection of various classes, methods, and interfaces for easy
communication with a database. JDBC API provides two different packages to connect
with different databases.
java.sql.*;
javax.sql.*;

DriverManager: It plays an important role in the JDBC architecture. It uses some


database-specific drivers to effectively connect enterprise applications to databases.

JDBC Drivers
o JDBC drivers are used to connecting with data sources. All databases like Oracle,
MSSQL, MYSQL, etc. have their drivers, to connect with these databases we need to load
their specific drivers. Class is a java class used to load drivers. Class.forName() method is
used to load drivers in JDBC architecture.
JDBC-ODBC Bridge Drivers
o As the name suggests JDBC-ODBC Bridge Drivers are used to translate JDBC
methods to ODBC function calls. JDBC-ODBC Bridge Drivers are used to connect database
drivers to the database. Even after using JDBC for Java Enterprise Applications, we need an
ODBC connection for connecting with databases.
o JDBC-ODBC Bridge Drivers are used to bridge the same gap between JDBC and ODBC
drivers. The bridge translates the object-oriented JDBC method call to the procedural

P.K.M.COLLEGE 16
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

ODBC function call. It makes use of the sun.jdbc.odbc package. This package includes a
native library to access ODBC characteristics.

 Datatypes in JDBC
The following table summarizes the default JDBC data type that the java data type is
converted when you call the setXXX() method of preparedStatement and CallableStatement.
SQL JDBC/Java setXXX()
VARCHAR Java.lang.String setString()
CHAR Java.lang.String setString()

LONGVARCHAR Java.lang.String setString()

BIT Boolean setBoolean()

NUMERIC Java.math.BigDecimal setBigDecimal()

TINYINT Byte setByte()

SMALLINT Short setShort()

INTEGER Int setInt()

BIGINT Long setLong()

REAL Float setFloat

FLOAT Float setFloat()

DOUBLE Double setDouble()


DATE Java.sql.Date setDate()
ARRAY Java.sql.Array setArray()
STRUCT Java.sql.Struct setStruct()

TIME Java.sql.Time setTime()

 Database Exception Handling


Exception handling is the process of detecting, managing, and responding to
errors (called exceptions) that occur during the execution of a program
JDBC Exception handling is very similar to the Java Exception handling but for
JDBC, the most common exception you'll deal with is java.sql.SQLException.

Method Description

Gets the error number associated


getErrorCode( )
with the exception.

Gets the JDBC driver's error


getMessage( ) message for an error, handled by
the driver or gets the Oracle

P.K.M.COLLEGE 17
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

error number and message for a


database error.

Gets the XOPEN SQLstate string.


For a JDBC driver error, no useful
information is returned from this
getSQLState( ) method. For a database error,
the five-digit XOPEN SQLstate
code is returned. This method
can return null.

Gets the next Exception object in


getNextException( )
the exception chain.

Prints the current exception, or


printStackTrace( ) throwable, and it's backtrace to a
standard error stream.

Prints this throwable and its


printStackTrace(PrintStream s) backtrace to the print stream you
specify.

Prints this throwable and it's


printStackTrace(PrintWriter w) backtrace to the print writer you
specify.
Here is the general form of a try block –
try {
// Your risky code goes between these curly braces!!!
}
catch(Exception ex) {
// Your exception handling code goes between these
// curly braces, similar to the exception clause
// in a PL/SQL block.
}
finally {
// Your must-always-be-executed code goes between these
// curly braces. Like closing database connection.
}
Here Simple example using Exception handling in jdbc :
import java.sql.*;
import java.util.Scanner;

public class SimpleJDBCWithException {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Get input from user

P.K.M.COLLEGE 18
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

System.out.print("Enter Employee Name: ");


String empName = sc.nextLine();

// Database connection info


String url = "jdbc:mysql://localhost:3306/companydb";
String user = "root"; // replace with your MySQL username
String password = "root"; // replace with your MySQL password

Connection conn = null;


PreparedStatement pstmt = null;

try {
// Load JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Connect to the database


conn = DriverManager.getConnection(url, user, password);

// Prepare SQL insert statement


String sql = "INSERT INTO Employee (Emp_Name) VALUES (?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, empName);
// Execute update
int rows = pstmt.executeUpdate();
System.out.println(rows + " row(s) inserted successfully!");

} catch (SQLException e) {
System.out.println("Database error occurred: " +
e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("JDBC Driver not found.");
} finally {
// Close resources
System.out.println("Error while closing resources.");
}
sc.close();
}
}

 Types of Database Driver


JDBC Driver Type
JDBC Driver is a software component that enables java application to interact with
the database.
Database vendor provide a driver along with the database. These database driver are
used to communicate with java programs.
There are 4 types of JDBC drivers:
 JDBC-ODBC bridge driver
 Native-API driver (partially java driver)
 Network Protocol driver (fully java driver)
 Thin driver (fully java driver)

P.K.M.COLLEGE 19
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

1. JDBC-ODBC Bridge
The JDBC-ODBC bridge driver converts all JDBC call into ODBC calls and send them to
the ODBC driver. The ODBC driver then forwards the call to the database server.
Figure shows communication between java application and Database using JDBC-ODBC
Bridge. E.g. MS Access do not provide JDBC driver. Instead they provide Open Database
Connectivity(ODBC) drivers. One can access such databases by using the ODBC-JDBC
Bridge.

Advantages
 easy to use.
 can be easily connected to
any database.
Disadvantages
 Performance degraded
because JDBC method call
is converted into the ODBC
function calls.
 The ODBC driver needs to
be installed on the client
machine.

2. Native-API / Partly-Java driver

This driver communicates directly the database server. Therefore the vendor
database library needs to be
loaded on each client computer.
The type 2 driver converts
JDBC calls into database-
specific calls for databases.
Example: Oracle will have
oracle native API.
Advantage:
 Performance upgraded
than JDBC-ODBC
bridge driver.
Disadvantage:
 The Native driver needs
to be installed on the
each client machine.
 The Vendor client library
needs to be installed on
client machine.

P.K.M.COLLEGE 20
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

3. Net-Protocol / fully-Java Driver


The JDBC Type 3 driver, or the net-protocol/all-java driver, follows a three-tiered
approach. In the three-tiered approach, JDBC database requests are passed to a middle-tier
server.
The middle-tier server then translates the requests and passes to the database-specific
native-connectivity interface and forward the requests to the database server. If the middle-
tier server is written in Java, it can use the Type 1 or Type 2 drivers to forward the requests to
the database server.

Advantage:
 No client side library is required
because of application server that
can perform many tasks like
auditing, load balancing, logging
etc.
Disadvantages:
 Network support is required on
client machine.
 Requires database-specific coding
to be done in the middle tier.
 Maintenance of Network Protocol
driver becomes costly because it
requires database-specific coding
to be done in the middle tier.

4. Thin Driver / fully java driver


These drivers are commonly implemented in java to achieve platform independence.
These drivers convert JDBC calls into vendor specific DBMS protocol. Therefore
client applications can communicate directly with the database server when Type 4 driver are
used.

Advantage:
 Better performance than all other drivers.
 No software is required at client side or
server side.
Disadvantage:
 Drivers depend on the Database.

P.K.M.COLLEGE 21
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

 JDBC API for database connectivity


Key Components of JDBC API (java.sql package)

Here are the core interfaces and classes:

Component Description
Driver Manager Manages a list of database drivers. Establishes a
connection to the database using a URL, username, and
password.
Connection Represents an active connection with a database.
Provides methods to create Statement objects and
manage transactions.
Statement Used to execute SQL queries (static SQL).
Prepared Statement A subclass of Statement used for executing
precompiled parameterized queries. More efficient and
secure than Statement.
Result Set Represents the result of a SQL query. Allows traversal
through returned data.
SQLException Handles any SQL-related errors.
ResultSetMetaData Provides information about the types and properties of
the columns in a ResultSet.
Database Metadata Allows querying metadata about the database (tables,
columns, supported features, etc.).

1 Connection
A Connection is the session between java application and database.
Once a connection is established, it is used to execute SQL statements and manage
database transactions.
The Connection interface is a factory of Statement, Prepared Statement, and Database
Meta Data i.e. object of Connection can be used to get the object of Statement and Database
Meta Data. The Connection interface provide many methods for transaction management like
commit(),rollback() etc.

Key Responsibilities of Connection


1. Establish communication with the database.
2. Create SQL statements like Statement, PreparedStatement, and
CallableStatement.
3. Manage transactions (commit, rollback).
4. Retrieve metadata about the database.
5. Close the connection when done.

You use the DriverManager class to obtain a Connection:

Connection conn = DriverManager.getConnection(


"jdbc:mysql://localhost:3306/mydatabase","username","password");

P.K.M.COLLEGE 22
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Methods :

Method Description
createStatement() Creates a basic Statement for executing
SQL.
prepareStatement(String sql) Creates a PreparedStatement for
parameterized SQL queries.
prepareCall(String sql) Creates a CallableStatement for calling
stored procedures.
setAutoCommit(boolean flag) Enables/disables auto-commit mode.
commit() Commits the current transaction manually.
rollback() Rolls back the current transaction.
close() Closes the connection and releases resources.
isClosed() Checks if the connection is closed.
getMetaData() Returns database metadata (e.g., DB name,
version, tables).

2. Driver Manager Class


The DriverManager Class belongs to java.sql package. It consists of the static
methods to manage the JDBC Driver must register with the DriverManager class. There are
many JDBC Driver for Oracle. In short DriverManager class controls the interface between
the application and JDBC Driver.
In DriverManager class important methos is getConnection() method which is used to
establish the connection with the different database servers. It has three overloaded signatures
(parameters)

Key Responsibilities of Connection


Load and register JDBC drivers.
Establish database connections.

Methods :
getConnection(String url):
Attempts to establish a connection with the given URL.

getConnection(String url, String user, String password):


Establishes a connection with the specified database credentials.

registerDriver(Driver driver) :
Manually registers a JDBC driver (rarely used now).

3 Statement
The interface object is used to execute the SQL statement and obtain the result
produced after executing the statement. It is having following different types of methods to
execute the different types of SQL Statements.
A Statement object is created from a Connection object:
Connection conn = DriverManager.getConnection
(dbURL, username, password);
Statement stmt = conn.createStatement();

P.K.M.COLLEGE 23
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Methods :
executeQuery():
This method is used to fetch the records from the database by using select query. It
can be only return the single ResultSet object at a time. It passed a parameter with it which is
SQL statement which selects the records from the database. This method throws
SQLException.
Syntax :-
public ResultSet executeQuery(String sql) throws SQLException
executeUpdate() :
This methods is used to perform the insert, update, delete operation on the records of
the database. It returns the integer value which indicates no. of records updated the records in
the database. It passes a SQL statement as a parameter which updates the records of the
database. This method throws SQLException.
Syntax :-
Public int executeUpdate(String sql) throws SQLException
execute() :
It is used to execute the SQL statements which returns the multiple results. It returns
the boolean indicating value if it returns true that the next result is ResultSet object and if it
returns false then defines no. of records updated or no more result is there. This method
throws SQLException.
Syntax :-
Public boolean execute(String sql) throws SQLException

4 Prepared Statement
A PreparedStatement is a pre-compiled SQL statement. It is a subinterface of
Statement.
Prepared Statement objects have some useful additional features than Statement
objects. Instead of hard coding queries, PreparedStatement object provides a feature to
execute a parameterized query.
Advantages of PreparedStatement
When PreparedStatement is created, the SQL query is passed as a parameter. This
Prepared Statement contains a pre-compiled SQL query, so when the PreparedStatement is
executed, DBMS can just run the query instead of first compiling it.
We can use the same PreparedStatement and supply with different parameters at the
time of execution.
Methods of PreparedStatement:
setInt(int, int): This method can be used to set integer value at the given parameter
index.
setString(int, string): This method can be used to set string value at the given
parameter index.
setFloat(int, float): This method can be used to set float value at the given parameter
index.
setDouble(int, double): This method can be used to set a double value at the given
parameter index.
executeUpdate(): This method can be used to create, drop, insert, update, delete etc.
It returns int type.
executeQuery(): It returns an instance of ResultSet when a select query is executed.

P.K.M.COLLEGE 24
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Examples :-

String sql = “insert into data(ID, Name) values (?,?)”;


PreparedStatement ps = con.preparedStatement(sql);
ps.setInt(1,10);
ps.setString(2,”ABC”);

5 Callable Statement
A CallableStatement object provides a way to call stored procedure in a standard way
for all DBMSs.
A stored procedure is stored in a database; the call to the stored procedure is what a
CallableStatement object contains.
You can create an object of the CallableStatement (interface) using the prepareCall()
method of the Connection interface. This method accepts a string variable representing a
query to call the stored procedure and returns a CallableStatement object.
A Callable statement can have input parameters, output parameters or both. To pass
input parameters to the procedure call you can use place holder and set values to these using
the setter methods (setInt(), setString(), setFloat()) provided by the CallableStatement
interface.

Setting values to the input parameters


You can set values to the input parameters of the procedure call using the setter
methods.
These accepts two arguments, one is an integer value representing the placement
index of the input parameter and, the other is a int or, String or, float etc… representing the
value you need to pass as input parameter to the procedure.
cstmt.setString(1, "Ram");
cstmt.setInt(2, 3000);
cstmt.setString(3, "Ayodhya");

Executing the Callable Statement


Once you have created the CallableStatement object you can execute it using one of
the execute() method.
cstmt.execute();

6 Result set Meta Data


ResultSetMetaData is an interface in Java under the package
java.sql.ResultSetMetaData which can be used in determining or retrieving the structural
characteristics of a table's ResultSet.
It is not always necessary for the programmer to know the structural information of a
ResultSet column (such as name, datatype, count, or other information associated with a
specific column) being returned by the ResultSet object's get( ) method.

Steps to use ResultSetMetaData in JDBC


Below are the steps to use the RSMD (ResultSetMetaData) in JDBC to retrieve
information about ResultSet Columns.

P.K.M.COLLEGE 25
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Step 1: ResultSetMetaData can be used by importing the ResultSetMetaData interface from


java.sql package in the JDBC program.

import java.sql.ResultSetMetaData;

Step 2: After importing the package create a connection with your database through your
jdbc connector and Driver. In this article, I'll be using MySQL as my jdbc database

Connection con =
DriverManager.getConnection("jdbc:mysql://localhost/dbname",
"yourusername",

"your password");
Statement stmt = con.createStatement()) ;

Step 3: Create a SQL query through the Statement object which returns an object of
ResultSet type. e.g.: select query to view all information.

String query = "SELECT * FROM AyurvedaHerb";


ResultSet rs = stmt.executeQuery(query);

Step 4: Now that we have the ResultSet object we can create the ResultSetMetaData object
using the .getMetaData( ) method of the ResultSet interface as:

ResultSetMetaData rstm=rs.getMetaData();

7 Database Meta Data


Generally, Data about data is known as metadata.
The DatabaseMetaData interface provides methods to get information about the
database you have connected with like, database name, database driver version, maximum
column length etc...
It provides metadata about the database like its structure, capabilities, and other
properties of the database. The metadata refers to data about the data of database with the
help of JDBC. By using DatabaseMetaData, we can perform different tasks.
Retrieving information about database products like database name, version of the
database, driver version of the database, and other properties.
And we can get information about tables, columns, primary keys, foreign keys, and
other things.
And it can determine SQL syntax supported by the database.
Also, DatabaseMetaData provides information about database objects.
Commonly used methods of DatabaseMetaData interface
Database Product Name
Database Product Version
Driver Name
Driver Version
Database Connection Information
Database User name Information
Database URL information
Database Time Date functions information

P.K.M.COLLEGE 26
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Method Description
getDatabaseProductName() Returns database name (e.g., "MySQL", "Oracle").
getDatabaseProductVersion() Returns the version of the database.
getDriverName() Returns the JDBC driver name.
getTables(...) Returns a ResultSet of table names.
getColumns(...) Returns a ResultSet of columns for a given table.
supportsTransactions() Checks if transactions are supported.
getPrimaryKeys(...) Retrieves primary key info for a table.
getExportedKeys(...) Gets foreign keys that reference the table.

Example :
import java.sql.*;

public class DatabaseMetaDataExample {


public static void main(String[] args) throws Exception {
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/Heritage_data", "root",
"password");
DatabaseMetaData meta = conn.getMetaData();

System.out.println("Database: " + meta.getDatabaseProductName());


System.out.println("Version: " + meta.getDatabaseProductVersion());
System.out.println("Driver: " + meta.getDriverName());
System.out.println("Supports Transactions: " + meta.supportsTransactions());
}
}

Difference between Statement and Prepared Statement

1. The PreparedStatement is a slightly more powerful version of a Statement,


and should always be at least as quick and easy to handle as a Statement.
2. The PreparedStatement may be parametrized while statement is not
3. PreparedStatement is sub interface of statement inferface
4. A Statement will always proceed through the steps for each SQL query sent to the
database while prepared statement pre-executes some of those steps

Connecting with other databases(Mysql,Access,Oracle)


Connect with Oracle
To connect with oracle data base first of all create oracle procedure.
First of all start oracle database.
start sql*plus enter scott as username and tiger as password.
Then create Panchang_data table and enter data in a table.
 Create table Panchang_data(id number(3), tithi varchar2(30));
 Insert into Panchang_data values(1,’Purnima’);
 Insert into Panchang_data values(2,’Amavas’);
Step 1: Import the JDBC Package
First, we need to import the packages.

P.K.M.COLLEGE 27
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Step 2: Load or Register the Driver


Class.forName(“oracle.jdbc.driver.OracleDriver”);

Step 3: Establish a Connection


Connection con = DriverManager.getConnection(url,user,password)
user: Username from which your SQL command prompt can be accessed.
password: password from which the SQL command prompt can be accessed.
con: It is a reference to the Connection interface.
Url: Uniform Resource Locator which is created as shown below:
String url = “ jdbc:oracle:thin:@localhost:1521:xe”

Where,
oracle is the database used, thin is the driver used
@localhost is the IP Address where a database is stored
1521 is the port number and xe is the service provider.

Step 4: Create a Statement


Statement st = con.createStatement();

Step 5: Execute SQL Query


int m = st.executeUpdate(sql);
if (m==1)
System.out.println("inserted successfully : "+sql);
else
System.out.println("insertion failed");

Step 6: Close the Connection


con.close();

Connect with mysql


To connect with mysql database first of all create table in mysql.
And start apache server.
Then create FolkTradition table and enter data in a table.
 Create table FolkTradition(id number(3), TraditionName varchar2(50), Region
varchar2(50), Category varchar2(50));
 Insert into FolkTradition values(1,’Garba’,’Gujarat’,’Dance’);
 Insert into FolkTradition values(2,’Bihu Dance’,’Assam’,’Dance’);
Step 1 - Users have to create a database in MySQL (for example let the name of the
database be 'FolkTraditionDB' ).

Step 2 - Create a table in that database.

Step 3 - In this src code, we will set up the connection and get all the data from the
table. we have created the 'check.java' file in the src folder.

P.K.M.COLLEGE 28
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

write the java program


//Java program to set up connection and get all data from table
import java.sql.*;

public class FolkTradition {


public static void main(String arg[])
{
Connection connection = null;
try {
// below two lines are used for connectivity.
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/FolkTradionDB",
"root", "");

// FolkTradionDB is database
// root is name of database
// “” is password of database

Statement statement;
statement = connection.createStatement();
ResultSet resultSet;
resultSet = statement.executeQuery(
"select * from FolkTradion");

while (resultSet.next()) {
id = resultSet.getInt("id");
TraditionName = resultSet.getString("TraditionName”);
System.out.println(" TraditionName: " +TraditionName);
}
resultSet.close();
statement.close();
connection.close();
}
catch (Exception exception) {
System.out.println(exception);
}
} // function ends
} // class ends

P.K.M.COLLEGE 29
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

2 RMI, Servlet

Topics Covered
1. Servlet Introduction
2. Architecture of a Servlet
3. Servlet API (Javax.servlet and Javax.servlet.http)
4. Servlet Life Cycle
5. Developing and Deploying Servlets
6. Handling Servlet Requests and Responses
7. Session Tracking Approaches (URL Rewriting, Hidden Form Fields,
Cookies, Session API)
8. Servlet Collaboration
9. Servlet with JDBC
10. RMI overview
11. RMI architecture
12. Stub and Skeleton

 Servlet Introduction
– A Java Servlet is a Java class that runs on a web server or application server and
handles HTTP requests and responses, enabling dynamic web content generation.
– Servlet is one of the server-side programming language which runs on Java enabled
server. It is used to develop web based applications.
– Servlets are grouped under the Advanced Java tree that is used to create dynamic web
applications.
– Servlets are robust, well scalable, and are primarily used in developing server-side
applications
Key Features:
Servlets work on the server side.
Generate dynamic responses efficiently.
Can easily manage/control the application flow.
Suitable to implement business logic.
Can effectively balance the load on the server side.
Handle HTTP Request and Response
Also act as an interceptor or filter for a specific group of requests

P.K.M.COLLEGE 30
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

 Architecture of a Servlet

Execution of Servlets basically involves Six basic steps:


The Clients send the request to the Web Server.
The Web Server receives the request.
The Web Server passes the request to the corresponding servlet.
The Servlet processes the request and generates the response in the form of output.
The Servlet sends the response back to the webserver.
The Web Server sends the response back to the client and the client browser displays
it on the screen.
1. Client
– The client shown in the architecture above is the web browser and it primarily works
as a medium that sends out HTTP requests over to the web server and the web server
generates a response based on some processing in the servlet and the client further processes
the response.
2. Web Server
– Primary job of a web server is to process the requests and responses that a user sends
over time and maintain how a web user would be able to access the files that has been hosted
over the server.
– The server we are talking about here is a software which manages access to a
centralized resource or service in a network.
– There are precisely two types of webservers:
• Static web server
• Dynamic web server
3. Web Container
– Web container is another typical component in servlet architecture which is
responsible for communicating with the servlets.
– Two prime tasks of a web container are:
• Managing the servlet lifecycle
• URL mapping
 Servlet API
– javax.servlet package

P.K.M.COLLEGE 31
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

– javax.servlet.http package
Javax.servlet Package
1. Servlet Interface :- It is having the methods which define the life cycle of the servlet.
2. ServletConfig Interface :- It provides basic or initialization parameter of the servlet.
3. ServletContext Interfce :- It provides the runtime environment to the servlet also logs
the events using log().
4. Generic Servlet class :- It implements the servlet, ServletConfig and Serialization
interface.
5. ServletRequest interface :- It is used to read the client request.
6. ServletResponce interface :- It is used to write the response data.
7. ServletException class :- It defines servlet occurred errors.
8. UnavailableException class :- It defines that servlet is parmanently or temporarily not
available.
9. ServletInputStream class :- It provides the input stream to read the data from client
request.
10. ServletOutputStream :- It provides the output stream to writing the data as response to
client.
11. ServletThreadModel interface :- It provides the mechanism to make servlet thread safe.

Javax.servlet.http package
1. HttpServletRequest interface :- It allows the servlet to read the data from HTTP
request.
2. HttpServletResponse interface :- It allows the servlet to write the data to an HTTP
response.
3. HttpServlet class :- It provides the methods of handling HTTP requests and HTTP
responses.
4. Cookie class :- It is used to store the state information at client side or on the client
machine.
5. HttpSession Interface :- It is used to create session and provides the way of reading and
writing the session and accessing the information related to session.
6. HttpSessionBuildingListener Interface :- It informs the object that it is bound or
unbound to the session.
7. HttpSessionEvent class :- It wrap ups the session change events.
8. HttpSessionBindingEvent class :- It defines that when session should be bound or
unbound with the object value and its attributes.
 Servlet Life Cycle
There are three life cycle methods of a Servlet:

P.K.M.COLLEGE 32
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

init()
service()
destroy()

Servlet life cycle can be defined as the stages through which the servlet passes from its
creation to its destruction.
The servlet life cycle consists of these stages:
Servlet is created
Servlet is initialized
Servlet is ready to service
Servlet is servicing
Servlet is not ready to service
Servlet is destroyed
Init() :
– The init method is called only once. It is called only when the servlet is created, and
not called for any user requests afterwards. So, it is used for one-time initializations, just as
with the init method of applets.
– The servlet is normally created when a user first invokes a URL corresponding to the
servlet, but you can also specify that the servlet be loaded when the server is first started.
– The init method definition looks like this :
public void init() throws ServletException {
// Initialization code...
}
Service() :
– The service() method is the main method to perform the actual task. The servlet
container (i.e. web server) calls the service() method to handle requests coming from the
client( browsers) and to write the formatted response back to the client.
– Each time the server receives a request for a servlet, the server spawns a new thread
and calls service. The service() method checks the HTTP request type (GET, POST, PUT,
DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
– Here is the signature of this method :
public void service(ServletRequest request,
ServletResponse response) throws ServletException,
IOException {}
– The doGet() and doPost() are most frequently used methods with in each service
request. Here is the signature of these two methods.
The doGet() Method
– A GET request results from a normal request for a URL or from an HTML form that
has no METHOD specified and it should be handled by doGet() method.
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
// Servlet code
}
The doPost() Method
– A POST request results from an HTML form that specifically lists POST as the
METHOD and it should be handled by doPost() method.

P.K.M.COLLEGE 33
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

public void doPost(HttpServletRequest request,


HttpServletResponse response) throws ServletException,
IOException {
// Servlet code
}
The destroy() Method
– The destroy() method is called only once at the end of the life cycle of a servlet. This
method gives your servlet a chance to close database connections, halt background threads,
write cookie lists or hit counts to disk, and perform other such cleanup activities.
– After the destroy() method is called, the servlet object is marked for garbage
collection.
– The destroy method definition looks like this :
public void destroy() {
// Finalization code...}

 Handling Servlet Requests and Responses


(1) ServletRequest Interface
• Servlet Request Interface is a member javax.servlet package. Public interface
ServletRequest defines an object to provide client request to a servlet. The Servlet container
create a ServletRequest object and passes it as an argument to the service method.

HttpServletRequest
• A public interface HttpServletRequest extends ServletRequest Interface and it is a
member of javax.servlet.http package. It is used to provide request information for HTTP
servlets. The Servlet container creates an HttpServletRequest object and passes it as a
argument to the service method.
Methods :
1. setAttribute()
• It is a method of the ServletRequest Interface and stores an attribute in this request.
Syntax :-
void setAttribute(String name, Object obj)
2. getParameter()
• It is a method of ServletRequest interface and it returns the value of a request
parameter as a String or null if the parameter does not exist.
Syntax:-
String getParameter(String name)
3. getParameterNames()
• It is a method of ServletRequest interface and it returns Enumeration of String objects
contining the names of the parameters contain in this request.
Syntax:-
Enumeration getParameterNames()
4. getParameterValues()
• It is a method of ServletRequest interface and it returns an array of string objects with
all the values that the given request parameter has, or null if the parameter does not exist.
Syntax:-
String [] getParameterValues(String name)
5. getAttribute()
• It is a method of ServletRequest interface and it returns the value of named attribute
as an Object or null if no attribute of the name exists.

P.K.M.COLLEGE 34
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Syntax:-
Object getAttribute(String arr)
6. getAttributeNames()
• It is a method of ServletRequest Interface and it returns an Enumeration containing
the names of the attribute available to this request.

Syntax:-
Enumeration getAttributeNames()
7. getRemoteHost()
• It is a method of ServletRequest interface and it returns the fully qualified name of the
client or the last proxy that sent the request.
Syntax:-
String getRemoteHost()
8. getHeaders()
• The HttpServletRequest interface provides to return all the values of the specified
request header as an Enumeration of String objects.
Syntax:-
Enumeration getHeaders(String name)
9. getCookies()
• The HttpServletRequest interface provides the getCookies method to obtain an array
cookies that are present in the request. This method will return null if no cookies were sent.
Syntax:-
Cookies[] getCookies()
10. getQueryString()
• The HttpServletRequest interface returns the query string that is contained in the
request URL after the path.
Syntax:-
String getQueryString()
11. getSession()
• The HttpServletRequest interface returns the current session associated with this
request or if the request does not have a session creates one.
Syntax:-
HttpSession getSession()

ServletResponse Interface
A public interface ServletResponse is a member of javax.servlet package. It defines
an object to assist a servlet in sending a response to the client. The container of the servlet
creates a ServletResponse object and passes it as an argument to its service method.

HttpServletResponse Interface
• A public interface HttpServletResponse extends ServletResponse interface.
HttpServletResponse interface provides Http specific HTTP specific functionalities in
sending response.
Methods :
1. setContectType()
• It is a method of ServletResponse interface, which is used to set the contect type of
the response being sent to the client.
Syntax:-
void setContectType(String type)
2. setHeader()

P.K.M.COLLEGE 35
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

• It is a method of HttpServletResponse interface and is used to set a response header


with the given name and value. If the header had already been set, the new value overwrites
the previous one.
Syntax:-
void setHeader(String name,String value)
3. setStatus()
• It is a method of HttpServetResponse interface and it sets the status code for HTTP
response.
Syntax:-
void setStatus(int sc)
4. getWriter()
• It is a method of ServletResponse interface and it returns a PrintWriter object that can
be used to send character data to the client.
Syntax:-
PrintWriter getWriter() throws IOException
5. sendRedirect()
• It is a method of HttpServletResponse interface and it sends a temporary redirect
response to the client using the specified redirect location URL.
Syntax :-
void sendRedirect(String location) throws IOException
6. addCookies()
• It is a method of ServletResponse interface and it adds the specified cookie to the
HTTP response.
Syntax:-
void addCookie(Cookie cookie)
7. encodeURL()
• It is a method of HttpServletResponse interface and it encode the specified URL by
including the session ID in it, if encoding is not needed, return the URL unchanged. The
implementation of this method includes the logic to determine weather the session ID needs
to be encoded in the URL.
Syntax:-
String encodeURL(String url)

 Session tracking approaches


What is Session ?
• When a user makes a page request to the server, the server creates a temporary session
to identify that user. So when that same user goes to another page on that site the server can
recognize that user easily. So a Session is a temporary small unique connection between a
server and the user or client enabling it to identify that user across multiple page requests or
visit to that site.
Why Session is needed ?
• More than hundreds of simultaneous users can be visiting website at a time and if we
can identify each of them separately then it can provide huge benefits to us.

P.K.M.COLLEGE 36
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Session
Tracking Approach
• URL Rewriting
• Using Hidden Field
• Using Cookie

URL Rewriting
– URL rewriting is based on the idea of inserting a unique ID in each URL of the
response from the server.
– In URL rewriting, we append a token or identifier to the URL of the next Servlet or
the next resource. We can send parameter name/value pairs using the following format:
url?name1=value1&name2=value2&??
– A name and a value is separated using an equal = sign, a parameter name/value pair is
separated from another parameter using the ampersand(&). When the user clicks the
hyperlink, the parameter name/value pairs will be passed to the server. From a Servlet, we
can use getParameter() method to obtain a parameter value.
Advantage of URL Rewriting
1. It will always work whether cookie is disabled or not (browser independent).
2. Extra form submission is not required on each pages.
Disadvantage of URL Rewriting
1. It will work only with links.
2. It can send Only textual information.
Example :
//LoginServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class LoginServlet extends HttpServlet {


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String username = request.getParameter("user");

P.K.M.COLLEGE 37
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

// URL rewriting: passing data via URL


out.println("<a href='WelcomeServlet?user=" + username + "'>
Click here to continue </a>");
}
}

// WelcomeServlet.java
// Get data from rewritten URL
String username = request.getParameter("user");
out.println("<h2>Welcome, " + username + "!</h2>");

Using Hidden Field


– A web server can send a hidden HTML form field along with a unique session ID as
follows −
<input type = "hidden" name = "sessionid" value =
"12345">
– This entry means that, when the form is submitted, the specified name and value are
automatically included in the GET or POST data. Each time when web browser sends request
back, then session_id value can be used to keep the track of different web browsers.
– This could be an effective way of keeping track of the session but clicking on a
regular (<A HREF...>) hypertext link does not result in a form submission, so hidden form
fields also cannot support general session tracking.

Using Cookie
– Cookies are the textual information that is stored in key-value pair format to the
client's browser during multiple requests. It is one of the state management techniques in
session tracking.
– Cookie provide a better alternative to explicit URL rewriting, because cookie s are not
sent as query string but are exchanged within the bodies of HTTP requests and responses.
Since there is no need no rewrite URLs , session handling via cookies does not depend on
weather the content is static or dynamic.
javax.servlet.http.Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies.
Constructor of Cookie class
Cookie(String name, String value): Constructs a cookie with a specified name and
value.
Commonly used methods of Cookie class
public void setMaxAge(int expiry):Sets the maximum age of the 1. cookie in
seconds.
public String getName():Returns the name of the cookie. The name cannot be
changed after creation.
public String getValue():Returns the value of the cookie. Other methods required for
using Cookies
public void addCookie(Cookie ck):method of HttpServletResponse interface is used
to add cookie in response object.
public Cookie[] getCookies():method of HttpServletRequest interface is used to
return all the cookies from the browser.

P.K.M.COLLEGE 38
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

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

Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.

Setting Cookies with Servlet


Setting cookies with servlet involves three steps −
(1) Creating a Cookie object − You call the Cookie constructor with a cookie name and a
cookie value, both of which are strings.
Cookie cookie = new Cookie("key","value");
(2) Setting the maximum age − You use setMaxAge to specify how long (in seconds) the
cookie should be valid.
Following would set up a cookie for 24 hours.
cookie.setMaxAge(60 * 60 * 24);
(3) Sending the Cookie into the HTTP response headers − You use response.addCookie to
add cookies in the HTTP response header as follows −
response.addCookie(cookie);

Example :
// CreateYogaCookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class CreateYogaCookieServlet extends HttpServlet {


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Define a simple yoga routine


String yogaRoutine = "Sun Salutation, Tree Pose, Cobra
Pose, Meditation";

// Create cookie
Cookie yogaCookie = new Cookie("Yoga Routine", yogaRoutine);

// Set cookie expiration time (optional) — 1 day


yogaCookie.setMaxAge(24 * 60 * 60);

// Add cookie to response


response.addCookie(yogaCookie);

P.K.M.COLLEGE 39
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

out.println("<html><body>");
out.println("<h3>Yoga routine cookie has been set!</h3>");
out.println("<a href='ReadYogaCookieServlet'>View Yoga
Routine</a>");
out.println("</body></html>");
}
}
//ReadYogaCookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ReadYogaCookieServlet extends HttpServlet {


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

Cookie[] cookies = request.getCookies();


String yogaRoutine = null;

if (cookies != null) {
for (Cookie cookie : cookies) {
if ("yogaRoutine".equals(cookie.getName())) {
yogaRoutine = cookie.getValue();
break;
}
}
}
}
}

Session API
– Apart from the above mentioned three ways, servlet provides HttpSession Interface
which provides a way to identify a user across more than one page request or visit to a Web
site and to store information about that user.
– The servlet container uses this interface to create a session between an HTTP client
and an HTTP server. The session persists for a specified time period, across more than one
connection or page request from the user.
– You would get HttpSession object by calling the public
method getSession() of HttpServletRequest, as below −
Sr.No. Method & Description
1 public Object getAttribute(String name)
This method returns the object bound with the specified name in this
session, or null if no object is bound under the name.

P.K.M.COLLEGE 40
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

2 public Enumeration getAttributeNames()


This method returns an Enumeration of String objects containing the
names of all the objects bound to this session.
3 public long getCreationTime()
This method returns the time when this session was created,
measured in milliseconds since midnight January 1, 1970 GMT.
4 public String getId()
This method returns a string containing the unique identifier assigned
to this session.
5 public long getLastAccessedTime()
This method returns the last accessed time of the session, in the
format of milliseconds since midnight January 1, 1970 GMT
6 public int getMaxInactiveInterval()
This method returns the maximum time interval (seconds), that the
servlet container will keep the session open between client accesses.
7 public void invalidate()
This method invalidates this session and unbinds any objects bound
to it.
8 public boolean isNew(
This method returns true if the client does not yet know about the
session or if the client chooses not to join the session.
9 public void removeAttribute(String name)
This method removes the object bound with the specified name from
this session.
10 public void setAttribute(String name, Object value)
This method binds an object to this session, using the name specified.
11 public void setMaxInactiveInterval(int interval)
This method specifies the time, in seconds, between client requests
before the servlet container will invalidate this session.

Session Tracking Example


This example describes how to use the HttpSession object to find out the creation time and
the last-accessed time for a session. We would associate a new session with the request if one
does not already exist.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

// Extend HttpServlet class


public class SessionTrack extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {

P.K.M.COLLEGE 41
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

// Create a session object if it is already not created.


HttpSession session = request.getSession(true);

// Get session creation time.


Date createTime = new Date(session.getCreationTime());

// Get last access time of this web page.


Date lastAccessTime = new Date(session.getLastAccessedTime());

String title = "Welcome Back to my website";


Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
String userID = new String("ABCD");
// Check if this is new comer on your web page.
if (session.isNew()) {
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
} else {
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
}
session.setAttribute(visitCountKey, visitCount);

// Set response content type


response.setContentType("text/html");
PrintWriter out = response.getWriter();

out.println(“Session info”+session.getId());
out.println(“Current Time”+create Time);
out.println(“Last Access Time”+lastAccessTime);
out.println(“User Id”+uId());
out.println(“Number of Visit”+visitCount);
} }

Compile the above servlet SessionTrack and create appropriate entry in web.xml file. Now
running http://localhost:8080/SessionTrack would display the following result when you
would run for the first time −
Welcome to my website

Session Infomation
Session info value
id 0AE3EC93FF44E3C525B4351B77ABB2D5
Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010
Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010
User ID ABCD
Number of visits 0

P.K.M.COLLEGE 42
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Now try to run the same servlet for second time, it would display following result.

Welcome Back to my website

Session Infomation

info type value


id 0AE3EC93FF44E3C525B4351B77ABB2D5
Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010
Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010
User ID ABCD
Number of visits 1

 Servlet Collaboration
Servlet Collaboration
– A servlet can call another servlet’s public method directly, if the two servlets run
within the same server. To call another servlet’s public methods directly, we must know the
name of the servlet that we want to call.
– Servlet running together in the same server have serveral ways to communicate with
one another. This communication can be called as a sort servlet collaboration.
RequestDispatcher Interface
– A RequestDispatcher is a public interface which defines an object that receives
requests from the client and sends them to any resource such as a servlet, HTML file or JSP
file on the server.
– The servlet container creates the ReuestDispatcher object, which is used as a wrapped
around a server resources located at a particular path or given by a particular name.
Methods :
1. Forward
If forwards a client request to another resource. It allows a servlet to serve as a
“request Processor”. Forward may not be called if data has been sent to the client.
Syntax :-
public void forward(ServletRequest req, ServletResponse res) throws
ServletException, IOException

figure (just for understanding)

P.K.M.COLLEGE 43
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

As you see in the above figure, response of second servlet is sent to the client.
Response of the first Servlet is not displayed to the user.
2. include()
It includes the content of a resource like servlet, JSP page, HTML file in the response.
This method is used to include some content to the response has been initiated by
opening a Print Writer or Servlet Output Stream back to the client machine.
Syntax:-
public void include(Servlet Request req, Servlet Response res) throws Servlet
Exception, IO Exception

figure (just for understanding)

As you can see in the above figure, response of second servlet is included in the
response of the first Servlet that is being sent to the client.

 Servlet With JDBC


– This tutorial assumes you have understanding on how JDBC application works.
Before starting with database access through a servlet, make sure you have proper JDBC
environment setup along with a database.

To start with basic concept, let us create a simple table and create few records in that table as
follows –

Create Table
To create the DailyPanchang table in PanchangDB database, use the following steps –

Step 1: create database with mysql


Step 2: create table DailyPanchang with PanchangDB database
Field Like :
Id int , Date date, Tithi varchar2(50), Nakshtra varchar2(50)
Step 3: insert record
Step 4: open netbeans , create project, add jdbc driver
Step 5: access PanchangDB database using servlet

import java.sql.Statement;
import java.io.IOException;
import java.io.PrintWriter;
import static java.lang.System.out;

P.K.M.COLLEGE 44
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class NewServlet extends HttpServlet {

protected void processRequest(HttpServletRequest request,


HttpServletResponse response)throws ServletException, IOException
{

response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn=DriverManager.getConnection
("jdbc:mysql://localhost:3306/ PanchangDB","root","");

Statement stmt=conn.createStatement();
String sql="select * from DailyPanchang";
ResultSet rs=stmt.executeQuery(sql);
// Extract data from result set

while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
Date date = rs.getDate("date");
String Tithi = rs.getString("Tithi");
String Nakshtra = rs.getString(“Nakshtra”);
out.println("ID: " + id + "<br>");
out.println(", date: " + date + "<br>");
out.println(", Tithi: " + Tithi + "<br>");
out.println(", Nakshtra: " + Nakshtra + "<br>");

}
//Cleanup Enviroment
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
}
}

P.K.M.COLLEGE 45
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

@Override
public void doGet(HttpServletRequest request, HttpServletResponse
response)throws ServletException, IOException {
// Set response content type
processRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException
{
processRequest(request, response);
}

@Override
public String getServletInfo() {
return "Short description";
}
}

 Introduction to RMI
– RMI stands for Remote Method Invocation. It is a mechanism that allows an object
residing in one system (JVM) to access/invoke an object running on another JVM.
– RMI is used to build distributed applications; it provides remote communication
between Java programs. It is provided in the package java.rmi.
– RMI provide remote communication between the applications using two object stub
and skeleton.

Understanding stub and skeleton


Stub : The stub object on the client machine builds an information block and sends this
information to the server. The stub is an object, acts as a gateway for the client side. All the
outgoing requests are routed through it. It resides at the client side and represents the remote
object. When the caller invokes method on the stub object, it does the following tasks:

1. It initiates a connection with remote Virtual Machine (JVM),


2. It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM),
3. It waits for the result
4. It reads (unmarshals) the return value or exception, and
5. It finally, returns the value to the caller.

Skeleton :The skeleton is an object, acts as a gateway for the server side object. All the
incoming requests are routed through it. When the skeleton receives the incoming request, it
does the following tasks:

1. It reads the parameter for the remote method


2. It invokes the method on the actual remote object, and
3. It writes and transmits (marshals) the result to the caller.

P.K.M.COLLEGE 46
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

 RMI Architecture
– RMI architecture defines the how the client request to the server for the remote
objects and how the server processes for the request.
– Each layer can perform specific functions, like establish the connection, assemble and
disassemble the parameters, transmitting the objects etc.

Application Layer
Application layer consists of the client side java program and Server side java
programs with remote methods. Here, the high level calls are made in order to access the
remote method through an interface that extends java.rmi.Remote.
When we want to define set of methods that will be remotely called they must be
declared in one or more interface that should extend java.rmi.Remote.

Proxy Layer
The Stub/Skeleton Layer is responsible for listening to the remote method calls made
by the client and redirecting them to the server. This layer consists of a stub and a skeleton.

The stub and skeleton are created using the RMI compiler. These are simply class
files that represent the client and server side of remote object.
A stub is a client-side proxy representing the remote objects. The stub communicates
the method in invocations to the remote object through a skeleton that is implemented on the
server.

P.K.M.COLLEGE 47
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

The skeleton is a server-side proxy that communicates with the stub. It makes a call
to the remote object.

Remote Reference Layer


The Remote reference layer is interface between the proxy layer and transport layer.
The Remote Reference Layer interprets the references made by the client to the remote
objects on the server.
This layer is presented in the client-side as well as server side. The RRL on the client-
side receives the request for the methods from the stub. The request is then transmitting the
parameter or object through the network it should be in the form of a stream.
The JVM works with the JAVA Byte Codes. It can get the stream-oriented data from
the transport layer and give it to the proxy layer and vice versa.

Transport Layer
Transport layer manages the connection between client remote reference layer and
remote server machine. It receives a request from the client-side RRL and establish a
connection with the server through server-side RRL.
 It is responsible for handling the actual machine to machine communication; the
default communication will take place through a standard TCP/IP.
 It creates a stream that is accessed by the remote reference layer to send and receive
data to and from other machines.
 It sets up the connections to remote machines.
 It manage the connection.
 It monitors the connections to make sure that they are live
 It listens for connections from the machines.

P.K.M.COLLEGE 48
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

3 JSP,Java Beans

Topics Covered
1. Introduction to JSP and JSP Basics
2. JSP Vs. Servlet
3. JSP Architecture
4. Lifecycle of JSP
5. JSP Elements: Directive Elements, Scripting Elements, Action Elements
• Directives Elements (page, include)
• Scripting Elements (Declaration, scriptlet, expression)
• Action Elements (JSP:param, JSP:include, JSP:Forward, JSP:plugin)
6. JSP Implicit objects
7. Including and Forwarding from JSP Pages – Include Action , Forward Action
8. Working with Session and Cookie in JSP
9. Error Handling and Exception Handling with JSP
10. JDBC With JSP
11. JavaBean Properties
12. JavaBean Methods
13. JavaBean Introduction

 Introduction to JSP
– Java Server Pages (JSP) is a server-side technology that creates dynamic web
applications.
– It allows developers to embed Java code directly into HTML or XML pages, and it
makes web development more efficient.
– JSP is an advanced version of Servlets. It provides enhanced capabilities for building
scalable and platform-independent web pages.
– Using JSP, you can collect input from users through Webpage forms, present records
from a database or another source, and create Webpages dynamically.
– JSP tags can be used for a variety of purposes, such as retrieving information from a
database or registering user preferences, accessing JavaBeans components, passing control
between pages, and sharing information between requests, pages etc.
Key Features of JSP
• It is platform-independent; we can write once, run anywhere.
• It simplifies database interactions for dynamic content.
• It contains predefined objects like request, response, session, and application,
reducing development time.
• It has built-in mechanisms for exception and error management.
• It supports custom tags and tag libraries.
Why JSP is preferred over servlets?
• JSP provides an easier way to code dynamic web pages.
• JSP does not require additional files like, java class files, web.xml etc
• Any change in the JSP code is handled by Web Container(Application server like
tomcat), and doesn't require re-compilation.
• JSP pages can be directly accessed, and web.xml mapping is not required like in
servlets.

P.K.M.COLLEGE 49
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

 JSP Vs. Servlet

Servlet JSP

Servlet is a java code. JSP is a HTML-based compilation


code.

Writing code for servlet is harder than JSP is easy to code


JSP

Servlet plays a controller role in the JSP is the view in the MVC approach
,MVC approach. for showing output.

Servlet is faster than JSP. JSP is slower than Servlet because the
first step in the JSP lifecycle is the
translation of JSP to java code and then
compile.

Servlet can accept all protocol JSP only accepts HTTP requests.
requests.

In Servlet, we can override the In JSP, we cannot override its service()


service() method. method.

In Servlet by default session In JSP session management is


management is not enabled, user have automatically enabled.
to enable it explicitly.

In Servlet we have to implement In JSP business logic is separated from


everything like business logic and presentation logic by using JavaBeans
presentation logic in just one servlet client-side.
file.

Modification in Servlet is a time- JSP modification is fast, just need to


consuming compiling task because it click the refresh button.
includes reloading, recompiling,
JavaBeans and restarting the server.

It does not have inbuilt implicit In JSP there are inbuilt implicit objects.
objects.

There is no method for running While running the JavaScript at the


JavaScript on the client side in Servlet. client side in JSP, client-side validation
is used.

P.K.M.COLLEGE 50
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Packages are to be imported on the top Packages can be imported into the JSP
of the program. program (i.e, bottom , middleclient-
side, or top )

It can handle extensive data It cannot handle extensive data


processing. processing very efficiently.

The facility of writing custom tags is The facility of writing custom tags is
not present. present.

Servlets are hosted and executed on Before the execution, JSP is compiled
Web Servers. in Java Servlets and then it has a
similar lifecycle as Servlets.

 JSP Architecture
– The web server needs a JSP engine, i.e, a container to process JSP pages. The JSP
container is responsible for intercepting requests for JSP pages. This tutorial makes use of
Apache which has built-in JSP container to support JSP pages development.
– A JSP container works with the Web server to provide the runtime environment and
other services a JSP needs. It knows how to understand the special elements that are part of
JSPs.
JSP Processing
As with a normal page, your browser sends an HTTP request to the web server.
The web server recognizes that the HTTP request is for a JSP page and forwards it to
a JSP engine. This is done by using the URL or JSP page which ends with .jsp instead
of .html.
The JSP engine loads the JSP page from disk and converts it into a servlet content.
This conversion is very simple in which all template text is converted to println( ) statements
and all JSP elements are converted to Java code. This code implements the corresponding
dynamic behavior of the page.
The JSP engine compiles the servlet into an executable class and forwards the original
request to a servlet engine.
A part of the web server called the servlet engine loads the Servlet class and executes
it. During execution, the servlet produces an output in HTML format. The output is furthur
passed on to the web server by the servlet engine inside an HTTP response.
The web server forwards the HTTP response to your browser in terms of static HTML
content.
Finally, the web browser handles the dynamically-generated HTML page inside the
HTTP response exactly as if it were a static page.

P.K.M.COLLEGE 51
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

All the above mentioned steps can be seen in the following diagram −

 JSP life cycle


The life cycle of a JavaServer Page (JSP) consists of various phases that start from its
creation, followed by its translation into a servlet, and finally managed by the servlet
lifecycle. The JSP engine handles this process automatically.
JSP Compilation

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

The compilation process involves three steps −


Parsing the JSP.
Turning the JSP into a servlet.
Compiling the servlet.

P.K.M.COLLEGE 52
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

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.

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 on request basis. This 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.

JSP Cleanup
The destruction phase of the JSP life cycle represents when a JSP is being removed from use
by a container.
The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override
jspDestroy when you need to perform any cleanup, such as releasing database connections or
closing open files.
The jspDestroy() method has the following form −
public void jspDestroy() {

// Your cleanup code goes here.

 JSP Elements
JSP elements are as follows:
• Directive elements (page, include)
• Scripting elements (Declaration, scriptlet, expression)
• Action elements (JSP:param, JSP:include, JSP:Forward, JSP:plugin)

P.K.M.COLLEGE 53
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

1) Scripting Element
Scriptlet Element :
– Scripting elements in JSP must be written within the <% %> tags.
– Following is the syntax of Scriptlet −
<% code fragment %>

Example :
<html>
<head><title>Hello World</title></head>

<body>
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body>
</html>

Declaration Element :
– A declaration declares one or more variables or methods that you can use in Java code
later in the JSP file. You must declare the variable or method before you use it in the JSP file.
Following is the syntax for JSP Declarations −
<%! declaration; [ declaration; ]+ ... %>
Example :
<%! int i = 0; %>
<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>

Expression Element :
– 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 %>

P.K.M.COLLEGE 54
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Example :
<html>
<head><title>A Comment Test</title></head>

<body>
<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>
</body>
</html>

2) Directive elements
– A JSP directive affects the overall structure of the servlet class. It usually has the
following form −
<%@ directive attribute = "value" %>

S.No. Directive & Description

1 <%@ page ... %>

Defines page-dependent attributes, such as scripting language, error page,


and buffering requirements.

2 <%@ include ... %>

Includes a file during the translation phase.

JSP - The page Directive


– The page directive is used to provide instructions to the container. These instructions
pertain to the current JSP page. You may code page directives anywhere in your JSP page.
By convention, page directives are coded at the top of the JSP page.
Following is the basic syntax of the page directive −
<%@ page attribute = "value" %>

Attributes
Following table lists out the attributes associated with the page directive −
 language: Specifies the scripting language for JSP, with “java” as the default.
 import: Allows for importing Java classes.
Example:
<%@ page language="java" contentType="text/html" import="java.util.Date"
%>
<html>
<body>
<%
// Printing current date using imported Date class
out.println("Current Date: " + new Date());
%>
</body>
</html>

P.K.M.COLLEGE 55
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

In this case:
The page directive imports the Date class.
The content Type is set to text/html, so the response will be an HTML page.
 content Type: Defines the MIME type of the response.
 error Page: Points to an error page for handling exceptions.
 is Error Page: Indicates if this page is an error page.
Example





 session: States whether the session s

 info : This attribute simply sets the information of the JSP page which is retrieved later by
using getServletInfo() method of Servlet interface.
Example
<%@ page info=“Composed by abc” %>

Jsp - Include directive


– The include directive is used to include the contents of any resource it may be jsp file,
html file or text file.
– The include directive includes the original content of the included resource at page
translation time.
– The code of the included file is added to the JSP document.
Following is the basic syntax of include directive-
<%@ include file=“filename” %>
Example:
//header.jsp
<html><body>

<h1><%=new java.util.Date(); %></h1>

</body></html>

//main.jsp
<%@ include file=“header.jsp” %>

<html><body>

The above content is included from header.jsp

</body></html>

P.K.M.COLLEGE 56
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

3) Action elements
– Action element are high level jsp element which are used to create, modify and use
other objects
– Some standard action element in JSP page are as follows
 jsp:include
 jsp:forward
 jsp:param
 jsp:plugin
 jsp:include
The syntax looks like this –
<jsp:include page = "relative URL" flush = "true/false" />
Where,
Page:-Any JSP/HTML file which will be included
Flush:-it is an optional parameter used to flush buffer
Example :jsp:include
//printdate.jsp
<html><body>
<h1><%=new java.util.Date(); %></h1>
</body></html>
//main.jsp
<html><body>
<jsp:include page=“printdate.jsp”/>
<h1>End of main page</h1>
</body></html>

 jsp:forward
The forward action terminates the action of the current page and forwards the request to
another resource such as a static page, another JSP page, or a Java Servlet.
The syntax looks like this –
<jsp:forward page = "Relative URL" />
Example
//printdate.jsp
<html><body>
<h1><%=new java.util.Date(); %></h1>
</body></html>
//main.jsp
<html><body>
<jsp:forward page=“printdate.jsp”/>
<h1>End of main page</h1></body</html>

 jsp:param
This element is used to provide the tag/value pairs of information by including these as
sub-attribute of the <jsp:include> ,<jsp:forward> and the <jsp:pulgin> actions

The syntax looks like this –


<jsp:param name=“pname” value=“pvalue”/>
Where,

P.K.M.COLLEGE 57
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Pname:-is a name of parameter name which is being referenced


pvalue-:-is the value of parameter
Example
<!-- main.jsp -->
<html>
<body>
<h1> Demo of Param tag</h1>
<jsp:forward page="demo.jsp" >
<jsp:param name="color" value="red" />
</jsp:forward>
</body>
</html>
<!-- Demo.jsp -->
<html>
<body>
<%= "<b>Your given color is:"+request.getParameter("color") %>
</body>
</html>
 jsp:plugin
This element is used to embed an applet and java beans with the jsp page .
The tag automatically detects the browser type and insert the appropriate HTML tag
either <embed> or <object> in the output.
The syntax looks like this –
<jsp:plugin type=“plugintype” code=“class filename”
codebase=“url” />

Example
<html>
<head><title>Applet Pulgin Demo</title>
</head>
<body>
<jsp:plugin type="applet" code="Circle1.class" width="300"
height="300">
</jsp:plugin>
</body>
</html>
Circle.java
import java.awt.*;
import java.applet.*;
/*<applet code=Circle1.class
height=500
width=500>
</applet>*/
public class Circle1 extends Applet
{
public void paint(Graphics g)
{
setBackground(Color.white);
Dimension d=getSize();

P.K.M.COLLEGE 58
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

int x=d.width;
int y=d.height;
setForeground(Color.magenta);
g.fillOval(50,50,x-100,y-100);
}
}

 Implicit objects of JSP


– These Objects are the Java objects that the JSP Container makes available to the
developers in each page and the developer can call them directly without being explicitly
declared. JSP Implicit Objects are also called pre-defined variables.
– Following table lists out the nine Implicit Objects that JSP supports –
S.No. Object & Description
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 the 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.
 Request Object :
The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a
client requests a page the JSP engine creates a new object to represent that request.
Examples
//index.html
<form action=”welcome.jsp”>
<input type=”text” name=”uname”>
<input type=”submit” value=”go..”><br>
</form>
//welcome.jsp
<%
String name=request.getParameter(“uname”);
out.print(“welcome”+name);

P.K.M.COLLEGE 59
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

%>

 Response Object :
This is another most important objects which is used in JSP programming. If you want to
generate any output for client, then you can generate it using response object. As Similar to
servlet programming response objects in JSP in belongs to
javax.servlet.http.HttpServletResponse class .

The scope of the objects is page only because it is used to generate output of a particular page.
Examples

//index.html
<form action=”welcome.jsp”>
<input type=”text” name=”uname”>
<input type=”submit” value=”go..”><br>
</form>
//welcome.jsp
<%
String name=sendRedirect(“http://www.google.com”);
%>

 Out Object :
The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to send
content in a response.it is the object of JspWriter.

In case of servlet you need write :


PrintWriter out=response.getWriter();
Examples
<%
// Using Out.print() to send content
out.print("Welcome to Advanced Java Programming");

%>

 Session Object
The session object is an instance of javax.servlet.http.HttpSession. The session object is used
to track client session between client requests.
Examples
//index.html
<form action=”welcome.jsp”>
<input type=”text” name=”uname”>
<input type=”submit” value=”go..”><br>
</form>
//welcome.jsp
<%
String name=request.getParameter(“uname”);
out.print(“welcome, ”+name);
session.setAttribute(“user”,name);

P.K.M.COLLEGE 60
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

<a href=”second.jsp”> Second JSP Page </a>


<%>
//second.jsp
<%
String name=(String)session.getAttribute(“user”);
out.print(“hello,”+name);
%>

 Config Object
This implicit object is similar to servletConfig object of Servlet. Config is created using
javax.servlet.ServletConfig class. This is mainly used to read some initial parameters which
are passed to particular page.

Examples
<body>
<h1>Config Object Demo</h1>
<h2>First Page</h2>

<h3><%= config.getServletName() %></h3>


</body>

 Exception Object
• This object is used to get the information about the exception (runtime errrors).
• This object is exists in java.lang.Throwable class.
//Error.jsp
<%@ page isErrorPage="true" %>

<html>
<body>
<h3>
<%=exception.getMessage() %>exception has been occcured.
</h3>
</body>
</html>

 Application Object
This implicit object is used to set the values and attribute at application level. Application
object of JSP is similar to ServletContext object of Servlet Programming.
Examples
//index.html
<% application.setAttribute("uname","PKM College"); %>
<form action=”welcome.jsp” method=”get”>
<input type=”text” name=”uname”>
<input type=”submit” value=”go..”><br>
</form>
//welcome.jsp
<%
String uname=application.getAttribute("uname").toString();
%>

P.K.M.COLLEGE 61
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

<h2>Username :- &nbsp;&nbsp; <%=uname %></h2>

 Including and Forwarding from JSP Page


1) Include Action :
Include action tag is used for including another resource to the current JSP page. The
included resource can be a static page in HTML, JSP page or Servlet. We can also pass
parameters and their values to the resource which we are including.

Syntax:
<jsp:include page="Relative_URL_Of_Page">
<jsp:param ... />
– When the JSP container translate the page, this include directive causes the indicate
file to be included in that place in the page and become part of the java source file that is
compiled into the JSP Page implementation class; that is , it is included at translation time.
Using the include directive, included file does not need to be a complete and valid JSP Page.
– With the “include” standard action, the JSP file stops processing the current request
and passes the request to the included file. The included file passes its output to the response.
– After that control of the response returns to the calling JSP, which completes further
process of response. The output of included page or servlet is included at request time.
– Components that are include action must be valid JSP pages or servlet.
– The included file is neither allowed to modify the headers of response nor to set
cookies in the response.
– For the include element the page attribute is require and its value is the URL of the
page whose output is included in the response.
Examples
//index.jsp

<html>
<body>
<h2>This is index.jsp Page</h2>
<jsp:include page="display.jsp">
<jsp:param name="name" value="PKM College" />
</jsp:include>
</body>
</html>
//display.jsp
<html>
<body>
<h2>Hello this is a display.jsp Page</h2>
User Name: <%=request.getParameter("name") %>
</body>
</html>

P.K.M.COLLEGE 62
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

2) Forward Action
JSP forward action tag is used for forwarding a request to the another resource (It can be a
JSP, static page such as html or Servlet). Request can be forwarded with or without
parameter.
Syntax:
<jsp:forward page="relative url of this page">
<jsp:param ... />

Examples
//index.jsp
<html>
<body>
<h2>This is index.jsp Page</h2>
<jsp:forward page="display.jsp">
<jsp:param name="name" value="PKM College" />
</jsp:forward>
</body>
</html>

//display.jsp
<html>
<body>
<h2>Hello this is a display.jsp Page</h2>
User Name: <%=request.getParameter("name") %>
</body>
</html>

 Working with Session and Cookie in JSP


Cookie :
– Cookies are nothing but just text files stored on the client's machine, and they are used
for various purposes by various websites.
– JSP also supports HTTP cookies. JSP uses servlet technology for working with
cookies.
Steps involved in Identifying and returning users:
Server scripts send cookies to the browser. Generally, it sends sets of cookies, For
example, age, name, or any other identification number.
The browser stores this information for future use on the local machines.
And from the next time, whenever the browser sends any request to the web server, it
sends those cookies to the server, and it also helps find data in the server.
The structure of the cookie:
Cookies are generally set in the HTTP header. In JSP, the headers which have cookie
looks something like this:

HTTP/1.1 200 OK
Date: Tue, 18 May 2025 13:03:28 GMT
Server: Apache/1.3.9 (UNIX)
Set-Cookie: name = abc; expires = Monday, 19-May-25 22:03:38 GMT;
path = /; domain = abc.com

P.K.M.COLLEGE 63
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Connection: close
Content-Type: text/html

– The Set-Cookie header contains a GMT date, a path, a name-value pair, and a domain, as
you can see in the above example.
– The value and name will be URL encoded. The expire filed instruction tells the browser
to forget the cookie after a particular date and time.
– The browser configured to store cookies will store the cookies until the expiry date. The
browser will resend the cookie to the server when the user points it to any page that
matches the domain and path of the cookie. The browser's header will look something
like this:
GET / HTTP/1.0
User-Agent: Mozilla/4.6 (X1; I; Linux 2.2.6-15apmac ppc)
Connection: Keep-Alive
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name = abc
Types of Cookies and Methods
Broadly, there are two types of cookies:
1. Persistent Cookie: These are the types of cookies available up to a specific time,
even after closing the browser. We have to use the setMaxAge() method to get these cookies.
2. Non-persistent cookie: This means that the data will be deleted as soon as one closes
the browser. By default, we get these cookies.

Servlet Cookie Methods


S.No Method Description
1 Public void This method sets the domain to which cookies apply,
setDomain(string for example, codingninjas.com
pattern)
2 getDomain() It gets the domain of the cookie.
3 setMaxAge(int expiry) It mentions and sets the time for which cookie will
remain. It automatically expires after the session ends.
4 getMaxAge() It returns -1 to the browser if the age of the cookie is
not set. It measures the age of the cookie in seconds. It
will return the name of the cookie.
5 getName() It will return the name of the cookie.
6 getValue() It will get the value of the cookie.
7 setValue(String It will get the value of the cookie.
newValue)
8 setPath(string uri) It will set the path of the cookie and if it is not defined
then it will get applied to all the URIs of the directory.
9 getPath() It will get the path of the associated cookie.
10 setComment(string It gives a message to a cookie so that the user can
purpose) understand its use.
11 getComment() It returns the message of the cookie and if there is no
message it returns NULL.
12 setSecure(Boolean flag) It tells whether the cookie needs to be sent over
encrypted connections or not.

P.K.M.COLLEGE 64
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Working With Cookies in JSP


– We can perform many functions on cookies, but here we will first set up cookies, then
read cookies, and delete cookies.

Setting Cookies with JSP


Setting cookies with JSP involves three steps:

Step 1: Creating a cookie object


You can make a cookie by calling the cookie constructor with the cookie value and name,
both of which are strings.
Cookie cookie = new Cookie(“Key”,” Value”);
Neither the value nor the name contains the white spaces or the following characters.
[]()=,:@?;

Step 2: Setting the maximum age


You can use the setMaxAge() function to specify the validation of the cookie. The time given
is in second like below code is for 12 hours.
cookie.setMaxAge(60*60*12);

Step 3: Sending coolie to the HTTP response headers


You can use response.addCookie function to add cookies in the header of the HTTP response.
response.addCookie(cookie);

Writing Cookie with JSP:


Example
//index.jsp
<%
// here we are creating the cookie with the first_name
Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));
// here we are creating the cookie with the last_name
Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));

// Setting the expiry date after 12 Hrs for both the cookies.
firstName.setMaxAge(60*60*12);
lastName.setMaxAge(60*60*12);

response.addCookie( lastName );
response.addCookie( firstName );
%>
<html>
<head>
<title>Setting Cookies</title>
</head>

<body>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>

P.K.M.COLLEGE 65
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>

</body>
</html>
//hello.jsp
<html>
<body>
<form action = "index.jsp" method = "GET">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>

</body>
</html>

Check the output at http://localhost:8080/hello.jsp.The output of the above form is

Reading Cookies with JSP


– By using the getCookies() method of HttpServletRequest user need to create an array
javax.servlet.http.Cookie for reading cookies. Then cycle through the array and use
getValue() and getName() to access each cookie and its associated value.

Example

Let us read cookies which we have set in previous example:

<html>
<head>
<title>Reading Cookies</title>
</head>
<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%
Cookie cookie = null;
Cookie[] cookies = null;

// Get an array of Cookies associated with this domain

cookies = request.getCookies();
if( cookies != null ){
out.println("<h2> Found Cookies Name and Value</h2>");

P.K.M.COLLEGE 66
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

for (int i = 0; i < cookies.length; i++){


cookie = cookies[i];
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
}
else{
out.println("<h2>No cookies founds</h2>");
}
%>
</body>
</html>
Found Cookies Name and Value
Name : first_name, Value: PKM

Name : last_name, Value: College

Delete Cookie with JSP


To delete cookies is very simple. If you want to delete a cookie then you simply need to
follow up following three steps:
Read an already existing cookie and store it in Cookie object.
Set cookie age as zero using setMaxAge() method to delete an existing cookie.
Add this cookie back into response header.
Session
– HTTP is a "stateless" protocol which means each time a client retrieves a Web page,
the client opens a separate connection to the Web server and the server automatically does not
keep any record of previous client request.
– Still there are following three ways to maintain session between web client and web
server:
Cookies:
A webserver can assign a unique session ID as a cookie to each web client and for subsequent
requests from the client they can be recognized using the received cookie.
This may not be an effective way because many time browser does not support a cookie, so I
would not recommend to use this procedure to maintain the sessions.

Hidden Form Fields:


A web server can send a hidden HTML form field along with a unique session ID as follows:
<input type="hidden" name="sessionid" value="12345">
This entry means that, when the form is submitted, the specified name and value are
automatically included in the GET or POST data. Each time when web browser sends request
back, then session_id value can be used to keep the track of different web browsers.
This could be an effective way of keeping track of the session but clicking on a regular (<A
HREF...>) hypertext link does not result in a form submission, so hidden form fields also
cannot support general session tracking.
URL Rewriting:
You can append some extra data on the end of each URL that identifies the session, and the
server can associate that session identifier with data it has stored about that session.
For example, with http://tutorialspoint.com/file.htm;sessionid=12345, the session identifier is
attached as sessionid=12345 which can be accessed at the web server to identify the client.
URL rewriting is a better way to maintain sessions and works for the browsers when they
don't support cookies but here drawback is that you would have generate every URL
dynamically to assign a session ID though page is simple static HTML page.

P.K.M.COLLEGE 67
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

The session Object:


Apart from the above mentioned three ways, JSP makes use of servlet provided HttpSession
Interface which provides a way to identify a user across more than one page request or visit
to a Web site and to store information about that user.
By default, JSPs have session tracking enabled and a new HttpSession object is instantiated
for each new client automatically. Disabling session tracking requires explicitly turning it off
by setting the page directive session attribute to false as follows:
<%@ page session="false" %>
The JSP engine exposes the HttpSession object to the JSP author through the implicit session
object. Since session object is already provided to the JSP programmer, the programmer can
immediately begin storing and retrieving data from the object without any initialization or
getSession().
Here is a summary of important methods available through session object:
S.N. Method & Description

public Object getAttribute(String name)


1 This method returns the object bound with the specified name in this session, or null if no
object is bound under the name.

public Enumeration getAttributeNames()


2 This method returns an Enumeration of String objects containing the names of all the objects
bound to this session.

public long getCreationTime()


3 This method returns the time when this session was created, measured in milliseconds since
midnight January 1, 1970 GMT.

public String getId()


4
This method returns a string containing the unique identifier assigned to this session.

public long getLastAccessedTime()


5 This method returns the last time the client sent a request associated with this session, as the
number of milliseconds since midnight January 1, 1970 GMT.

public int getMaxInactiveInterval()


6 This method returns the maximum time interval, in seconds, that the servlet container will
keep this session open between client accesses.

public void invalidate()


7
This method invalidates this session and unbinds any objects bound to it.

public boolean isNew(


8 This method returns true if the client does not yet know about the session or if the client
chooses not to join the session.

public void removeAttribute(String name)


9
This method removes the object bound with the specified name from this session.

P.K.M.COLLEGE 68
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

public void setAttribute(String name, Object value)


10
This method binds an object to this session, using the name specified.

public void setMaxInactiveInterval(int interval)


11 This method specifies the time, in seconds, between client requests before the servlet
container will invalidate this session.

Session Tracking Example:


<%@ page import="java.io.*,java.util.*" %>
<%
// Get session creation time.
Date createTime = new Date(session.getCreationTime());
// Get last access time of this web page.
Date lastAccessTime = new Date(session.getLastAccessedTime());

String title = "Welcome Back to my website";


Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
String userID = new String("ABCD");

// Check if this is new comer on your web page.


if (session.isNew()){
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
session.setAttribute(visitCountKey, visitCount);
}
visitCount = (Integer)session.getAttribute(visitCountKey);

visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
session.setAttribute(visitCountKey, visitCount);
%>
<html>
<head>
<title>Session Tracking</title>
</head>
<body>
<center>
<h1>Session Tracking</h1>
</center>
<table border="1" align="center">
<tr bgcolor="#949494">
<th>Session info</th>
<th>Value</th>
</tr>
<tr>
<td>id</td>
<td><% out.print( session.getId()); %></td>
</tr>
<tr>
<td>Creation Time</td>
<td><% out.print(createTime); %></td>
</tr>
<tr>
<td>Time of Last Access</td>
<td><% out.print(lastAccessTime); %></td>
</tr>

P.K.M.COLLEGE 69
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

<tr>
<td>User ID</td>
<td><% out.print(userID); %></td>
</tr>
<tr>
<td>Number of visits</td>
<td><% out.print(visitCount); %></td>
</tr>
</table>
</body>
</html>

Now put above code in main.jsp and try to access http://localhost:8080/main.jsp. It would
display the following result when you would run for the first time:

Welcome to my website

Session Infomation

Session info value


Id 0AE3EC93FF44E3C525B4351B77ABB2D5
Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010
Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010
User ID ABCD
Number of visits 0

Now try to run the same JSP for second time, it would display following result.

Welcome Back to my website

Session Infomation

info type value


Id 0AE3EC93FF44E3C525B4351B77ABB2D5
Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010
Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010
User ID ABCD
Number of visits 1
Deleting Session Data:
When you are done with a user's session data, you have several options:
Remove a particular attribute: You can call public void removeAttribute(String
name) method to delete the value associated with a particular key.

P.K.M.COLLEGE 70
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Delete the whole session: You can call public void invalidate() method to discard an
entire session.
Setting Session timeout: You can call public void setMaxInactiveInterval(int
interval) method to set the timeout for a session individually.
Log the user out: The servers that support servlets 2.4, you can call logout to log the
client out of the Web server and invalidate all sessions belonging to all the users.
web.xml Configuration: If you are using Tomcat, apart from the above mentioned
methods, you can configure session time out in web.xml file as follows.
<session-config>
<session-timeout>15</session-timeout>
</session-config>
The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes in
Tomcat.
The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that session
in seconds. So if your session is configured in web.xml for 15 minutes,
getMaxInactiveInterval( ) returns 900.
 Handling Errors and Exceptions
– Exceptions can be defined as an object that is thrown during a program run. Exception
handling is the practice of handling errors at runtime.
– Exceptions can occur at any time in a web application. Therefore, the web developer
must handle exceptions to be on the safe side and make the user work flawlessly on the web.
– it is an object of java.lang.Throwable class, and is used to print exceptions.
errorPage: Used to site which page to be displayed when exception occurred.
Syntax :
<%@page errorPage="url of the error page"%>

isErrorPage: Used to mark a page as an error page where exceptions are displayed.

Syntax :
<%@page isErrorPage="true"%>

Example :
//main.html
<html>
<head>
<body>
<form action="process.jsp">
Number1:<input type="text" name="first" >
Number2:<input type="text" name="second" >
<input type="submit" value="divide">
</form>
</body>
</html>

// process.jsp
<%@ page errorPage="error.jsp" %>
<%
String num1 = request.getParameter("n1");

P.K.M.COLLEGE 71
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

String num2 = request.getParameter("n2");

int a = Integer.parseInt(num1);
int b = Integer.parseInt(num2);
int c = a / b; // May throw ArithmeticException
if b is 0

out.print("The result of the division is: " + c);


%>
//error.jsp
<%@ page isErrorPage="true" %>

<h3>Oops! Something went wrong.</h3>


<p>Error Details: <%= exception.getMessage() %></p>

-main.html

- error.jsp

 Connectivity of JSP with JDBC


JDBC is an application programming interface between Java programs and database
management systems. JDBC is a core part of the Java platform and is included in the standard
JDK distribution. The purpose of JDBC is to connect database and manipulate the data in
database from a Servlet page or from a JSP page.

Basic Steps to Connect Database


1. Establish a connection.
2. Create JDBC Statements.
3. Execute SQL Statements.
4. Get ResultSet.
5. Close connections.

1. Establish a connection
A connection to MySQL is established by using the package,

import java.sql.*;
Then load the vendor specific driver,
Class.forName(“oracle.jdbc.driver.OracleDriver”);
This code dynamically loads a driver class, for Oracle database.
Make the connection,
Connection conn = DriverManager.getConnection(DB_URL,USER,PASS);
This code establishes connection to database by obtaining a Connection object.

P.K.M.COLLEGE 72
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

2. Create JDBC statement(s)


JDBC statements are created using the following code,
Statement stmt = con.createStatement() ;
This creates a Statement object for sending SQL statements to the database.

3. Executing SQL Statements


SQL statements are executed using the query,
sql = “SELECT attributes FROM Table”;

4. Get ResultSet
The Resultset object is obtained by the executeQuery() function,
ResultSet rs = Stmt.executeQuery(sql);

5. Close Connection
The JDBC connection and SQL query execution is closed by calling the close() function,
con.close();

First we have to create table student of test database with mysql


,Here is code of JDBC with JSP

//JspJDBC.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<table border="1" align="center">
<tr>
<td>Quote</td>
<td>Author</td>
</tr>
<%

try
{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/ShlokDB","r
oot","");
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery("select * from shloka_tbl");
while(rs.next())
{

P.K.M.COLLEGE 73
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

%>
<tr>
<td><%=rs.getString("Quote")%></td>
<td><%=rs.getString("Author")%></td>
</tr>
<%
}
}
catch (Exception e)
{
e.printStackTrace();
}
%>
</table>
</body>
</html>

 Introduction of JavaBean
– JavaBeans are classes that encapsulate many objects into a single object (the bean)
– Their primary goal of a JavaBean is WORA (Write Once Run Anywhere).
– JavaBeans should adhere to portability, reusability and interoperability.
– JavaBeans will look a plain Java class written with getters and setters methods.
– It is a Java class that should follow the following conventions:
1. Must implement Serializable.
2. It should have a public no-arg constructor.
3. All properties in java bean must be private with public getters and setter methods.

Properties for setter methods:


1. It should be public in nature.
2. The return type a should be void.
3. The setter method should be prefixed with the set.
4. It should take some argument i.e. it should not be a no-arg method.

Properties for getter methods:


1. It should be public in nature.
2. The return type should not be void i.e. according to our requirement, return type we
have to give the return type.
3. The getter method should be prefixed with get.
4. It should not take any argument.

JavaBean properties are accessed through two methods in the JavaBean's


implementation class:
Method Description

For example, if property name is firstName, your method


getPropertyName() name would be getFirstName() to read that property. This
method is called accessor.

P.K.M.COLLEGE 74
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

For example, if property name is firstName, your method


setPropertyName() name would be setFirstName() to write that property. This
method is called mutator.

A read-only attribute will have only a getPropertyName() method, and a write-only


attribute will have only a setPropertyName() method.

Accessing JavaBeans Properties


– Along with <jsp:useBean...> action, you can use the <jsp:getProperty/> action to
access the get methods and the <jsp:setProperty/> action to access the set methods. Here is
the full syntax −
<jsp:useBean id = "id" class = "bean's class" scope = "bean's
scope">
<jsp:setProperty name = "bean's id" property = "property
name"
value = "value"/>
<jsp:getProperty name = "bean's id" property = "property
name"/>
...........
</jsp:useBean>

– The name attribute references the id of a JavaBean previously introduced to the JSP
by the useBean action. The property attribute is the name of the get or the set methods that
should be invoked.
– Following example shows how to access the data using the above syntax –
Let's create a simple Java web application that uses JavaBeans to manage and display data
related to Yoga Asanas
// AsanaBean.java
<html>
<head>
<title>get and set properties Example</title>
</head>
<body>
<jsp:useBean id = "asana" class ="mypack.AsanaBean">
</jsp:useBean>
<jsp:setProperty name="asana" property="name" value="Tree
Pose" />

<jsp:setProperty name="asana" property="category"


value="Standing" />

<jsp:setProperty name="asana" property="sanskritName"


value="Vrikshasana" />

<jsp:setProperty name="asana" property="benefits"


value="Improves balance and posture" />

P.K.M.COLLEGE 75
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

<p> Asana Name::


<jsp:getProperty name="asana" property="name"/>
</p>
<p>Category Name::
<jsp:getProperty name="asana" property="category"/>
</p>
<p>Sanskrit Name::
<jsp:getProperty name="asana" property="sanskritName"
</p>
<p>Benefit::
<jsp:getProperty name="asana" property="benefits"
</p>
</body>
</html>

Output : This would be produce following result:

Asana Name:: Tree Pose


Category Name:: Standing
Sanskrit Name:: Vrikshasana
Benefit:: Improves balance and posture

4 MVC,EJB & Frameworks

 Introduction to MVC
– The Model-View-Controller (MVC) framework is an architectural/design pattern that
separates an application into three main logical components Model, View, and Controller.
– Each architectural component is built to handle specific development aspects of an
application. It isolates the business logic and presentation layer from each other.
– It was traditionally used for desktop graphical user interfaces (GUIs). Nowadays,
MVC is one of the most frequently used industry-standard web development frameworks to
create scalable and extensible projects.
– It is also used for designing mobile apps.
– The main goal of this design pattern was to solve the problem of users controlling a
large and complex data set by splitting a large application into specific sections that all have
their own purpose.
Key Features of MVC:
Modularity:
The application is divided into independent modules, promoting code organization and
reusability.
Reusability:
Components can be reused in different parts of the application or even in other projects.

P.K.M.COLLEGE 76
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Testability:
Individual components can be tested in isolation, simplifying the testing process.
Flexibility:
Components can be modified or replaced without significantly affecting the other parts of the
application.
Parallel Development:
Different teams can work on different components simultaneously, accelerating
development.
Scalability and Maintainability:
The structured approach of MVC makes it easier to scale and maintain applications as they
grow.
MVC Components

 Controller:
– The controller is the component that enables
the interconnection between the views and the
model so it acts as an intermediary. The
controller doesn’t have to worry about
handling data logic, it just tells the model what
to do. It processes all the business logic and
incoming requests, manipulates data using the
Model component, and interact with the View
to render the final output.

Responsibilities:
Receiving user input and interpreting it.
Updating the Model based on user actions.
Example:
– In a bookstore application, the Controller would handle actions such as searching for
a book, adding a book to the cart, or checking out.

 View:
– The View component is used for all the UI logic of the application. It generates a user
interface for the user.
– Views are created by the data which is collected by the model component but these
data aren’t taken directly but through the controller. It only interacts with the controller.
Responsibilities:
Displaying the user interface elements.
Example:
In a bookstore application, the View would display the list of books, book details, and
provide input fields for searching or filtering books.

 Model:
– Model domain contains the business logics and functions that manipulate the
business data.
– It provides updated information to view domain and also gives response to query And
the controller can access the functionality which is encapsulated in the model.
Responsibilities:
Managing data: CRUD (Create, Read, Update, Delete) operations.

P.K.M.COLLEGE 77
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Example:
In a bookstore application, the Model would handle data related to books, such as the book
title, author, price, and stock level.

 Implementation of MVC Architecture


In this Example , we are using Servlet as a Controller, JSP as a View component, and
JavaBean class as a Model.
Index.jsp a page that gets input from the user.
ControllerServlet.java a servlet that act as a controller.
Login-success.jsp and login-error.jsp file act as a view component.
Web.xml file for mapping the servlet.

 Introduction of EJB
– EJB stands for Enterprise Java Beans.
– EJB is an essential part of a J2EE platform.
– EJB id reusable server-side software component.
– EJB facilitates the distributed java applications, providing an object oriented
transactional environment for building distributed, multi tier enterprise components.
– The primary goal of EJB is WORA(Write Once Run Anywhere).
– EJB application is deployed on the server, so it is called server side component.
– J2EE platform have component based architecture to provide multi-tiered, distributed
and highly transactional features to enterprise level applications.
– EJB provides an architecture to develop and deploy component based enterprise
applications considering robustness, high scalability and high performance.
– An EJB application can be deployed on any of the application server compliant with
J2EE 1.3 standard specification.It provides a default, no-argument constructor.

 Benefits of EJB
– Simplified development of large scale enterprise level application.
– Application Server/ EJB container provides most of the system level services like
transaction handling, logging, load balancing, persistence mechanism, exception handling
and so on. Developer has to focus only on business logic of the application.

P.K.M.COLLEGE 78
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

– EJB container manages life cycle of ejb instances thus developer needs not to worry
about when to create/delete ejb objects.
– Simplicity
– Application portability
– Component reusability
– Ability to build complex application
– Sepration of business logic and presentation logic
– Deployment in many operating environments

 Types of EJB
There are three types of EJB:
1) Session Beans,
2) Entity Beans,
3) Message-driven beans
Session Bean:
Session bean contains business logic that can be invoked by local, remote or webservice
client.
There are two types of session beans:
(i) Stateful session bean and (ii) Stateless session bean.

(i) Stateful Session bean :


Stateful session bean performs business task with the help of a state. Stateful session bean can
be used to access various method calls by storing the information in an instance variable.
Some of the applications require information to be stored across separate method calls. In a
shopping site, the items chosen by a customer must be stored as data is an example of stateful
session bean.

(ii) Stateless Session bean :


Stateless session bean implement business logic without having a persistent storage
mechanism, such as a state or database and can used shared data. Stateless session bean can
be used in situations where information is not required to used across call methods.

2)Entity Bean
customers, orders, and products. In the Application Server, the persistent storage
mechanism is a relational database.
Typically, each entity bean has an underlying table in a relational database, and each
instance of the bean corresponds to a row in that table.

3) Message Driven Bean


A message-driven bean is an enterprise bean that allows Java EE applications to process
messages asynchronously. This type of bean normally acts as a JMS message listener, which
is similar to an event listener but receives JMS messages instead of events.
The messages can be sent by any Java EE component (an application client, another
enterprise bean, or a web component) or by a JMS application or system that does not use
Java EE technology.
Message-driven beans can process JMS messages or other kinds of messages.
Message-driven beans have the following characteristics.
 They execute upon receipt of a single client message.
 They are invoked asynchronously.

P.K.M.COLLEGE 79
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

 They are relatively short-lived.


 They do not represent directly shared data in the database, but they can access and
update this data.
 They can be transaction-aware.
 They are stateless.
 Introduction to hibernate
– Hibernate is a powerful, high-performance, object-relational mapping (ORM)
framework for Java.
– It simplifies the development of Java applications to interact with databases by
mapping Java objects to database tables.
– Hibernate is an open-source ORM tool developed by Gavin King in 2001.
– It is used to persist Java objects in a relational database without writing complex SQL
queries.
– Hibernate is a high-performance Object/Relational persistence and query service,
which is licensed under the open source GNU Lesser General Public License (LGPL) and is
free to download.
– Hibernate not only takes care of the mapping from Java classes to database tables (and
from Java data types to SQL data types), but also provides data query and retrieval facilities.

 Features of Hibernate Framework


Here are the key features of Hibernate framework:
1. Object-Relational Mapping (ORM)
– Maps Java objects to database tables, eliminating the impedance mismatch between
object-oriented and relational models.
– Supports complex mappings, including one-to-one, one-to-many, many-to-one, and
many-to-many relationships.

2. Simplified CRUD Operations


– Provides a simple and intuitive API for performing CRUD (Create, Read, Update,
Delete) operations.
– Supports batch updates and deletes for improved performance.
3. Database Vendor Independence
– Supports a wide range of databases, including Oracle, MySQL, PostgreSQL,
Microsoft SQL Server, and more.
– Allows for easy switching between different database vendors.
4. Lazy Loading
– Loads related objects only when needed, reducing memory usage and improving
performance.
– Supports lazy loading of collections and single objects.
5. Caching
– Provides a caching mechanism to reduce the number of database queries.
– Supports first-level cache (session cache) and second-level cache (application cache)
6. Query Language
– Provides a powerful query language, HQL (Hibernate Query Language), which allows
for flexible and efficient querying of the database.
– Supports querying of objects, collections, and scalar values.
7. Criteria API
– Provides API for querying the database.
– Supports querying of objects, collections, and scalar values.

P.K.M.COLLEGE 80
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

8. Native SQL Support


– Supports native SQL queries, allowing for direct access to the database.
– Supports stored procedures and functions.
9. Transaction Management
– Supports transaction management, which allows for atomicity and consistency of
database operations.
– Supports declarative transaction management using annotations.
10. Automatic Schema Generation
– Supports automatic schema generation, which allows for easy creation and
modification of database schemas.

 Hibernate architecture
– The Hibernate architecture is layered to keep you isolated from having to know the
underlying APIs.
– Hibernate makes use of the database and configuration data to provide persistence
services (and persistent objects) to the application.
– Following is a detailed view of the Hibernate Application Architecture with few
important core classes.

– Hibernate uses various existing Java APIs, like JDBC, Java Transaction
API(JTA), and Java Naming and Directory Interface (JNDI).

– JDBC provides a rudimentary level of abstraction of functionality common to


relational databases, allowing almost any database with a JDBC driver to be supported by
Hibernate. JNDI and JTA allow Hibernate to be integrated with J2EE application servers.
– Following section gives brief description of each of the class objects
involved in Hibernate Application Architecture.
Configuration:

P.K.M.COLLEGE 81
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

– Configuration is a class which is present in org.hibernate.cfg package. It activates


Hibernate framework. It reads both configuration file and mapping files.
It activate Hibernate Framework
Configuration cfg=new Configuration();
It read both cfg file and mapping files
cfg.configure();
– It checks whether the config file is syntactically correct or not.
– If the config file is not valid then it will throw an exception. If it is valid then it
creates a meta-data in memory and returns the meta-data to object to represent the config file.

SessionFactory:
SessionFactory is an Interface which is present in org.hibernate package and it is used
to create Session Object.
It is immutable and thread-safe in nature.
buildSessionFactory() method gathers the meta-data which is in the cfg Object.
From cfg object it takes the JDBC information and create a JDBC Connection.
SessionFactory factory=cfg.buildSessionFactory();

Session:
Session is an interface which is present in org.hibernate package. Session object is
created based upon SessionFactory object i.e. factory.
It opens the Connection/Session with Database software through Hibernate
Framework.
It is a light-weight object and it is not thread-safe.
Session object is used to perform CRUD operations.
Session session = factory.openSession();
openSession() is a method provided by the SessionFactory that creates and returns a new
Session instance. This session is not bound to any transaction or context and is independent
of any ongoing transactions in the application.
We can also use getCurrentSession, that returns a Session bound to the current context, which
is usually managed by a transaction manager or a framework like Spring.
Session session = sessionFactory.getCurrentSession();

Transaction:
Transaction object is used whenever we perform any operation and based upon that
operation there is some change in database.
Transaction object is used to give the instruction to the database to make the changes
that happen because of operation as a permanent by using commit() method.
Transaction tx=session.beginTransaction();
tx.commit();

Query:
Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data
from the database and create objects.
A Query instance is used to bind query parameters, limit the number of results
returned by the query, and finally to execute the query.

 Hibernate configuration file


Hibernate requires to know in advance where to find the mapping information that defines
how your Java classes relate to the database tables. Hibernate also requires a set of

P.K.M.COLLEGE 82
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

configuration settings related to database and other related parameters. All such information
is usually supplied as a standard Java properties file called hibernate.properties, or as an
XML file named hibernate.cfg.xml.

I will consider XML formatted file hibernate.cfg.xml to specify required Hibernate properties
in my examples. Most of the properties take their default values and it is not required to
specify them in the property file unless it is really required. This file is kept in the root
directory of your application's classpath.
Hibernate Properties
– Following is the list of important properties, you will be required to configure for a
databases in a standalone situation –
Sr.No. Properties & Description

hibernate.dialect
1 This property makes Hibernate generate the appropriate SQL for the
chosen database.

hibernate.connection.driver_class
2
The JDBC driver class.

hibernate.connection.url
3
The JDBC URL to the database instance.

hibernate.connection.username
4
The database username.

hibernate.connection.password
5
The database password.

hibernate.connection.pool_size
6 Limits the number of connections waiting in the Hibernate database
connection pool.

hibernate.connection.autocommit
7
Allows autocommit mode to be used for the JDBC connection.
If you are using a database along with an application server and JNDI, then you would have
to configure the following properties −
Sr.No. Properties & Description
1 hibernate.connection.datasource
The JNDI name defined in the application server context, which
you are using for the application.
2 hibernate.jndi.class
The InitialContext class for JNDI.
3 hibernate.jndi.<JNDIpropertyname>
Passes any JNDI property you like to the JNDI InitialContext.
4 hibernate.jndi.url
Provides the URL for JNDI.
5 hibernate.connection.username
The database username.

P.K.M.COLLEGE 83
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

6 hibernate.connection.password
The database password.

Hibernate with MySQL Database(configuration file)


MySQL is one of the most popular open-source database systems available today. Let us
create hibernate.cfg.xml configuration file and place it in the root of your application's
classpath. You will have to make sure that you have testdb database available in your
MySQL database and you have a user test available to access the database.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.3//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property
name="dialect">org.hibernate.dialect.MySQL8Dialect
</property>
<property
name="connection.url">jdbc:mysql://localhost/test
</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property
name="connection.driver_class">com.mysql.cj.jdbc.Driver
</property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>

 Hibernate mapping files


– An Object/relational mappings are usually defined in an XML document. This
mapping file instructs Hibernate how to map the defined class or classes to the database
tables?
– Though many Hibernate users choose to write the XML by hand, but a number of
tools exist to generate the mapping document. These include XDoclet, Middlegen and
AndroMDA for the advanced Hibernate users.
– There would be one table corresponding to each object you are willing to provide
persistence.
– Let us consider our previously defined POJO class whose objects will persist in the
table defined in next section.
public class Employee {
private int id;
private String firstName;
private String lastName;
public Employee() {}

public Employee(String fname, String lname) {

P.K.M.COLLEGE 84
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

this.firstName = fname;
this.lastName = lname;
}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName( String first_name ) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName( String last_name ) {
this.lastName = last_name;
}
}
– Consider above objects need to be stored and retrieved into the following RDBMS
table

create table EMPLOYEE (


id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);
Based on the two above entities, we can define following mapping file, 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>

P.K.M.COLLEGE 85
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

<property name = "firstName" column = "first_name" type =


"string"/>
<property name = "lastName" column = "last_name" type =
"string"/>

</class>
</hibernate-mapping>

The mapping document is an XML document having <hibernate-mapping> as the


root element, which contains all the <class> elements.
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.
The <meta> element is optional element and can be used to create the class
description.
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.
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.
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.
 Example of hibernate
Here, we are going to create a simple example of hibernate application using Netbeans IDE.
For creating the first hibernate application in Netbeans IDE, we need to follow following
steps:

1. Create the java project


2. Create the Persistent class
3. Create the mapping file for Persistent class
4. Create the Configuration file
5. Create the class that retrieves or stores the persistent object
6. Run the application
First we have to create new project  java webapplication select Hibernate4.3.1
framework finish

1) Create persistence class(create POJO class)


//Employee.java
public class Employee {
private int id;
private String firstName;
private String lastName;
private int salary;

public Employee() {}

P.K.M.COLLEGE 86
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

public Employee(String fname, String lname, int salary) {


this.firstName = fname;
this.lastName = lname;
this.salary = salary;
}
public int getId() {
return id;
}
public void setId( int id ) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName( String first_name ) {
this.firstName = first_name;
}
public String getLastName() {
return lastName;
}
public void setLastName( String last_name ) {
this.lastName = last_name;
}
public int getSalary() {
return salary;
}
public void setSalary( int salary ) {
this.salary = salary;
}
}

2) Create database table(MySql)


create table EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) NULL,
last_name VARCHAR(20) NULL,
salary INT NULL,
PRIMARY KEY (id)
);

3) Create mapping file for persistence class


//employee.hbm.xml
<?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>

P.K.M.COLLEGE 87
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

<id name = "id" type = "int" column = "id">


<generator class="native"/>
</id>

<property name = "firstName" column = "first_name" type =


"string"/>
<property name = "lastName" column = "last_name" type =
"string"/>
<property name = "salary" column = "salary" type = "int"/>

</class>
</hibernate-mapping>

4) Create configuration file


//hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration
DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property
name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/info</property>
<property name="hibernate.connection.username">root</property>
<mapping resource="mypack/Hdemo.hbm.xml"/>
</session-factory>
</hibernate-configuration>

5) Create the class that retrieves or stores the persistent object


//EmployeeServlet.java
package mypack;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class Insert extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");

P.K.M.COLLEGE 88
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

String Firstname,Lastname;
int Salary;
Firstname =request.getParameter("Firstname");
Lastname =request.getParameter("Lastname ");
Salary =Integer.parseInt(request.getParameter("Salary "));
SessionFactory sf=(SessionFactory) new
Configuration().configure().buildSessionFactory();
Session s=sf.openSession();
Transaction tr=s.beginTransaction();
Employee e1=new Employee();
e1.setFirstName("Mickey");
e1.setLastName("Mouse");
e1.setSalary(“20000”);

s.persist(h);
tr.commit();
s.close();
System.out.println("inserted");
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<body>");
out.println("<h1>Servlet Insert at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}

7) Run the application

 Hibernate Annotations
– We can create hibernate application with annotation.
– Following are the annotation that can be used to create Hibernate application such as
@Entity, @Id, @Table etc.
– It belongs to the javax.persistance.* package.
– We have to use Hibernate Anotation starting with @.

Consider we are going to use the following VEDAS table to store our objects −

create table VEDAS (


id INT NOT NULL auto_increment,
veda_name VARCHAR(20) default NULL,
PRIMARY KEY (id)
);

Following is the mapping of VEDAS class with annotations to map objects with the defined
VEDA table –

P.K.M.COLLEGE 89
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

import javax.persistence.*;

@Entity
@Table(name = " VEDAS")
public class Veda{
@Id @GeneratedValue
@Column(name = "id")
private int id;

@Column(name = "veda_name")
private String vedaName;

public Veda() {}

public int getId() {


return id;
}

public void setId( int id ) {


this.id = id;
}

public String getVedaName() {


return vedaName;
}

public void setVedaName( String veda_name ) {


this.vedaName = veda_name;
}

}
Following section will explain the annotations used in the above class.

@Entity Annotation

The EJB 3 standard annotations are contained in the javax.persistence package, so we


import this package as the first step. Second, we used the @Entity annotation to the VEDA
class, which marks this class as an entity bean, so it must have a no-argument constructor that
is visible with at least protected scope.

@Table Annotation

The @Table annotation allows you to specify the details of the table that will be used to
persist the entity in the database.

The @Table annotation provides four attributes, allowing you to override the name of the
table, its catalogue, and its schema, and enforce unique constraints on columns in the table.
For now, we are using just table name, which is VEDAS.

@Id and @GeneratedValue Annotations

P.K.M.COLLEGE 90
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Each entity bean will have a primary key, which you annotate on the class with
the @Id annotation. The primary key can be a single field or a combination of multiple fields
depending on your table structure.

By default, the @Id annotation will automatically determine the most appropriate primary
key generation strategy to be used but you can override this by applying
the @GeneratedValue annotation, which takes two parameters strategy and generator that
I'm not going to discuss here, so let us use only the default key generation strategy. Letting
Hibernate determine which generator type to use makes your code portable between different
databases.

@Column Annotation

The @Column annotation is used to specify the details of the column to which a field or
property will be mapped. You can use column annotation with the following most commonly
used attributes −

name attribute permits the name of the column to be explicitly specified.


length attribute permits the size of the column used to map a value particularly for a
String value.
nullable attribute permits the column to be marked NOT NULL when the schema is
generated.
unique attribute permits the column to be marked as containing only unique values.
 Hibernate Inheritance
The inheritance hierarchy can be seen easily in the table of the database. In Hibernate we
have three different strategies available for Inheritance Mapping
– Table Per Hierarchy
– Table Per Concrete class
– Table Per Subclass

 Hibernate - @Inheritance Annotation


– The @Inheritance annotation in JPA is used to specify the inheritance relation
between two entities.
– It is used to define how the data of the entities in the hierarchy should be stored in the
database.
– The @Inheritance annotation provides us with benefits to reduce code complexity by
creating a base class and inheriting other classes from the base class.
– The @Inheritance annotation is applied to the root entity class to define the
inheritance strategy.
– There are different types of strategies available for Inheritance annotation which
are as follows:
1. Single Table Inheritance Strategy.
2. Joined Inheritance Strategy.
3. Table Per Class Inheritance Strategy.
Example for Single Table Inheritance Strategy:
// on the below line creating an entity for Student
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)

P.K.M.COLLEGE 91
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

@DiscriminatorColumn(name = "entity_type",
discriminatorType
= DiscriminatorType.STRING)
public class Student {
// on the below line creating a field for id which we
// are annotating with @Id.
@Id
private int id;
// on the below line creating a field for the student
// name.
private String studentName;
}
// on the below line creating a separate entity for boys in
// the group of students.
@Entity
// on the below line specifying the discriminator value as
// boy.
@DiscriminatorValue("BOY")
// on the below line creating a class for boy and extending
// it with Student
public class Boy extends Student {
// Define Boys-specific properties in this class.
}
@Entity
// on the below line specifying the discriminator value as
// girl.
@DiscriminatorValue("GIRL")
// on the below line creating a class for girl and extending
// it with Student
public class Girl extends Student {
// Define Girls-specific properties in this class.
}
 Introduction to spring framework
– Spring Framework is a Java platform that provides comprehensive infrastructure
support for developing Java applications. Spring handles the infrastructure so you can focus
on your application.
– Spring framework is an open source Java platform and it was initially written by Rod
Johnson and was first released under the Apache 2.0 license in June 2003.
– Spring is lightweight when it comes to size and transparency. The basic version of
spring framework is around 2MB.
– The core features of the Spring Framework can be used in developing any Java
application, but there are extensions for building web applications on top of the Java EE
platform.
– Spring is not just a framework for building web applications but also an entire
ecosystem that includes components for dependency injection, transaction management, AOP
(Aspect-Oriented Programming), and much more.
– Its modularity means that developers can choose what parts of the framework to use
based on project needs.
 Spring framework architecture
– spring could potentially be a one-stop shop for all your enterprise applications,
however, Spring is modular, allowing you to pick and choose which modules are applicable
to you, without having to bring in the rest.

P.K.M.COLLEGE 92
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

– The Spring Framework provides about 20 modules which can be used based on an
application requirement.

Core Container
The Core Container consists of the Core, Beans, Context, and Expression Language modules
the details of which are as follows −
The Core module provides the fundamental parts of the framework, including the IoC
and Dependency Injection features.
The Bean module provides BeanFactory, which is a sophisticated implementation of
the factory pattern.
The Context module builds on the solid base provided by the Core and Beans
modules and it is a medium to access any objects defined and configured. The
ApplicationContext interface is the focal point of the Context module.
The SpEL module provides a powerful expression language for querying and
manipulating an object graph at runtime.

Data Access/Integration
The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and Transaction
modules whose detail is as follows −
The JDBC module provides a JDBC-abstraction layer that removes the need for
tedious JDBC related coding.
The ORM module provides integration layers for popular object-relational mapping
APIs, including JPA, JDO, Hibernate, and iBatis.
The OXM module provides an abstraction layer that supports Object/XML mapping
implementations for JAXB, Castor, XMLBeans, JiBX and XStream.
The Java Messaging Service JMS module contains features for producing and
consuming messages.
The Transaction module supports programmatic and declarative transaction

P.K.M.COLLEGE 93
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

management for classes that implement special interfaces and for all your POJOs.

Web
The Web layer consists of the Web, Web-MVC, Web-Socket, and Web-Portlet modules the
details of which are as follows −
The Web module provides basic web-oriented integration features such as multipart
file-upload functionality and the initialization of the IoC container using servlet listeners and
a web-oriented application context.
The Web-MVC module contains Spring's Model-View-Controller (MVC)
implementation for web applications.
The Web-Socket module provides support for WebSocket-based, two-way
communication between the client and the server in web applications.
The Web-Portlet module provides the MVC implementation to be used in a portlet
environment and mirrors the functionality of Web-Servlet module.

Miscellaneous
There are few other important modules like AOP, Aspects, Instrumentation, Web and Test
modules the details of which are as follows −
The AOP module provides an aspect-oriented programming implementation allowing
you to define method-interceptors and pointcuts to cleanly decouple code that implements
functionality that should be separated.
The Aspects module provides integration with AspectJ, which is again a powerful and
mature AOP framework.
The Instrumentation module provides class instrumentation support and class loader
implementations to be used in certain application servers.
The Messaging module provides support for STOMP as the WebSocket sub-protocol
to use in applications. It also supports an annotation programming model for routing and
processing STOMP messages from WebSocket clients.
The Test module supports the testing of Spring components with JUnit or TestNG
frameworks.

 Spring & MVC


– The Spring Web MVC framework provides Model-View-Controller (MVC)
architecture and ready components that can be used to develop flexible and loosely coupled
web applications.
– The MVC pattern results in separating the different aspects of the application (input
logic, business logic, and UI logic), while providing a loose coupling between these elements.
The Model encapsulates the application data and in general they will consist of
POJO.
The View is responsible for rendering the model data and in general it generates
HTML output that the client's browser can interpret.
The Controller is responsible for processing user requests and building an
appropriate model and passes it to the view for rendering.

Step 1: First request will be received by DispatcherServlet


Step 2: DispatcherServlet will take the help of HandlerMapping and get to know the
Controller class name associated with the given request

P.K.M.COLLEGE 94
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

The Spring Web model-view-controller (MVC) framework is designed around a


DispatcherServlet that handles all the HTTP requests and responses. The request processing
workflow of the Spring Web MVC DispatcherServlet is illustrated in the following diagram:

Following is the sequence of events corresponding to an incoming HTTP request to


DispatcherServlet:
1. After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to
call the appropriate Controller.
2. The Controller takes the request and calls the appropriate service methods based on
used GET or POST method. The service method will set model data based on defined
business logic and returns view name to the DispatcherServlet.
3. The DispatcherServlet will take help from ViewResolver to pickup the defined view
for the request.
4. Once view is finalized, The DispatcherServlet passes the model data to the view
which is finally rendered on the browser.
Step 3: So request transfer to the Controller, and then controller will process the request by
executing appropriate methods and returns ModeAndView object (contains Model data and
View name) back to the DispatcherServlet

Step 4: Now DispatcherServlet send the model object to the ViewResolver to get the actual
view page

Step 5: Finally DispatcherServlet will pass the Model object to the View page to display the
result

 Understanding Struts Framework


– Struts is an open-source web application framework developed by Apache Software
Foundation, it is used to create a web application based on servlet and JSP.
– It depends on the MVC (Model View Controller) framework. Struts are thoroughly
useful in building J2EE (Java 2 Platform, Enterprise Edition) applications because struts take
advantage of J2EE design patterns.
– It is a free open source framework, used to create java web application.
– It is differ from because it provides dynamic response.
– Web application based on JSP includes database code, page design, and control flow
together. these type of larger applications sometimes become difficult to maintain.
– We can separate these code by using MVC architecture.

P.K.M.COLLEGE 95
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

– The strut framework is designed to help developers create web applications that
utilize MVC architecture.

Here's a more detailed look at some key features:


MVC Architecture:
– Struts provides a ready-made MVC (Model-View-Controller) framework, eliminating
the need for developers to build their own.

Easy Configuration:
– Struts has a simple configuration, making it easier to set up and manage.
Built-in Features:
– It includes features like input validation, error handling, and internationalization
support.
Pluggable Result Types:
– Struts can be plugged with various result types, such as JSP, Freemaker, AJAX, and
Velocity.
Plugins:
– Struts supports various plugins that extend its functionality, including those for client-
side validation, page composition, and localization.
REST Support:
– Struts has a REST plugin for creating REST-based actions with extension-less URLs.
Dependency Injection:
– It integrates well with the Spring framework, enabling dependency injection.
AJAX Support:
– Struts supports AJAX functionality through plugins, allowing for more dynamic and
interactive user interfaces.

 Struts Flow of Control


From a high level, Struts2 is a pull-MVC (or MVC2) framework. The Model-ViewController
pattern in Struts2 is implemented with the following five core components –
Actions
Interceptors : It perform task such as logging, validation, file upload, etc. Request is
generated by user and sent servlet container.

Value Stack / OGNL : The object graph navigation language(ONGL) is powerfull


expression language that is used to reference and manipulate data on the value stack. ONGL
also help in data transfer and type conversion.

Results / Result types

View technologies
truts 2 is slightly different from a traditional MVC framework, where the action takes the role
of the model rather than the controller, although there is some overlap.

P.K.M.COLLEGE 96
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

The above diagram depicts the Model, View and Controller to the Struts2 high level
architecture.
The controller is implemented with a Struts2 dispatch servlet filter as well as interceptors,
this model is implemented with actions, and the view is a combination of result types and
results.
The value stack and OGNL provides common thread, linking and enabling integration
between the other components.
Apart from the above components, there will be a lot of information that relates to
configuration. Configuration for the web application, as well as configuration for actions,
interceptors, results, etc.

P.K.M.COLLEGE 97
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE

Questions Bank-2025
Unit-1

1. Explain JDBC architecture


2. Explain J2EE APIs in brief.
3. Explain Container.
4. Explain Types of JDBC Driver.
5. Describe JDBC API for Database Connectivity
(Connection, Driver Manager, Statement, PreparedStatement, CallableStatement)
6. Write a jdbc program to accept Id, Tithi, Nakshtra and Weekday from user and
insert into Panchang_data table.
7. Explain N-Tier Architecture
8. Explain database meta data with suitable example.

Unit-2

1. Demonstrate architecture of servlet.


2. Explain servlet life cycle
3. Explain HttpServlet Request and HttpServlet Response.
4. Demonstrate of Session Tracking Approaches.
5. Explain Servlet with JDBC.
6. Explain RMI architecture.

Unit-3

1. explain JSP architecture.


2. explain life cycle of JSP.
3. explain JSP elements.
4. explain JSP action element with example.
5. Explain Cookie in JSP.
6. Explain working with session in JSP.
7. Explain error handling in JSP.
8. What is JavaBean? explain JavaBean Properties.

Unit-4

1. Explain MVC Architecture.


2. Explain Types of Enterprise JavaBean.
3. Explain Hibernate Architecture in detail.
4. Explain annotation in hibernate.
5. Explain Hibernate Configuration file and mapping file.
6. Demonstrate spring architecture.
7. Explain flow of control of Struts.

P.K.M.COLLEGE 98

You might also like