0% found this document useful (0 votes)
31 views395 pages

Web Based Java All PPts Infoway

The document provides an overview of Java EE, its components, and the need for Java EE in developing scalable and secure web and enterprise applications. It discusses the types of components (web and business), the role of containers, and introduces JDBC for database connectivity, detailing its drivers and core API. Additionally, it covers the implementation of servlets and the HTTP protocol as foundational elements in web application development.

Uploaded by

privatemail.mno
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)
31 views395 pages

Web Based Java All PPts Infoway

The document provides an overview of Java EE, its components, and the need for Java EE in developing scalable and secure web and enterprise applications. It discusses the types of components (web and business), the role of containers, and introduces JDBC for database connectivity, detailing its drivers and core API. Additionally, it covers the implementation of servlets and the HTTP protocol as foundational elements in web application development.

Uploaded by

privatemail.mno
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/ 395

Revision no./Date:00/Oct.

09 2008 By Rahul Barve 1


Objectives
 What is Java EE
 Java EE Components
 Need for Java EE
 Java EE Environment

Revision no./Date:00/Oct.09 2008 By Rahul Barve 2


Java EE

Revision no./Date:00/Oct.09 2008 By Rahul Barve 3


Java EE
 Java Enterprise Edition is a platform designed to
create web based as well as enterprise level
applications.
 Java EE emphasizes upon Component Driven
Architecture.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 4


Why Java EE

Revision no./Date:00/Oct.09 2008 By Rahul Barve 5


Why Java EE
 Would my application be able to support a set of
thousand or more users?
 Would the service be available for 24x7x365?
 Would the response time suffer if user load increases?

Revision no./Date:00/Oct.09 2008 By Rahul Barve 6


Why Java EE
 Would the hardware resource requirements increase
day by day with increasing user load?
 Would my application be able to get integrated with
external applications smoothly?
 Will anybody be able to hack, steal or corrupt my
confidential data?

Revision no./Date:00/Oct.09 2008 By Rahul Barve 7


Quality of Service Requirements
 Scalability
 Availability
 Performance
 Flexibility
 Security
 Re-usability
 Asynchronous Messaging

Revision no./Date:00/Oct.09 2008 By Rahul Barve 8


Components

Revision no./Date:00/Oct.09 2008 By Rahul Barve 9


Components
 A component is an application level reusable unit.
 Components are divided into 2 types:
 Unmanaged
 Managed

Revision no./Date:00/Oct.09 2008 By Rahul Barve 10


Components
 A component which is to be instantiated explicitly is
called as an unmanaged component.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 11


Components
 A component which gets instantiated implicitly is
called as a managed component.
 Managed components are taken care by an
environment known as Container.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 12


Components
 In Java EE, components are divided into 2 types:
 Web Components
 Business Components

Revision no./Date:00/Oct.09 2008 By Rahul Barve 13


Web Components

Revision no./Date:00/Oct.09 2008 By Rahul Barve 14


Web Components
 A component that is responsible for accepting a web
request and generating a web response is called as a
Web Component, e.g, Servlet and JSP.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 15


Business Components

Revision no./Date:00/Oct.09 2008 By Rahul Barve 16


Business Components
 A component that is responsible for handling a
business logic of the application is called as a
Business Component, e.g, EJB.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 17


Container

Revision no./Date:00/Oct.09 2008 By Rahul Barve 18


Container
 A container is a runtime environment responsible for
managing the life cycle of a Java EE components.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 19


Container
 Containers are of 2 types:
 Web Container
 EJB Container

Revision no./Date:00/Oct.09 2008 By Rahul Barve 20


Web Container

Revision no./Date:00/Oct.09 2008 By Rahul Barve 21


Web Container
 A Web Container is a runtime environment
responsible for managing the life cycle of web
components: Servlet and JSP.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 22


Web Container
 A web container is made available by a 3rd party
product called as Web Server.
 The most commonly used web server is Apache
Tomcat.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 23


EJB Container

Revision no./Date:00/Oct.09 2008 By Rahul Barve 24


EJB Container
 An EJB Container is a runtime environment
responsible for managing the life cycle of a business
component: EJB.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 25


EJB Container
 An EJB Container is made available by a 3rd party
product called as an Application Server.
 An Application Server is an extension to Web Server.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 26


EJB Container
 There are different types of Application Servers:
 Oracle Weblogic
 IBM WebSphere
 RedHat Jboss
 Oracle Glassfish

Revision no./Date:00/Oct.09 2008 By Rahul Barve 27


Let’s Summarize
 What is Java EE
 Why Java EE
 Java EE Components
 Web Server and Application Server

Revision no./Date:00/Oct.09 2008 By Rahul Barve 28


By Rahul Barve
Objectives
 Introduction to JDBC
 Why JDBC
 JDBC Drivers
 JDBC Core API
 Executing Simple Queries
 Executing Parameterized Queries
 Transaction Management

By Rahul Barve
Introduction to JDBC

By Rahul Barve
Introduction to JDBC
 JDBC stands for Java to Database Connectivity.
 It is an API that allows Java applications to interact
with Database.

By Rahul Barve
Why JDBC

By Rahul Barve
Why JDBC
 Applications need to write data into or load data from
database.
 JDBC provides a channel to bridge the gap between a
Java application and a Database.

By Rahul Barve
Why JDBC

Java
JDBC Database
Application

By Rahul Barve
JDBC Driver

By Rahul Barve
JDBC Driver
 Every DB vendor provides its own API that simplifies
access for the client programs to connecting to the
database.
 Such an API is known as a Vendor Specific API.

By Rahul Barve
JDBC Driver
 Since both the APIs are written as per the proprietary
standards, they are not compatible with each other.
 This mismatch is resolved by a mediator known as a
Driver.

By Rahul Barve
JDBC Driver

Vendor
Java
JDBC Driver Specific Database
Application
API

By Rahul Barve
JDBC Driver
 There are 4 types of JDBC drivers:
 Type 1
 Type 2
 Type 3
 Type 4

By Rahul Barve
Type 1 Driver

By Rahul Barve
Type 1 Driver
 It is called as a JDBC – ODBC Bridge.
 It uses a 3rd party library known as ODBC which is
provided by Microsoft.

By Rahul Barve
Type 1 Driver

Vendor
Java Type 1
JDBC ODBC Specific Database
Application Driver
API

By Rahul Barve
Type 1 Driver
 It is platform dependent.
 It is the slowest, takes much time for processing.
 Every client machine must have ODBC configuration
setup.

By Rahul Barve
Type 1 Driver
 Suitable for simple desktop applications or even just
for testing purpose.
 Not much recommended in case of large scale
applications or even in production environment.

By Rahul Barve
Type 2 Driver

By Rahul Barve
Type 2 Driver
 Native API, partly Java driver.
 It uses a combination of Java as well as Database
proprietary standards for implementation.

By Rahul Barve
Type 2 Driver

Vendor
Java Type 2
JDBC Specific Database
Application Driver
API

By Rahul Barve
Type 2 Driver
 It does not use any 3rd party library and hence it is
platform independent and faster in processing as
compared to Type 1.

By Rahul Barve
Type 2 Driver
 Since it uses a DB specific native API, the
