J2ee 1
J2ee 1
SEM – 5
INDEX
Sr. No. Subject Name Page No.
Course Objectives:
P.K.M.COLLEGE 1
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE
Course Contents
UNIT Hours
P.K.M.COLLEGE 2
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE
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
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
P.K.M.COLLEGE 6
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE
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.
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.
P.K.M.COLLEGE 11
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE
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
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.*;
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()
Method Description
P.K.M.COLLEGE 17
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE
P.K.M.COLLEGE 18
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE
try {
// Load JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
} 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();
}
}
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.
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
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.
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
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.
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).
Methods :
getConnection(String url):
Attempts to establish a connection with the given URL.
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 :-
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.
P.K.M.COLLEGE 25
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE
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.
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();
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.*;
P.K.M.COLLEGE 27
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE
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 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
// 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
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
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
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.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
P.K.M.COLLEGE 37
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE
// WelcomeServlet.java
// Get data from rewritten URL
String username = request.getParameter("user");
out.println("<h2>Welcome, " + username + "!</h2>");
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.
Example :
// CreateYogaCookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Create cookie
Cookie yogaCookie = new Cookie("Yoga Routine", yogaRoutine);
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.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
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
P.K.M.COLLEGE 41
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE
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.
Session Infomation
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
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
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.
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 –
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;
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.
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:
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.
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
Servlet 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.
It does not have inbuilt implicit In JSP there are inbuilt implicit objects.
objects.
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 )
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 −
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.
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) {
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() {
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" %>
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
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” %>
</body></html>
//main.jsp
<%@ include file=“header.jsp” %>
<html><body>
</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
P.K.M.COLLEGE 57
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE
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);
}
}
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.
%>
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
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>
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
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>
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.
P.K.M.COLLEGE 64
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE
// 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>
Example
<html>
<head>
<title>Reading Cookies</title>
</head>
<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%
Cookie cookie = null;
Cookie[] cookies = null;
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
P.K.M.COLLEGE 67
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE
P.K.M.COLLEGE 68
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE
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
Now try to run the same JSP for second time, it would display following result.
Session Infomation
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
int a = Integer.parseInt(num1);
int b = Integer.parseInt(num2);
int c = a / b; // May throw ArithmeticException
if b is 0
-main.html
- error.jsp
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
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();
//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.
P.K.M.COLLEGE 74
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE
– 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" />
P.K.M.COLLEGE 75
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE
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.
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.
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.
P.K.M.COLLEGE 79
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE
P.K.M.COLLEGE 80
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE
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).
P.K.M.COLLEGE 81
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE
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.
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-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>
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
<hibernate-mapping>
<class name = "Employee" table = "EMPLOYEE">
P.K.M.COLLEGE 85
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE
</class>
</hibernate-mapping>
public Employee() {}
P.K.M.COLLEGE 86
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE
<hibernate-mapping>
<class name = "Employee" table = "EMPLOYEE">
P.K.M.COLLEGE 87
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE
</class>
</hibernate-mapping>
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;
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>");
}
}
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 −
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() {}
}
Following section will explain the annotations used in the above class.
@Entity Annotation
@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.
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 −
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.
P.K.M.COLLEGE 94
B.C.A. SEM – 5 ADVANCE JAVA AND J2EE
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
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.
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.
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
Unit-2
Unit-3
Unit-4
P.K.M.COLLEGE 98