corresponding API must be installed on every client
machine.

By Rahul Barve
Type 3 Driver

By Rahul Barve
Type 3 Driver
 Net Protocol, Intermediate DB Access Server
 It is used especially when an application needs to
connect to multiple databases.

By Rahul Barve
Type 3 Driver
Vendor
Specific Database
API

Intermediate Vendor
Java Type 3 Specific
JDBC DB Access Database
Application Driver API
Server

Vendor
Specific Database
API

By Rahul Barve
Type 4 Driver

By Rahul Barve
Type 4 Driver
 Database specific, Pure Java Driver.
 Every DB vendor provides its own driver
implementation.
 Directly connects to a DB server using TCP/IP socket
connections.

By Rahul Barve
Type 4 Driver

Vendor
Java Type 4
JDBC Specific Database
Application Driver
API

Socket with
IP Address and Port No

By Rahul Barve
Type 4 Driver
 It is the fastest as compared to Type 1 and Type 2
drivers.
 Platform independent.

By Rahul Barve
Type 4 Driver
 No configuration is required on the client machine.
 Hence, highly recommended for large scale
applications as well as production environment.

By Rahul Barve
JDBC Core API

By Rahul Barve
JDBC Core API
 To implement any JDBC program, Java provides an
API known as a JDBC API.
 It belongs to a package java.sql.

By Rahul Barve
JDBC Core API
 DriverManager
 Driver
 Connection
 Statement
 PreparedStatement
 CallableStatement
 ResultSet

By Rahul Barve
Steps in JDBC Application

By Rahul Barve
Steps in JDBC Application
 Load the Driver.
 Establish Connection.
 Obtain the Statement.
 Execute SQL query.
 (For SELECT query) Obtain the ResultSet and
perform navigation.

By Rahul Barve
Load the Driver

By Rahul Barve
Load the Driver
 A driver can be loaded either by using
Class.forName() or by creating an object of the
driver implementation class.

By Rahul Barve
Establish Connection

By Rahul Barve
Establish Connection
 A Connection to the database can be established
either by using a DriverManager class or a
Driver interface.

By Rahul Barve
Establish Connection
 E.g.
Connection conn =
DriverManager.getConnection(….);

OR

Driver dr =
new <<DriverImplClassNAME>>();
Connection conn = dr.connect(…);
By Rahul Barve
Obtain the Statement

By Rahul Barve
Obtain the Statement
 Once a connection is established, depending upon the
type of the operation, a statement needs to be
obtained.

By Rahul Barve
Obtain the Statement
 Statement is used to execute simple queries.
Statement stmt =
conn.createStatement();

By Rahul Barve
Execute SQL Query

By Rahul Barve
Execute SQL Query
 Statement interface provides relevant methods to
execute SQL queries.
 To execute SELECT query, executeQuery()
method is used that returns ResultSet.

By Rahul Barve
Execute SQL Query
 String sqlQuery = “select ….”;
ResultSet rs =
stmt.executeQuery(sqlQuery);

By Rahul Barve
Perform Navigation

By Rahul Barve
Perform Navigation
 ResultSet maintains data fetched from database in
a tabular format.
 Every column has a column index and a row has a
record position.

By Rahul Barve
Perform Navigation

Before First 1 2 3
1
2
3
After Last

By Rahul Barve
Perform Navigation
 By default, the cursor position of ResultSet points
to BeforeFirst.
 To move in the forward direction, next() method is
used.

By Rahul Barve
Parameterized Queries

By Rahul Barve
Parameterized Queries
 A query may accept parameters.
 To execute parameterized queries,
PreparedStatement interface is used.

By Rahul Barve
Parameterized Queries
 Queries created using PreparedStatement are
compiled once, hence are called as precompiled
queries.

By Rahul Barve
Parameterized Queries
 E.g.
String sqlQuery =
“select … where deptno in (?, ?)”;
PreparedStatement pstmt =
conn.prepareStatement(sqlQuery);

By Rahul Barve
DML Queries

By Rahul Barve
DML Queries
 To execute SELECT queries, executeQuery()
method is used whereas to execute DML queries,
executeUpdate() method is used.

By Rahul Barve
Transaction Management

By Rahul Barve
Transaction Management
 Transaction Management is a very important activity
in an application development.
 Transaction is a set of operations that must execute in
a single unit.

By Rahul Barve
Transaction Management
 Updates made from Java application to database are
committed by default.
 Once, changes are committed, cannot be rolled back.

By Rahul Barve
Transaction Management
 To manage the transactions, auto-commit must be
disabled.
 This is done by using setAutoCommit(false)
on the Connection object.

By Rahul Barve
Transaction Management
 Once auto-commit is disabled, it is possible to commit
or rollback the transactions by using commit() or
rollback() methods respectively.

By Rahul Barve
Lets Summarize
 What is JDBC
 Why JDBC
 JDBC Drivers
 JDBC Core API
 Executing Simple Queries
 Executing Parameterized Queries
 Transaction Management

By Rahul Barve
Revision no./Date:00/Oct.09 2008 By Rahul Barve 1
Objectives
 HTTP Basics
 Introduction to Servlets
 Implementing Servlets
 Life Cycle
 Request Handling

Revision no./Date:00/Oct.09 2008 By Rahul Barve 2


HTTP

Revision no./Date:00/Oct.09 2008 By Rahul Barve 3


HTTP
 HTTP stands for Hyper Text Transfer Protocol.
 HTTP is a stateless protocol or request-response
protocol.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 4


HTTP
 Does not maintain any conversational state between
the 2 requests.
 Cannot recognize the client.
 The most commonly used protocol in Web
Application.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 5


What is Servlet

Revision no./Date:00/Oct.09 2008 By Rahul Barve 6


What is Servlet
 Servlet is a component that is used to extend the
functionality of web server.
 A component that resides on server side and performs
server side processing.
 Used to generate dynamic web contents.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 7


Why Servlet

Revision no./Date:00/Oct.09 2008 By Rahul Barve 8


Why Servlet
 Servlets are written in Java language, thus inherit all
the features of Java.
 Portable
 Secured
 Platform Independent

Revision no./Date:00/Oct.09 2008 By Rahul Barve 9


Servlet API

Revision no./Date:00/Oct.09 2008 By Rahul Barve 10


Servlet API
ServletConfig Servlet Serializable

GenericServlet

HttpServlet

ServletRequest ServletResponse

HttpServletRequest HttpServletReponse

Revision no./Date:00/Oct.09 2008 By Rahul Barve 11


Servlet Life Cycle

Revision no./Date:00/Oct.09 2008 By Rahul Barve 12


Servlet Life Cycle
 Life Cycle of Servlet consists of 3 stages:
 Instantiation and Initialization
 Service
 Destroy

Revision no./Date:00/Oct.09 2008 By Rahul Barve 13


Servlet Life Cycle
 There are 3 life cycle methods:
 init()
 service()
 destroy()

Revision no./Date:00/Oct.09 2008 By Rahul Barve 14


ServletConfig

Revision no./Date:00/Oct.09 2008 By Rahul Barve 15


ServletConfig
 An object of ServletConfig is associated with a
servlet.
 Stores configuration specific information related to
the servlet.
 Can be used to retrieve initial parameters.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 16


ServletContext

Revision no./Date:00/Oct.09 2008 By Rahul Barve 17


ServletContext
 An object of ServletContext is created per
application.
 Thus, useful to handle the application level
information.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 18


ServletContext
 Useful Methods:
 public void setAttribute(String, Object);
 public Object getAttribute(String);

Revision no./Date:00/Oct.09 2008 By Rahul Barve 19


HTML Form Processing

Revision no./Date:00/Oct.09 2008 By Rahul Barve 20


HTML Form Processing
 In a web application, end user enters data using some
HTML form.
 Once, SUBMIT is clicked, request is made to the
server and it is to be processed by some server side
component.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 21


HTML Form Processing
 E.g. User validation using Login page, User
registration using registration page.
 This is done using action attribute of the HTML
<form> element.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 22


Difference between GET and POST
GET POST
 Request parameters are  Request parameters are sent
appended to URL. with the page body.
 Limitation on data transfer.  There is no limitation on
Generally 8kb. data transfer.
 Limitation on length of the  There is no limitation on
URL: 255 characters URL length.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 23


Let’s Summarize
 HTTP Basics
 What is Servlet and its Need
 Servlet API
 Implementing Servlets
 Servlet Life Cycle
 HTML Form Processing

Revision no./Date:00/Oct.09 2008 By Rahul Barve 24


Revision no./Date:00/Oct.09 2008 By Rahul Barve 1
Objectives
 Collaboration
 Session Management

Revision no./Date:00/Oct.09 2008 By Rahul Barve 2


Collaboration

Revision no./Date:00/Oct.09 2008 By Rahul Barve 3


Collaboration
 When 2 components of same web application are
interacting with each other, that process is known as
collaboration.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 4


Collaboration
 Benefits
 Modularity
 Reusability

Revision no./Date:00/Oct.09 2008 By Rahul Barve 5


RequestDispatcher

Revision no./Date:00/Oct.09 2008 By Rahul Barve 6


RequestDispatcher
 Used to achieve collaboration between the
components running within the same web application.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 7


RequestDispatcher
 Methods:
 public void forward(ServletRequest,
ServletResponse);
 public void include(ServletRequest,
ServletResponse);

Revision no./Date:00/Oct.09 2008 By Rahul Barve 8


RequestDispatcher
 forward()
 A called resource generates the final response back to the
client.
 include()
 A calling resource generates the final response back to the
client.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 9


Session Management

Revision no./Date:00/Oct.09 2008 By Rahul Barve 10


Session Management
 HTTP is a stateless protocol.
 In a web application, an end user can make some
transaction through one or multiple requests.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 11


Session Management
 During this, server needs to maintain a conversational
state along with the client.
 This technique is known as session tracking.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 12


Session Management
 Different methods used for Session Tracking:
 URL Rewriting
 Hidden Fields
 Cookies
 Servlet API - HttpSession

Revision no./Date:00/Oct.09 2008 By Rahul Barve 13


HttpSession

Revision no./Date:00/Oct.09 2008 By Rahul Barve 14


HttpSession
 A Servlet API that is used to handle Session Tracking.
 HttpServletRequest is used to obtain the object of
HttpSession.
 getSession()
 getSession(boolean)

Revision no./Date:00/Oct.09 2008 By Rahul Barve 15


HttpSession
 Important Methods:
 setAttribute()
 getAttribute()
 isNew()
 setMaxInactiveInterval()
 invalidate()

Revision no./Date:00/Oct.09 2008 By Rahul Barve 16


Let’s Summarize
 Collaboration
 Session Management

Revision no./Date:00/Oct.09 2008 By Rahul Barve 17


Revision no./Date:00/Oct.09 2008 By Rahul Barve 1
Objectives
 Understand: What is JSP, Why JSP
 Explain: Life Cycle of JSP
 Working with JSP Tags
 Working with Implicit Objects

Revision no./Date:00/Oct.09 2008 By Rahul Barve 2


What is JSP

Revision no./Date:00/Oct.09 2008 By Rahul Barve 3


What is JSP
 JSP stands for Java Server Pages.
 JSP is a server side component that is used to extend
the functionality of web server.
 Used to generate dynamic web content.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 4


Why JSP
 Allows developers to concentrate on Presentation
rather than Processing.
 Designers without knowing Java, still can develop
elegant web pages.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 5


JSP Life Cycle
 There are 3 life cycle methods:
 jspInit()
 _jspService()
 jspDestroy()

Revision no./Date:00/Oct.09 2008 By Rahul Barve 6


JSP Tags

Revision no./Date:00/Oct.09 2008 By Rahul Barve 7


JSP Tags
 JSP Specification supports 3 types of tags:
 Directives
 Scripting Elements
 Standard Actions

Revision no./Date:00/Oct.09 2008 By Rahul Barve 8


Directives
 Directives are divided into 3 categories:
 page
 include
 taglib

Revision no./Date:00/Oct.09 2008 By Rahul Barve 9


Page Directive
 Used to specify some information about the page.
 Syntax:
<%@page attr=“value”...%>

Revision no./Date:00/Oct.09 2008 By Rahul Barve 10


Page Directive
 Attributes:
 language
 extends
 import
 session
 isThreadSafe
 errorPage
 isErrorPage

Revision no./Date:00/Oct.09 2008 By Rahul Barve 11


Page Directive
 language
 Specifies scripting language of the JSP page.
 Possible Values: java
 Default Value: java

Revision no./Date:00/Oct.09 2008 By Rahul Barve 12


Page Directive
 extends
 Specifies fully qualified name of the class from which JSP
specific Servlet implementation class will inherit from.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 13


Page Directive
 import
 Specifies fully qualified names of the classes or interfaces to
be imported from the package other than java.lang.
 E.g.
<%@ page import =
“java.util.Vector, java.io.File” %>

Revision no./Date:00/Oct.09 2008 By Rahul Barve 14


Page Directive
 session
 Specifies whether the page participates in a session or not
and therefore whether the implicit object session will be
available or not.
 Possible Values: true / false
 Default Value : true

Revision no./Date:00/Oct.09 2008 By Rahul Barve 15


Page Directive
 isThreadSafe
 Tells container whether to make the JSP page thread safe or
not.
 It is in contrast to the thread safety concept of
multithreading.
 Possible Values: true / false
 Default Value: true

Revision no./Date:00/Oct.09 2008 By Rahul Barve 16


Page Directive
 errorPage
 Specifies the name of the JSP page to which control is to be
diverted if the current JSP page contains some Java code
that fires an exception.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 17


Page Directive
 isErrorPage
 Indicates whether the JSP page is an error page or not. If so,
an implicit object exception becomes available in the page.
 Possible Values: true / false
 Default Value: false

Revision no./Date:00/Oct.09 2008 By Rahul Barve 18


Include Directive
 Used to include resources like HTML, JSP or Text
files in JSP.
 Syntax:
<%@include file = “<filename>”%>

Revision no./Date:00/Oct.09 2008 By Rahul Barve 19


Scripting Elements
 Scripting Elements are divided into 3 categories:
 Declaration
 Scriptlet
 Expression

Revision no./Date:00/Oct.09 2008 By Rahul Barve 20


Declaration
 Used to declare variables and define methods.
 E.g.
<%!
int x = 100;
public void myMethod(){
//Some Code
}
%>

Revision no./Date:00/Oct.09 2008 By Rahul Barve 21


Scriptlet
 Used to write any valid Java code.
 E.g.
<%
//Java Statements
%>
 Statements written inside scriptlet execute inside the
service method of the servlet.
 Not possible to define methods inside scriptlet.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 22


Expressions
 Used to extract value of the variable.
 Expressions are directly processed on the browser
window.
 E.g.
<%=<expr>%>
 Methods returning ‘void’ cannot be invoked using
expressions.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 23


Implicit Objects

Revision no./Date:00/Oct.09 2008 By Rahul Barve 24


Implicit Objects
 request
 response
 out
 session
 config
 application
 page
 pageContext
 exception

Revision no./Date:00/Oct.09 2008 By Rahul Barve 25


Implicit Objects
 request
 An object of type
javax.servlet.http.HttpServletRequest that
can be used to handle request specific parameters.
 E.g.
<%
String str =
request.getParameter(“name”);
%>

Revision no./Date:00/Oct.09 2008 By Rahul Barve 26


Implicit Objects
 response
 An object of type
javax.servlet.http.HttpServletResponse that
can be used to handle response.
 E.g.
<%
String url =
response.encodeURL(“hello”);
%>

Revision no./Date:00/Oct.09 2008 By Rahul Barve 27


Implicit Objects
 out
 An object of type
javax.servlet.jsp.JspWriter that can be used to
generate response through scriptlets.
 E.g.
<%
String str = “Welcome”;
out.println(“<h1>” +str+ “</h1>”);
%>

Revision no./Date:00/Oct.09 2008 By Rahul Barve 28


Implicit Objects
 session
 An object of type
javax.servlet.http.HttpSession that can be used
to handle the information at the session level.
 E.g.
<%
session.setAttribute
(“name”, “James”);
%>

Revision no./Date:00/Oct.09 2008 By Rahul Barve 29


Implicit Objects
 config
 An object of type
javax.servlet.ServletConfig

Revision no./Date:00/Oct.09 2008 By Rahul Barve 30


Implicit Objects
 application
 An object of type
javax.servlet.ServletContext that can be used to
handle application level information.
 E.g.
<%
application.setAttribute
(“message”, “Welcome”);
%>

Revision no./Date:00/Oct.09 2008 By Rahul Barve 31


Implicit Objects
 page
 It is a reference that refers to an object of JSP specific
servlet implementation class generated by the web container.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 32


Implicit Objects
 pageContext
 An object of type
javax.servlet.jsp.PageContext that acts as an
SPOC through which it is possible to obtain other
resources..

Revision no./Date:00/Oct.09 2008 By Rahul Barve 33


Implicit Objects
 pageContext
 E.g.
<%
pageContext.
setAttribute(“a”,“Hello”,
pageContext.REQUEST_SCOPE);

pageContext.
setAttribute(“b”,“Welcome”,
pageContext.SESSION_SCOPE);
%>

%>

Revision no./Date:00/Oct.09 2008 By Rahul Barve 34


Implicit Objects
 exception
 An object of type
Java.lang.Throwable that can be used to handle
exceptions occurred during the execution.
 It is available only when isErrorPage attribute of page
directive is set to true.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 35


Let’s Summarize
 What is JSP, Why JSP
 Life Cycle of JSP
 JSP Tags
 Implicit Objects

Revision no./Date:00/Oct.09 2008 By Rahul Barve 36


Revision no./Date:00/Oct.09 2008 By Rahul Barve 1
Objectives
 Understanding Standard Actions in JSP
 Introduction to Custom Tag, and The Need
 Creating Custom Tags

Revision no./Date:00/Oct.09 2008 By Rahul Barve 2


Standard Actions

Revision no./Date:00/Oct.09 2008 By Rahul Barve 3


Standard Actions
 Standard Actions are used to perform some specific
task.
 All JSP standard actions follow a standard format:
 <prefix:suffix>
 suffix is the actual name of the tag.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 4


<jsp:useBean>

Revision no./Date:00/Oct.09 2008 By Rahul Barve 5


<jsp:useBean>
 Used to instantiate a Java Bean.
 Important Attributes:
 id
 class
 type
 scope

Revision no./Date:00/Oct.09 2008 By Rahul Barve 6


<jsp:useBean>
 E.g.
<jsp:useBean id=“d1”
class=“java.util.Date”
scope=“session”/>

Revision no./Date:00/Oct.09 2008 By Rahul Barve 7


<jsp:setProperty>
 Used to set properties of the bean.
 Syntax:
<jsp:setProperty name=“<beanName>”
……..<Property-Details>………/>

Revision no./Date:00/Oct.09 2008 By Rahul Barve 8


<jsp:setProperty>
 Property Details:
 property=“*”
 property=“<property>”
 property=“<property>” param=“<param>”
 property=“<property>” value=“<value>”

Revision no./Date:00/Oct.09 2008 By Rahul Barve 9


<jsp:getProperty>
 Used to retrieve properties of the bean.
 Syntax:
<jsp:getProperty name=“<beanName>”
property=“<property>”/>

Revision no./Date:00/Oct.09 2008 By Rahul Barve 10


Other Actions
 <jsp:forward>
 <jsp:include>
 <jsp:param>

Revision no./Date:00/Oct.09 2008 By Rahul Barve 11


Other Actions
 <jsp:forward>
 Used to forward the request to another page.
 E.g.
<jsp:forward page=“next.jsp”/>

Revision no./Date:00/Oct.09 2008 By Rahul Barve 12


Other Actions
 <jsp:include>
 Used to include the resources in the existing JSP.
 E.g.
<jsp:include page=“next.jsp”/>

Revision no./Date:00/Oct.09 2008 By Rahul Barve 13


Other Actions
 <jsp:param>
 Used in conjunction with either <forward> or <include>, to
supply additional parameters.
 E.g.
<jsp:param name=“..” value=“..”/>

Revision no./Date:00/Oct.09 2008 By Rahul Barve 14


Custom Tags

Revision no./Date:00/Oct.09 2008 By Rahul Barve 15


Custom Tags
 Sometimes, as per the application’s requirement, it is
necessary to create user defined tags.
 Such tags are called as custom tags.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 16


Custom Tags
 Need
 <jsp:useBean> is capable of working upon only
Value Objects.
 To handle the processing, still developer is required to
write a Java code inside scriptlets.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 17


Custom Tags
 Benefits:
 Custom tags can be used to reduce the no of scriptlets in
JSP.
 Reusability
 Can be used to handle bean processing.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 18


Custom Tags
 To create custom tags, developer has to provide the
implementation of the tag using a Java class that is
known as a Tag Handler Class.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 19


Custom Tags
 The tag handler class is to be created using a Tag
API that belongs to a package
javax.servlet.jsp.tagext.
 It mainly includes the following:
 Tag
 TagSupport

Revision no./Date:00/Oct.09 2008 By Rahul Barve 20


Custom Tags
 Once the tag implementation class is defined, it is to
be mapped with the name of the tag which can be
accomplished by creating a TLD file.
 It is a mapping file that contains entries in the XML
format.

Revision no./Date:00/Oct.09 2008 By Rahul Barve 21


Custom Tags
 TLD Format:
<tag>
<name>…</name>
<tag-class>…</tag-class>
<body-content>…</body-content>
</tag>

Revision no./Date:00/Oct.09 2008 By Rahul Barve 22


Taglib Directive
 Used to locate TLD file in the JSP.
 E.g.
<%@taglib
uri=“<uri>” prefix=“<prefix>”
%>

Revision no./Date:00/Oct.09 2008 By Rahul Barve 23


Let’s Summarize
 Standard Actions in JSP
 Custom Tag and Their Need

Revision no./Date:00/Oct.09 2008 By Rahul Barve 24


By Rahul Barve
Objectives
 Introduction to Hibernate
 Hibernate Architecture
 First Hibernate Application

By Rahul Barve
Introduction to Hibernate

By Rahul Barve
Introduction to Hibernate
 Hibernate is an Open Source Java Based Framework
that is used to build a Persistence Layer of an
application.

By Rahul Barve
Persistence Layer

By Rahul Barve
Introduction to Hibernate
 Hibernate is a framework that is based upon some
principles known as ORM.
 It is distributed into a single ZIP file which contains
several JAR files.

By Rahul Barve
Hibernate – Basic Architecture

By Rahul Barve
Hibernate – Basic Architecture
Application Classes

Hibernate

Database Server

By Rahul Barve
Hibernate – Core Architecture

By Rahul Barve
Hibernate – Core Architecture

By Rahul Barve
Hibernate – Core API
 Configuration
 Session
 SessionFactory
 Transaction
 Query

By Rahul Barve
Configuration

By Rahul Barve
Configuration
 org.hibernate.cfg.Configuration
 Used to configure Hibernate based upon the
configurations through .properties or .xml
files or even programmatically.

By Rahul Barve
Session

By Rahul Barve
Session
 org.hibernate.Session
 An object representing a conversation between the
application and the persistent store.
 Wraps a JDBC connection.
 A client of TransactionFactory.

By Rahul Barve
Session
 A Component used to persist or load objects to/from
the database.
 Used to perform basic CRUD operations.
 Provides utility methods like save(),
update(), delete(), load().

By Rahul Barve
SessionFactory

By Rahul Barve
SessionFactory
 org.hibernate.SessionFactory
 A factory for Session and a client of
ConnectionProvider.

By Rahul Barve
SessionFactory
 Allows to instantiate Session
 Heavyweight Component
 Only one per application

By Rahul Barve
Transaction

By Rahul Barve
Transaction
 org.hibernate.Transaction
 An object used by the application to specify atomic
units of work.

By Rahul Barve
Transaction
 Abstracts application from underlying JDBC or JTA
transaction.
 Ensures that all the operations on persisted objects
occur in a transaction supported by either JDBC or
JTA.
 Maintains Atomicity.

By Rahul Barve
ConnectionProvider

By Rahul Barve
ConnectionProvider
 org.hibernate.connection.
ConnectionProvider
 A factory for JDBC connections.
 Abstracts application from underlying
Datasource or DriverManager.

By Rahul Barve
TransactionFactory

By Rahul Barve
TransactionFactory
 org.hibernate.TransactionFactory
 A factory for Transaction instances.

By Rahul Barve
Query

By Rahul Barve
Query
 Used to perform Query operations across the
database.
 Uses various clauses, functions to fine tune the
query results.

By Rahul Barve
Hibernate with Annotations

By Rahul Barve 1
Objectives
 Introduction to Hibernate Annotations
 Introduction to JPA
 Working with Annotations
 A Simple Example

By Rahul Barve 2
Hibernate Annotations

By Rahul Barve 3
Hibernate Annotations
 Hibernate provides support for Mapping between
Class and Table, or Field and Column using
Annotations

By Rahul Barve 4
Hibernate Annotations
 There are 2 ways to handle Annotation Based
mapping:
 Using Hibernate Annotations
 Using JPA Annotations

By Rahul Barve 5
What is JPA

By Rahul Barve 6
What is JPA
 JPA stands for Java Persistence API.
 A specification for managing entities in the
application domain.

By Rahul Barve 7
What is JPA
 It is an abstraction on the top of any ORM framework
like Hibernate, Toplink, Eclipselink, Ibatis and so on.

By Rahul Barve 8
Why JPA

By Rahul Barve 9
Why JPA
 Provides ease-of-use abstraction on top of JDBC.
 Application code can be isolated from database,
vendor specific peculiarities and optimization.

By Rahul Barve 10
Why JPA
 An Object-to-Relational Mapping (ORM) engine.
 Provides a query language that is tailored to work
with java objects rather than relational schema.

By Rahul Barve 11
JPA Entities

By Rahul Barve 12
JPA Entities
 JPA manages persistency with the help of simple
Java Entities.
 JPA Entities are simple POJOs.

By Rahul Barve 13
Basic Annotations

By Rahul Barve 14
Basic Annotations
 JPA provides 4 basic annotations:
 @Entity
 @Table
 @Id
 @Column

By Rahul Barve 15
@Entity

By Rahul Barve 16
@Entity
 Tells the persistence provider about the entity class
which is being mapped to the database table.
 Mandatory as far as annotation based metadata is
concerned.

By Rahul Barve 17
@Table

By Rahul Barve 18
@Table
 Tells the EntityManager service about the
relational table to which the bean class maps.
 If omitted, it defaults to the unqualified name of the
entity class.

By Rahul Barve 19
@Column

By Rahul Barve 20
@Column
 Specifies the respective DB column to which the
entity class field maps.
 Not required if class field name matches with the DB
column name.

By Rahul Barve 21
@Id

By Rahul Barve 22
@Id
 Identifies one or more properties that make up the
primary key for the table.
 Mandatory as far as annotation based metadata is
concerned.

By Rahul Barve 23
Let’s Summarize
 Introduction to Hibernate Annotations
 Introduction to JPA
 Working with Annotations
 A Simple Example

By Rahul Barve 24
By Rahul Barve
Objectives
 Describe Hibernate Query Language (HQL)
 Working with Queries

By Rahul Barve
Features

By Rahul Barve
Features
 Used to execute queries against database.
 Based on the relational object models.

By Rahul Barve
Features
 Uses Classes and properties instead of tables and
columns.
 Extremely powerful and it supports Polymorphism
and Associations.

By Rahul Barve
Features
 The ability to apply restrictions to properties of
associated objects related by reference or held in
collections.
 The ability to retrieve only properties of an entity or
entities, without the overhead of loading the entity.

By Rahul Barve
Features
 The ability to order the results of the query.
 The ability to paginate the results.

By Rahul Barve
Features
 Provides support for aggregation with group by,
having, and aggregate functions like sum, min and
max.
 Outer joins when retrieving multiple objects per row.

By Rahul Barve
Clauses

By Rahul Barve
Clauses
 FROM
 SELECT
 WHERE
 ORDER BY

By Rahul Barve
FROM
 Used to load a set of entities from the underlying
database table.
 The returned collection contains instances of an entity
class.
 General Form: from Employee e

By Rahul Barve
SELECT
 Used to retrieve selected fields from the underlying
database table.
 The returned collection contains instances of array
type.
 General Form: select e.name, e.sal from
Employee e

By Rahul Barve
Let’s Summarize
 HQL
 Querying using HQL

By Rahul Barve
By Rahul Barve 1
Objectives
 What is Spring
 Why Spring
 Spring Features
 Spring Modules
 Spring Architecture
 First Example

By Rahul Barve 2
What is Spring?

By Rahul Barve 3
What is Spring?
 Spring is a lightweight dependency injection,
aspect-oriented container and framework.

By Rahul Barve 4
What is Spring?
 Spring is a Container as it creates the Java
Components for your application and manages their
life-cycle.

By Rahul Barve 5
What is Spring Framework?
 It is lightweight in terms of size and overhead.
 It is distributed in a single ZIP file.

By Rahul Barve 6
Why Spring Framework?

By Rahul Barve 7
Why Spring Framework?
 Java components running inside Spring container
have NO dependency on Spring specific Classes
and Interfaces.

By Rahul Barve 8
Why Spring Framework?
 Spring enables to build applications from “plain old
Java objects” (POJOs) and to apply enterprise
services to POJOs

By Rahul Barve 9
Spring Features

By Rahul Barve 10
Spring Features
 Loose Coupling
 Dependency Injection
 Aspect Oriented Programming
 Data Access Support
 Support for Enterprise Services
 Integration Support
 MVC Support

By Rahul Barve 11
Spring Features
 Loose Coupling
 Applications built using Spring are loosely coupled as it is
not required to modify the Java source code in order to
adopt changes in the configuration.

By Rahul Barve 12
Spring Features
 Dependency Injection
 A technique through which, the dependent objects are given to
the components so that components need not create dependent
objects themselves.

By Rahul Barve 13
Spring Features
 Dependency Injection
 public class Employee {
private Address addr;
//Some Code
}

By Rahul Barve 14
Spring Features
 At the time of creating Employee, the container
injects the inner object (Address) inside the main
component (Employee).

By Rahul Barve 15
Spring Features
 Dependency Injection
 Dependency Injection (DI) is also known as Inversion Of
Control (IoC) as now the control is with the Container to
create the Dependent Object and inject it inside the
Component Object.

By Rahul Barve 16
Spring Features
 Aspect Oriented Programming
 AOP is a programming model that promotes separation
of business logic from the system concerns such as
logging, transaction management, security, persistence
etc.

By Rahul Barve 17
Spring Features
 Aspect Oriented Programming
 The code that implements these system wide concerns
is NOT duplicated across multiple components.
 The component development is simple as they can
focus now only upon core business logic.

By Rahul Barve 18
Spring Features
 Data Access Support
 Spring abstracts away the common code like opening and
closing connections, so that the database code can be
clean and simple.

By Rahul Barve 19
Spring Features
 Data Access Support
 Spring doesn’t attempt to implement its own ORM
solution, but provides hooks into several popular ORM
frameworks like Hibernate, JPA, iBATIS etc.

By Rahul Barve 20
Spring Features
 Support for Enterprise Services
 An application built using Spring can acquire various
enterprise level services like:
 Transaction Management
 Persistence
 Asynchronous Messaging
 Security
 Task Scheduling

By Rahul Barve 21
Spring Features
 Integration Support
 Spring provides support for integration with other
technologies like EJB, JNDI, Web Services etc.
 Already implemented services can be consumed very
efficiently using Spring.

By Rahul Barve 22
Spring Features
 MVC Support
 Spring comes with its own MVC framework and even it
can integrated with existing popular MVC frameworks
like Struts, JSF, Tapestry etc.

By Rahul Barve 23
ApplicationContext
 Built on the top of core container.
 Provides support for internationalization,
application life cycle events and validation.

By Rahul Barve 24
Spring Framework – Core Modules

By Rahul Barve 25
Let’s Summarize
 What is Spring
 Why Spring
 Spring Features
 Spring Modules
 Spring Architecture
 First Example

By Rahul Barve 26
By Rahul Barve 1
Objectives
 Introduction to Spring’s Annotation Support
 Bean Configuration
 Using Various Annotations

By Rahul Barve 2
Spring Annotations

By Rahul Barve 3
Spring Annotations
 Spring Framework provides support for Annotation
Based Metadata to handle RAD.
 Developers may discard XML totally and take full
advantage of Spring Annotations.

By Rahul Barve 4
Spring Annotations
 In Annotation based configuration, there are further
2 options:
 Java Based Configuration
 Pure Annotation Based Configuration

By Rahul Barve 5
Configuring Beans

By Rahul Barve 6
Configuring Beans
 To configure beans, Spring provides 2 basic
annotations:
 @Configuration
 @Bean

By Rahul Barve 7
@Configuration

By Rahul Barve 8
@Configuration
 Applied at the class level to introduce a class as a
Configuration Unit.
 Classes annotated with @Configuration act as
entry points of the spring configuration unit.

By Rahul Barve 9
@Bean

By Rahul Barve 10
@Bean
 Applied at the method level to indicate that a
method is a Bean Creation Method.
 Objects returned by methods annotated with @Bean
are treated as managed components in the Spring
Environment.

By Rahul Barve 11
Retrieving Beans

By Rahul Barve 12
Retrieving Beans
 Beans registered in the annotation based
configuration unit are obtained using a class
AnnotationConfigApplicationContext.

By Rahul Barve 13
AnnotationConfigApplicationContext

By Rahul Barve 14
AnnotationConfigApplicationContext

 A class used to register the configuration specific class


so that beans can be obtained against their identities.

By Rahul Barve 15
Components

By Rahul Barve 16
Components
 @Bean annotation can be used to configure beans in
the configuration unit.
 However, developer needs to create these objects
explicitly.

By Rahul Barve 17
Components
 To enable Spring to create Java Objects using
Reflection API, Spring provides a stereotype
annotation @Component.

By Rahul Barve 18
Components
 @Component
Applied at the class level to mark that class as a
Component class.

By Rahul Barve 19
Scanning Components

By Rahul Barve 20
Scanning Components
 Once a component is declared, it is to be scanned in
the configuration unit and that is accomplished by an
annotation @ComponentScan.

By Rahul Barve 21
Let’s Summarize
 Spring’s Annotation Support
 Bean Configuration
 Component Scanning
 Using Various Annotations

By Rahul Barve 22
By Rahul Barve 1
Objectives
 Understand Aspect Oriented Programming.
 Why AOP
 AOP Terminologies
 Weaving
 Implementing AOP

By Rahul Barve 2
What is AOP

By Rahul Barve 3
What is AOP
 AOP is a programming model that promotes
separation of business logic from cross-cutting
concerns.

By Rahul Barve 4
What is AOP
 A cross-cutting concern can be described as any
functionality that affects multiple points of an
application.

By Rahul Barve 5
What is AOP
 These cross-cutting concerns can be modularized into
special objects called Aspects.

By Rahul Barve 6
AOP – Big Picture

By Rahul Barve 7
Benifits
 Aspects offer an alternative to inheritance and
delegation that can be cleaner in many circumstances.
 Secondary concerns are decoupled from primary
concerns.
 Allows developers to focus upon business logic.

By Rahul Barve 8
AOP Terminology

By Rahul Barve 9
AOP Terminology
 There are 5 terms involved in Spring AOP:
 Advice
 Joinpoint
 Pointcut
 Aspect
 Weaving

By Rahul Barve 10
AOP Terminology
 Advice
 Aspects have a purpose, a job they are meant to do.
 The job of an aspect is called advice.
 It defines both: WHAT and WHEN of an aspect.

By Rahul Barve 11
AOP Terminology
 JoinPoint
 A joinpoint is a point in the execution of the application
where an aspect can be plugged in.

By Rahul Barve 12
AOP Terminology
 Pointcut
 If advice defines WHAT and WHEN of an aspect, then
pointcut defines WHERE.
 A pointcut definition matches one or more joinpoints at
which advice should be woven.

By Rahul Barve 13
AOP Terminology
 Aspect
 An aspect is the merger of advice and pointcut.
 It specifies what to do, when to do and where to do.

By Rahul Barve 14
Weaving
 Weaving is the process of applying aspects to a
target object to create a new, proxied object.
 The aspects are woven into the target object at the
specified join points.

By Rahul Barve 15
Weaving
 Weaving can take place at three different points:
 Compile time
 Classload time
 Runtime

By Rahul Barve 16
Weaving
 Compile time
 Aspects are woven in when the target class is compiled.

By Rahul Barve 17
Weaving
 Classload Time
 Aspects are woven in when the target class is loaded into
the JVM.
 This requires a special class loader that enhances the byte
code before the class is introduced to the application.

By Rahul Barve 18
Weaving
 Runtime
 Aspects are woven in sometime during the execution of the
application.
 Typically, an AOP container will dynamically generate a
proxy object that will delegate to the target object while
weaving in the aspects.
 This is how Spring AOP aspects are woven.

By Rahul Barve 19
Spring AOP support

By Rahul Barve 20
Spring AOP support
 Spring Advices are written in Java.
 Spring applies an Advice to an Object at runtime, by
wrapping them with a proxy class.

By Rahul Barve 21
Spring AOP support
 Between the time that the proxy intercepts the
method call and the time it invokes the target bean’s
method, the proxy performs the aspect logic.
 Spring only supports method joinpoints.

By Rahul Barve 22
Types of Spring AOP Advices

By Rahul Barve 23
Types of Spring AOP Advices
 Before Advice
 After returning Advice
 After throwing Advice
 After Advice
 Around Advice

By Rahul Barve 24
Before Advice
 Causes a method to be invoked before the invocation
of a target method.

By Rahul Barve 25
After Returning Advice
 Causes a method to be invoked after successful
invocation of a target method.

By Rahul Barve 26
After Throwing Advice
 Causes a method to be invoked if an exception is
occurred during an execution of the target method.

By Rahul Barve 27
After Advice
 Causes a method to be invoked irrespective of
whether a target method completes successfully or
not.

By Rahul Barve 28
Around Advice
 A single advice that wraps up all types of advices.
 Provides a single method through which other advice
methods are invoked.

By Rahul Barve 29
Enabling Proxying

By Rahul Barve 30
Enabling Proxying
 Since in AOP, spring performs weaving with the help
of proxies, it’s necessary to enable Proxy in the
application.

By Rahul Barve 31
Enabling Proxying
 To enable proxy, the configuration specific class must
be annotated with @EnableAspectJAutoProxy.

By Rahul Barve 32
Spring’s AOP Annotations

By Rahul Barve 33
Spring’s AOP Annotations
 Spring comes with Annotation Based Support,
through AspectJ annotations for AOP.

By Rahul Barve 34
Spring’s AOP Annotations
 AOP Annotations:
 @Aspect
 @Before
 @AfterReturning
 @AfterThrowing
 @After
 @Pointcut
 @Around

By Rahul Barve 35
@Aspect
 Applied at the class level.
 Tells Spring that the class is not just a POJO, rather
it’s an aspect.
 Classes annotated with @Aspect will only be
considered as Aspects.

By Rahul Barve 36
@Before
 Applied at the method level.
 Annotated methods will be called before the
execution of advised method.

By Rahul Barve 37
@AfterReturning
 Applied at the method level.
 Annotated methods will be called after the
successful return of the advised method.

By Rahul Barve 38
@AfterThrowing
 Applied at the method level.
 Annotated methods will be called if some exception
is raised during the execution of the advised
method.

By Rahul Barve 39
@After
 Applied at the method level.
 Annotated methods will be called after the
execution of the advised method, irrespective of
whether the advised method returns successfully or
not.

By Rahul Barve 40
@Pointcut
 Used to define a pointcut.
 Applied at the method level to mark the method as a
pointcut.
 The marked method can be used for further
referencing.

By Rahul Barve 41
@Around
 Applied at the method level to mark the method as a
an Around Advice.
 Uses a Pointcut expression to apply the aspect.

By Rahul Barve 42
Let’s Summarize
 What is AOP
 Why AOP
 AOP Terminologies
 Types of Advices
 Weaving
 Implementing AOP

By Rahul Barve 43
By Rahul Barve 1
Objectives
 Working with ApplicationContext
 Bean Life Cycle
 Understanding Dependency Injections
 Bean Scopes
 Auto-wiring

By Rahul Barve 2
ApplicationContext
 In a Spring-based application, the application objects live
within the Spring Container.
 The container creates the objects, wire them together,
configure them, and manage their lifecycle.

By Rahul Barve 3
ApplicationContext
 The ApplicationContext interface standardizes the Spring
bean container behavior.
 Its implementations form the simple container, providing
basic support for DI.
 Supports I18N.
 Supports Event Management.

By Rahul Barve 4
ApplicationContext
 Spring comes with several flavors of
ApplicationContext.
 FileSystemXmlApplicationContext
 ClassPathXmlApplicationContext
 XmlWebApplicationContext

By Rahul Barve 5
FileSystemXmlApplicationContext
 Loads a context definition from an XML file located
in the file system.
 E.g.
ApplicationContext ctx;
String file = “c:/config.xml”;
ctx =
new
FileSystemXmlApplicationContext(file);

By Rahul Barve 6
ClassPathXmlApplicationContext
 Loads a context definition from an XML file located
in the classpath.
 E.g.
ApplicationContext ctx;
String file = “config.xml”;
ctx =
new ClassPathXmlApplicationContext(file);

By Rahul Barve 7
XmlWebApplicationContext
 Loads a context definition from an XML file
contained within a web application.
 Used in Spring MVC environment.

By Rahul Barve 8
Bean Configuration File
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="emp"
class="com.emp.Employee">
</bean>
</beans>

By Rahul Barve 9
Bean Configuration File
 bean: The Element which is the most basic
configuration unit in Spring. It tells Spring Container to
create an Object.
 id: The Attribute which gives the bean a unique name by
which it can be accessed.
 class: The Attribute which tells Spring the type of a
Bean.

By Rahul Barve 10
Accessing Bean
ApplicationContext ctx;
String file = “c:/config.xml”;
ctx = new
FileSystemXmlApplicationContext(file);

GreetingService service;
service =
(GreetingService)ctx.getBean(“greet”);

By Rahul Barve 11
How DI/IoC Container works
 In Inversion Of Control (IoC), control is inverted back
to the Container to support the object dependencies.
 IoC container creates the POJO objects and provides
dependencies to them.
 These POJO objects are not tied to any framework.
 The declarative configuration for POJO objects is
defined with unique identities (id) in XML.
 These are known as bean definitions.

By Rahul Barve 12
How DI/IoC Container works
 The IoC container at runtime identifies POJO bean
definitions, creates bean objects and returns them to
the Application.
 IoC container manages dependencies of the objects.

By Rahul Barve 13
Injecting the Dependencies
 The IoC container will Inject the dependencies in
three ways
 Create the POJO objects by using no-argument
constructor and injecting the dependent
properties by calling the setter methods.

By Rahul Barve 14
Injecting the Dependencies
 The IoC container will Inject the dependencies in
three ways
 Create the POJO objects by using no-argument
constructor and injecting the dependent
properties by calling the setter methods.
 Create the POJO objects by using
parameterized constructors and injecting the
dependent properties through the constructor.

By Rahul Barve 15
Injecting the Dependencies
 The IoC container will Inject the dependencies in
three ways
 Create the POJO objects by using no-argument
constructor and injecting the dependent
properties by calling the setter methods.
 Create the POJO objects by using
parameterized constructors and injecting the
dependent properties through the constructor.
 Implements the method Injection.

By Rahul Barve 16
Injecting Properties by calling Setters
public Class Employee {
private String fname, lname;
public Employee(){}

public void setFname(String f) {


fname = f;
}
public void setLname(String l) {
lname = l;
}
}

By Rahul Barve 17
Injecting Properties by calling Setters
<bean id="emp"
class="com.emp.Employee">
<property name=“fname” value=“a”/>
<property name=“lname” value=“b”/>
</bean>

By Rahul Barve 18
Bean LifeCycle

By Rahul Barve 19
Bean LifeCycle
Instantiate Populate BeanNameAware's
Properties setBeanName()

BeanFactoryAware's ApplicationContextAware's
setBeanFactory() setApplicationContext()

InitializingBean's Call Custom


afterPropertiesSet() init-method

DisposableBean's Call Custom


destroy() destroy-method

By Rahul Barve 20
Bean Life Cycle
 Instantiate: Spring instantiates the bean.
 Populate properties: Spring injects the bean’s
properties.
 Set bean name: If the bean implements
BeanNameAware, Spring passes the bean’s ID
to setBeanName().

By Rahul Barve 21
Bean Life Cycle
 Set Application Context: If the bean implements
ApplicationContextAware, Spring passes
the application context to
setApplicationContext().
 Postprocessor (before initialization): If there are
any BeanPostProcessors, Spring calls their
postProcessBeforeInitialization()
method.

By Rahul Barve 22
Bean Life Cycle
 Initialize beans: If the bean implements
InitializingBean, its
afterPropertiesSet() method will be called.
If the bean has a custom init method declared, the
specified initialization method will be called.
 Postprocessor (after initialization): If there are any
BeanPostProcessors, Spring calls their
postProcessAfterInitialization()
method.

By Rahul Barve 23
Bean Life Cycle
 Bean is ready to use. At this point the bean is ready
to be used by the application and will remain in the
bean factory until it is no longer needed.
 Destroy bean: If the bean implements
DisposableBean, its destroy() method will
be called. If the bean has a custom destroy-method
declared, the specified method will be called.

By Rahul Barve 24
Injecting Properties through Constructors
public Class Employee {
private String fname, lname;
public Employee(String f,String l ){
fname = f;
lname = l;
}
}

By Rahul Barve 25
Injecting Properties through Constructors
<bean id="emp"
class="com.emp.Employee">
<constructor-arg value=“Joe"/>
<constructor-arg value=“Thomas"/>
</bean>

By Rahul Barve 26
Dependent Beans

By Rahul Barve 27
Dependent Beans
 A bean is a dependency of another bean, is
expressed by the fact that, one bean is set as a
property of another.

By Rahul Barve 28
Dependent Beans
 It is achieved with the <ref/> element or ref
attribute in XML based configuration metadata of
beans.

By Rahul Barve 29
Bean Loading

By Rahul Barve 30
Bean Loading
 In Spring, Bean Loading happens by 2 ways:
 EAGER (DEFAULT)
 LAZY

By Rahul Barve 31
Bean Loading
 The bean registered in the configuration unit gets
instantiated as soon as the ApplicationContext
is built.
 This is known as EAGER Loading.

By Rahul Barve 32
Bean Loading
 The bean registered in the configuration unit gets
instantiated only when the client program makes a
request for the same.
 This is known as LAZY Loading.

By Rahul Barve 33
AutoWiring

By Rahul Barve 34
AutoWiring
 Rather than explicitly wiring all of your bean’s
properties, you can have Spring automatically figure
out how to wire beans.
 It is done by setting the autowire property.

By Rahul Barve 35
AutoWiring
 Spring provides 3 types of autowiring:
 byName
 byType
 constructor

By Rahul Barve 36
AutoWiring
 byName
 Attempts to find a bean in the container whose
name is the same as the name of the property
being wired.

By Rahul Barve 37
AutoWiring
 byType
 Attempts to find a single bean in the container
whose type matches the type of the property being
wired.

By Rahul Barve 38
AutoWiring
 constructor
 Tries to match up a constructor of the autowired bean
with beans whose types are assignable to the
constructor arguments.

By Rahul Barve 39
Bean Scopes

By Rahul Barve 40
Bean Scopes
 Every bean registered in XML file has some scope.
 It is possible to modify scope of the bean using
scope attribute of <bean> element.

By Rahul Barve 41
Bean Scopes
 There are 5 different types of scopes:
 singleton
 prototype
 request
 session
 global-session

By Rahul Barve 42
Bean Scopes
 singleton
 It is the default scope.
 Indicates that the bean configuration is singleton.
 If the same bean is requested multiple times, spring
returns the same object.

By Rahul Barve 43
Bean Scopes
 prototype
 Antonym of singleton.
 If the same bean is requested multiple times, spring
returns the a new object every time.

By Rahul Barve 44
Bean Scopes
 request
 Applicable only in the context of Spring MVC.
 The bean is alive until the response is generated.
 For every new instance of HttpServletRequest, spring
creates a new instance.

By Rahul Barve 45
Bean Scopes
 session
 Applicable only in the context of Spring MVC.
 The bean is alive until the session is over.
 Bean can survive even if the response is generated.
 For every new instance of HttpSession, spring creates a
new instance.

By Rahul Barve 46
Bean Scopes
 global-session
 Applicable in the context of Spring Portlet environment.
 The bean is alive across multiple portlets.

By Rahul Barve 47
Let’s Summarize
 Working with ApplicationContext
 Bean Life Cycle
 Understanding Dependency Injections
 Auto-wiring
 Bean Scopes

By Rahul Barve 48

You might also like