Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Advanced Java eBook

This document provides an introduction to Java EE, detailing its three editions: Java SE (Standard Edition), Java EE (Enterprise Edition), and Java ME (Micro Edition). It explains the Client-Server Model, distributed applications, and the architecture of Java EE, emphasizing its features and libraries for developing scalable and secure applications. Additionally, it covers HTTP protocol, server response types, and the significance of various client request types in web communication.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Advanced Java eBook

This document provides an introduction to Java EE, detailing its three editions: Java SE (Standard Edition), Java EE (Enterprise Edition), and Java ME (Micro Edition). It explains the Client-Server Model, distributed applications, and the architecture of Java EE, emphasizing its features and libraries for developing scalable and secure applications. Additionally, it covers HTTP protocol, server response types, and the significance of various client request types in web communication.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 644

Advanced Java

Lesson 1—Introduction to Java EE

© Simplilearn. All rights reserved.


Learning Objectives

Discuss Java editions

Describe distributed applications

Explain Client-Server Model and important terms related to it


Advanced Java
Topic 1—Java Editions
Java Editions

Java SE stands for Java’s Standard Edition

Java EE stands for Enterprise Edition

Java ME stands for Micro Edition


Java Editions
FEATURES OF JAVA SE (STANDARD EDITION)

• Java SE is the core Java programming platform. It contains all Java libraries.
Java SE
• The latest version is Java SE 8u131

• It helps to develop and deploy Java applications on desktops, servers, and embedded
environments. It is used to build standalone applications.
Java Editions
FEATURES OF JAVA EE (ENTERPRISE EDITION)

• Java EE platform is designed to help developers create large-scale, multi-tiered,


scalable, reliable, and secure network applications.

• The latest version is Java EE 7

• It is portable, so it allows an application hosted at one common place to be accessed


Java EE by users across the world over the Internet.

• It provides API (Application Programming Interface) to develop distributed


applications that follows Client-Server Model.

• It facilitates the development of web applications.


Java Editions
FEATURES OF JAVA ME (MICRO EDITION)

• Java ME (Java 2 Platform, Micro Edition) is a technology that allows programmers to


develop programs for mobile application devices.

• The latest version is Java ME 8.3

• It consists of programming specifications and a special virtual machine, the K virtual


machine, that allows a Java ME-encoded program to run on mobile devices.

Java ME
Java EE vs. Java SE

The Java EE (Enterprise Edition) differs from Java SE (Java Standard Edition Platform) in terms of the
libraries it provides to deploy:

• fault-tolerant,
• distributed, and
• multi-tier Java software, based largely on modular components running on an application server.
Java EE Libraries and APIs

• Built on top of Java SE, Java EE provides additional libraries for

o database access [JDBC (Java Database Connectivity), JPA (Java Persistence API)]
o remote method invocation (RMI)
o messaging [JMS (Java Message Service)]
o web services
o XML (eXtensible Markup Language) processing

• It also defines standard APIs for Enterprise JavaBeans, Servlets, Portlets, and Java Server Pages (JSP)

The installation guide containing the steps to download and configure Java JDK (standard
edition) and Apache Tomcat (to access additional libraries) can be downloaded from your LMS.
Java EE Architecture

Internet Client Web Server

Web Container
Web
Browser
Controller EJB Server
<%
EJB Container
%>
Model
View

Database

Intranet Client

GUI
Application
Java EE Architecture: Features

• Java EE platform facilitates an architecture in which the business components are placed in a separate
tier.

• The Java EE architecture enhances features such as scalability, extensibility, and maintainability.

• Its modular design allows easy modification of the business logic. It provides more security because it
partitions business services from the web tier. It also permits clean job separation of job roles.

• The enterprise components can leverage their EJB container for service, such as component and
resource management, security, persistence, and transactions.
Relating Java EE Architecture Complexity and Robustness

JSP Pages with


Modular
Component and
JSP Pages with Enterprise
Modular JavaBeans
Component
Basic JSP Pages • HTML Pages
Robustness and Servlets • HTML Pages • JSP Pages
• JSP Pages • Servlets
HTML Pages • HTML Pages
• Servlets • Java Beans
• JSP Pages Component
• Java Beans
• Servlets Component • Custom Tags
HTML Pages
• Custom Tags • Enterprise
JavaBeans

Complexity
Relating Java EE Architecture Complexity and Robustness
KEY POINTS

JSP Pages with


Modular
Component and
JSP Pages with Enterprise
Modular JavaBeans
• As the richness and robustness of a web application increases, so does the complexity.
Component
Basic JSP Pages • HTML Pages
Robustness • The complexity of the application can be managed by proper design that helps in getting
and Servlets • HTML Pages • JSP Pages
rid of programming concerns.
• JSP Pages • Servlets
HTML Pages • HTML Pages
• The web container and Java EE platform provide components that can be used to
• Servlets • Java Beans
manage complex application
• JSPdesign.
Pages
• Java Beans Component
• Servlets Component • Custom Tags
HTML Pages
• Custom Tags • Enterprise
Java Bean

Complexity
Advanced Java
Topic 2—Distributed Applications and Client-Server Model

• Distributed Applications
• Client Server Model
• HTTP Protocol
• Types of Server Response
• Client Request Types
• HTML
• Running HTML code with Apache
Recall!

Java EE provides API (Application Programming Interface) to develop


distributed applications that follow Client-Server Model.
Distributed Applications

• In distributed applications, same application can run across different machines at the same time using internet.
• One machine acts as Server where application is deployed and the other machines act as Client.

Client 1 Client 3 Client 1 Client 3

Server 1 Server 3
Application Application

Client 2 Client 4 Client 2 Client 4


INTERNET

Client 1 Client 3 Client 1 Client 3

Server 2 Server 4
Application Application

Client 2 Client 4 Client 2 Client 4


Client-Server Model
DEFINITION

The client–server model is a distributed application structure that partitions tasks or workloads between
the providers of a resource or service (web servers) and service requesters (web clients).

Both web client and web server are programs.

A web client is not a user, but a program. Someone who uses this program to send request
to web server is known as “end user.”
Client-Server Model
ARCHITECTURE

Web Client Web Server


request
Include web browser (Chrome, Include web, database,
Mozilla, etc.), chat applications, application, chat, email, etc.
and email software etc. response

Makes request in the form of an URL: Accepts requests from the client and gives back a
http://localhost:8080/applicationname response which can be either static or dynamic.
Responses are delivered in HTML format.

PORT
Network
HTTP Protocol

HTTP (Hypertext Transfer Protocol) is a TCP/IP based communication protocol, which is used to deliver
data over the web.

It provides a standardized way for the client to communicate with the server.
Client-Server Model
SIGNIFICANCE OF URL AND PORT

Uniform Resource Locator (URL) uniquely identifies a resource on the internet and follows HTTP protocol.

The machine on which the application is


hosted/deployed

http://localhost:8080/MyApplication

Server port number on which the


server is functional on the machine Name of the application/context root

Tomcat server runs on port 8080. Remember to check during installation.


Client-Server Model
FEATURES OF HTTP PROTOCOL

• HTTP (Hypertext Transfer Protocol) is a TCP/IP based communication protocol, which is used to deliver
data over the web.

• This protocol is used to change or transfer the hypertext.

• Hypertext is a structure text that uses logical links between containing text.

• It is a stateless protocol—it does not require the HTTP server to retain information about each user.
Client-Server Model
SERVER RESPONSE

Server generates response for Client request. It sends three things:

1. Status which tells whether client’s response has successfully reached the server or not. Example: 404
error for page not found.

2. Information about the type of content that the server is going to send. The server sends HTML pages
as response.

3. Actual content, example: when client types http://www.google.com in any browser, the server
navigates the client to the Google home page.
Client-Server Model
SERVER RESPONSE TYPES

• Static Page: There is no change in the content. Client requests a web page and server gets the page
back as response.

• Dynamic Page: The page content changes frequently. Server may not be able to process the request.

Dynamic Content
User Login Home
Map Page
Page Page

Static Content

Web Server
styles.css Dojo.js logo.jpg
Client-Server Model
TYPES OF SERVERS

Commonly used server types are as follows:

• Web Server
• Application Server
• Proxy Server
• Virtual ServerBlade Server
• File Server
• Policy Server

We will focus on web and application server in this course.


Web Server Vs. Application Server

Web Server Application Server


Web Server program runs on the server. It is a component based product.

It looks for incoming requests and services those requests. It provides middleware services for security and state
Once the web server receives a request, depending on the maintenance, along with data access and persistence.
type of request, it might look for a web page, or execute a
program on the server.

Web servers have plugins to support scripting languages like Application Server can do whatever Web Server is capable of
Perl, PHP, ASP, JSP etc. through which they can generate doing as it has Web Server as an integral part. Additionally, it
dynamic HTTP content. has components and features to support Application level
services such as Connection Pooling, Object Pooling,
Transaction Support, Messaging services, etc.

It acts as a container which serves static content. It acts as container upon which business logic is built.

Web Server only supports Servlets and JSP. Application Server supports distributed transaction and EJB.
Client-Server Model
CLIENT REQUEST TYPES

• GET

• POST

• PUT

• DELETE

• TRACE

• OPTIONS

• HEAD
Client-Server Model
CLIENT REQUEST TYPES: GET

GET • Used to GET the resource

POST • It can send limited data

• It is not secure, can be bookmarked and, the data is visible in URL


PUT
• It is the default method
DELETE

TRACE

OPTION

HEAD
Client-Server Model
CLIENT REQUEST TYPES: POST

GET • It is used to process data, save data, change data, etc.

• It is secure and cannot be bookmarked


POST
• No limit on data; sent as “payload” and not appended in URL
PUT

DELETE

TRACE

OPTION

HEAD
Client-Server Model
CLIENT REQUEST TYPES: PUT

GET • If the Uniform Resource Identifier (URI) refers to an already existing resource, it is modified. If the
URI does not point to an existing resource, then the server can create the resource with that URI
using PUT.
POST

PUT • It replaces all current representation of the target resource with the uploaded content.

DELETE

TRACE

OPTION

HEAD
Client-Server Model
CLIENT REQUEST TYPES: DELETE

GET • DELETE request is used to delete a document of the target resource given by URL.

• To allow eventual consistency while replication, deleted documents remain in the database forever.
POST

PUT

DELETE

TRACE

OPTION

HEAD
Client-Server Model
CLIENT REQUEST TYPES: TRACE

GET • TRACE request is used when the client wants to see if any change has been done by intermediate server.

POST • This request works for targeted resources.

PUT

DELETE

TRACE

OPTION

HEAD
Client-Server Model
CLIENT REQUEST TYPES: OPTION

GET • OPTION request returns the HTTP method which is supported by the server.

POST • It allows the client to determine the option requirements associated with a resource.

PUT

DELETE

TRACE

OPTION

HEAD
Client-Server Model
CLIENT REQUEST TYPES: HEAD

GET • HEAD request is used for testing hypertext links for accessibility, validity, and recent modification.

POST • This is similar to GET method, but it asks for response without response body.

PUT

DELETE

TRACE

OPTION

HEAD
Client-Server Model
SERVER RESPONSE: HTML

• HTML stands for Hypertext Mark-up Language.

• It refers to the way the web pages (HTML documents) are linked together. The link available on a
web page is called Hypertext.

• HTML contains tags and elements which are used to format web pages.
Client-Server Model
SERVER RESPONSE: HTML DOCUMENT STRUCTURE

A typical HTML document has the following structure:

<!DOCTYPE html>
<html>
<head>
<title>Html Program </title>
</head>
<body>

<h1>This is a Heading</h1>
<p>welcome To HTML Program.</p>

</body>
</html>
Client-Server Model
SERVER RESPONSE: RUNNING AN HTML CODE

Write the HTML code 4 To run HTML, double click on “file”

1 3 3 5

Open any editor Save it with HTML extension in any drive of your system
Running an HTML Code with Apache
TOMCAT APACHE DIRECTORY HIERARCHY

apache-tomcat-8.5.16-windows-x64

bin

lib

webapps

Index.html or
my_project_name
anyname.html
Running an HTML Code with Apache

1. Create a sub-folder in webapps folder

2. Add a name to the project

3. Place your HTML page inside project folder with index.html name or any_other_name.html

4. Open browser to send request through URL

5. Enter this for the URL: http://localhost:8080//my_project_name

6. If html filename is index.html, the above link will open an HTML page. If not, use the following:

http://localhost:8080//my_project_name/any_other_name.html
Screenshot of Project in Apache Webapp
Key Takeaways

Java has three editions: J2SE (standard), J2EE (Enterprise), and J2ME (Micro)

The J2EE (Enterprise Edition) differs from J2SE (Java Standard Edition Platform) in
terms of the libraries it provides to deploy fault-tolerant, distributed and, multi-tier
Java software

In distributed applications, same application can run across different machines at


the same time using internet. One is client and the other is Server.

The client–server model is a distributed application structure that partitions tasks


or workloads between the providers of a resource or service (web servers) and
service requesters (web clients).
Quiz
Thank You
Advanced Java
Lesson 2—Java Servlet I

© Simplilearn. All rights reserved.


Learning Objectives

Discuss Java Servlet Architecture

Explain the important terms related to Java Servlets

Understand Servlet Lifecycle

Explain ServletsRequest, ServletResponse, ServletConfig, and, ServletContext

List the steps to configure and deploy Servlet

Explain Servlet Collaboration


Advanced Java
Topic 1—Introduction to Java Servlet

• Static and Dynamic Response


• Client-Server Architecture with Java Servlet
• Web Container
• Client-Server Architecture with Web Container
Why Servlet?

We have learned that web server generates two types of responses: Static and
Dynamic.
However, a web server can generate static responses in the form of HTML.

To generate dynamic response, a programming language that performs dynamic operations is needed.

Servlet is a Java program that can perform dynamic operations and send to web server. The web
server then sends this response to web client.
Static Response

Every time you type https://www.google.com/ in your browser, you are directed to the Google home page.
This is called a static page as the web server displays the same HTML page every time the client requests.
Dynamic Response

When users login to their Facebook account, different pages will be generated for different users. You would see
the pages relevant to you.

This requires multiple responses from the server, called dynamic response. This uses Servlets.
Client-Server Architecture with Java Servlet

Http request
Web Server

User Workstation Web


Container
Servlet
Browser

Http response
Think Through!

Web server is a program that sends HTTP response, and Servlet is a Java Program
that deals with classes and objects.

How is the response generated in the HTTP format?


Think Through!

This is done using a “web container.”

Let’s understand what a web container is.


What is a Web Container?

A web container is built on top of the Java EE platform, and it implements the Servlet API and the services
required to process HTTP (and other Transmission Control/Internet Protocol [TCP/IP]) requests.

• Java Servlets are components that must exist in a web container. Web container activates the Servlet
that matches the requested URL by calling the service method on an instance of Servlet class.

• Activation of the service method for a given HTTP request is handled in a separate thread within the
web container protocol.
Client-Server Architecture with Web Container

The lifecycle of a Servlet is controlled by the web container in which the Servlet has been deployed.

Http request
User Workstation

Web Server
Browser
Http request
Http response

Web Container
Http response

request object
response object

Servlet
Advanced Java
Topic 2—Servlet API, Interface, and Methods

• Servlets API
• Servlet Interface and Classes
• Servlet API Interface
• Servlets API Hierarchy to Create Servlet
• Servlets Methods
• Generic Servlet Abstract Class
• Generic Servlet Abstract Class Methods
• HttpServlet Abstract Class Methods
Servlets API

Servlet API contains a number of classes and interfaces that describe the contracts between a servlet class and
the runtime environment provided for an instance by a conforming servlet container.

Servlet API provides the following two packages that contain its classes and interfaces:

javax.servlet.*; Classes and interfaces defines the contracts between a Servlet class and the
runtime environment provided for an instance of such a class by a conforming
Servlet container.
javax.servlet.http.*; Classes and interfaces defines the contracts between a Servlet class running
under the HTTP protocol and the runtime environment provided for an
instance of such a class by a conforming Servlet container.
Servlet Interface and Classes

Exception EventListener
ServletException interface
EventObject
ServletContextListener
UnavailableException ServletContextEvent
EventListener
interface
ServletContextAttribute Event
interface
interface ServletContextAttributeListener
ServletConfig
Servlet interface
interface
ServletRequest ServletResponse

Serializable
GenericServlet ServletRequestWrapper ServletResponseWrapper

interface interface OutputStream interface


interface
ServletContext RequestDispatcher ServletOutputStream SingleThreadModel
FilterConfig
interface InputStream

FilterChain ServletInputStream
Servlet API Interface
javax.servlet.FilterConfig Passes information to a filter during initialization
javax.servlet.RequestDispatcher Sends request and response object to any resource (such as a Servlet, HTML file, or
JSP file) on the server
javax.servlet.Servlet Defines methods that all Servlets must implement
javax.servlet.ServletConfig A Servlet configuration object used by a Servlet container to pass information to a
Servlet during initialization
javax.servlet.ServletContext Defines a set of methods that a Servlet uses to communicate with its Servlet
container, for example, to get the MIME type of a file, dispatch requests, or write to
a log file
javax.servlet.ServletContextAttri Implementation of this interface receives notifications of changes to the attribute
buteListener list on the Servlet context of a web application
javax.servlet.ServletContextListe Implementation of this interface receive notifications about changes to the Servlet
ner context of the web application they are a part of
javax.servlet.ServletRequest Defines an object to provide client request information to a Servlet
javax.servlet.ServletRequestAttri A ServletRequestAttributeListener can be implemented by the developer interested
buteListener in being notified of request attribute changes
javax.servlet.ServletRequestListe A ServletRequestListener can be implemented by the developer interested in being
ner notified of requests coming in and out of scope in a web component
javax.servlet.ServletResponse Defines an object to assist a Servlet in sending a response to the client
Servlets API Hierarchy to Create Servlet

javax.servlet.Servlet (I) All Servlets must implement Servlet interface that defines lifecycle methods.

Servlet can also be created by extending GenericServlet abstract class.


javax.servlet.GenericServlet GenericServlet abstract class implements all methods of Servlet interface
(C) except service method.

javax.servlet.http.Http Other way of creating a Servlet is to extend HttpServlet abstract class. HttpServlet
Servlet (C) abstract class extends GenericServlet abstract class.

User Defined Servlet I —Interface


C—Class
Servlet Methods

Servlet interface has 5 methods:

1. init

2. service

3. destroy

4. getServletInfo

5. getServletConfig
Servlet Methods
init

init method is called by Servlet container to indicate to a Servlet that it is being placed into
init
service.
service It is declared as: void init (ServletConfig config)

destroy

getServletInfo

getServletConfig
Servlet Methods
service

init service method is called by the Servlet container to allow the Servlet to respond to a request.

service public void service(ServletRequest req, ServletResponse


It is declared as: res) throws ServletException,
destroy java.io.IOException

getServletInfo

getServletConfig
Servlet Methods
destroy

init destroy() indicates that the Servlet is being taken out of service.

service
It is declared as: public void destroy()
destroy

getServletInfo

getServletConfig
Servlet Methods
getServletInfo

init getServletInfo method returns information about the Servlet.

service
It is declared as: public java.lang.String getServletInfo()
destroy

getServletInfo

getServletConfig
Servlet Methods
getServiceConfig

init Returns a ServletConfig object, that contains initialization and start-up parameters for this
Servlet.
service
It is declared as: public ServletConfig getServletConfig()
destroy

getServletInfo

getServletConfig
Generic Servlet Abstract Class

• GenericServlet implements Servlet interface.

• It defines Servlet generic and is independent of protocols.

• It doesn't give implementation for service method of Servlet interface.

• If your Servlet extends Generic Class, implementing service method is necessary.


Generic Servlet Abstract Class Methods

public abstract class Extends java.lang.Object


GenericServlet implements Servlet, ServletConfig, and java.io.Serializable
java.lang.String
Returns a String containing the value of the named initialization parameter, or
getInitParameter(java.lang.St
returns null if the parameter does not exist
ring name)
Returns the names of the Servlet's initialization parameters as an Enumeration of
java.util.Enumeration
String objects, or returns an empty Enumeration if the Servlet has no initialization
getInitParameterNames()
parameters
ServletContext
Returns a reference to the ServletContext in which the Servlet is running
getServletContext()
java.lang.String
Returns the name of this Servlet instance
getServletName()
A convenient method which can be overridden so that there's no need to call
void init()
super.init(config)
Generic Servlet Abstract Class Methods

void init(ServletConfig Called by the Servlet container to indicate to a Servlet that the Servlet is being
config) placed into service
void log(java.lang.String Writes the specified message to a Servlet log file, prepended by the Servlet's
msg) name
void log(java.lang.String
Writes an explanatory message and a stack trace for a given Throwable throwable
message, java.lang.Throwable
exception to the Servlet log file, prepended by the Servlet's name
t)
abstract void
service(ServletRequest req, Allows the Servlet to respond to a request.
ServletResponse res)
HttpServlet Abstract Class Methods
It provides an abstract class to be sub-classed to create an HTTP Servlet suitable for a website.

Following is the list of methods:

public abstract class Extends GenericServlet


HttpServlet Implements java.io.Serializable

doGet Used if the Servlet supports HTTP GET requests

doPost Used for HTTP POST requests

doPut Used for HTTP PUT requests

doDelete Used for HTTP DELETE requests

init and destroy Used to manage resources that are held for the life of the Servlet

getServletInfo Used by the Servlet to provide information about itself


Advanced Java
Topic 3—Servlet Lifecycle
Servlet Lifecycle
The lifecycle of a Servlet is controlled by the container in which the Servlet has been deployed.

When a request is mapped to a Servlet, the container performs the following steps if an instance of the
Servlet does not exist.

Loads the Servlet class

Creates an instance of the Servlet class

Called once init method (ServletConfig config) Initiates and calls init()

service (HttpServletRequest req,


Ready to serve request
HttpServletResponse res)

Called once destroy() Handles multiple requests and


sends responses
Advanced Java
Topic 4—Configure and Deploy Servlet
Configure and Deploy Servlet

1. Create dynamic web project in eclipse


2. Add Server to project
3. Run Server (Apache Tomcat)
4. Create HTML file
5. Click on src and create Servlet
6. Create web.xml file
7. Configure a Servlet Definition
8. Configure a Servlet Mapping
9. Activating the Servlet in Web
Configure and Deploy Servlet
STEPS TO CREATE DYNAMIC WEB PROJECT IN ECLIPSE
Create dynamic web
project in eclipse

Add Server to project Open eclipse for EE

Run Server (Apache


Tomcat)
2. Click on “File in menu
Create HTML file
bar”
Create Java class( 4. Click on “Java Projects”
Servlet) 3. Click on “New”
5. Click on “Dynamic Web Projects”
Create web.xml file

Configure a Servlet
definition
Configure a Servlet
Mapping
Activating the Servlet
in Web
Configure and Deploy Servlet
STEPS TO CREATE DYNAMIC WEB PROJECT IN ECLIPSE
Create dynamic web
project in eclipse

Add Server to project

Run Server (Apache


Tomcat)

Create HTML file


6. Give name to project.
Create Java class(
Servlet) 7. Add web.xml by selecting check box.
8. Click on f”Finish”
Create web.xml file

Configure a Servlet
definition
Configure a Servlet
Mapping
Activating the Servlet
in Web
Configure and Deploy Servlet
STEPS TO ADD SERVER TO PROJECT
Create dynamic web
project in eclipse
1. Click on “Windows” in menu bar
Add Server to project
2. Click on “preference”
Run Server (Apache
Tomcat) 3. Click on “Server”

Create HTML file


4. Click on “Runtime Environment”
5. Add Server
Create Java class(
Servlet)

Create web.xml file

Configure a Servlet
definition
Configure a Servlet
Mapping
Activating the Servlet
in Web
Configure and Deploy Servlet
RUN SERVER (APACHE TOMCAT)
Create dynamic web
project in eclipse
1. Run Apache with eclipse
Add Server to project
2. Click on “Window”
Run Server (Apache
Tomcat) 3. Click on “show view”

Create HTML file 4. Click on ”server“


5. click on ”new server“
Create Java class(
Servlet) 6. Click on ”next“
Create web.xml file 7. Click on “next”, the server is now added to your project

Configure a Servlet 8. To start server, right click on “Tomcat server”


definition
9. Click on “start option”
Configure a Servlet
Mapping
Activating the Servlet
in Web We have already discussed the detailed steps in the installation guide that is
available on your LMS for download.
Configure and Deploy Servlet
CREATE HTML FILE
Create dynamic web
project in eclipse

Add Server to project

Run Server (Apache


Tomcat)

Create HTML file

Create Java class(


Servlet)

Create web.xml file

Configure a Servlet
definition
Configure a Servlet
Mapping
Activating the Servlet
in Web

All web pages like html, css, and jsp should be added in the WebContent folder
Configure and Deploy Servlet
CREATE JAVA CLASS (SERVLET)
Create dynamic web
project in eclipse

Add Server to project

Run Server (Apache


Tomcat)

Create HTML file

Create Java class(


Servlet)

Create web.xml file

Configure a Servlet
definition
Configure a Servlet
Mapping
Activating the Servlet
in Web
Configure and Deploy Servlet
CREATE web.xml FILE
Create dynamic web
project in eclipse
• The web.xml deployment descriptor is used by the web container to configure servlet
Add Server to project component. The Servlet definition also specifies the fully qualified class that implements the
component.
Run Server (Apache
Tomcat)
• The web container creates an instance of each Servlet definition in the deployment descriptor
Create HTML file
• There can be multiple Servlet definitions
Create Java class(
Servlet)

Create web.xml file

Configure a Servlet
definition
Configure a Servlet
Mapping
Activating the Servlet
in Web
Configure and Deploy Servlet
CONFIGURE A SERVLET DEFINITION
Create dynamic web
project in eclipse

Add Server to project

Run Server (Apache Web Server web .xml


Tomcat)

Create HTML file


Web Container
Create Java class(
Servlet) <servlet>
<servlet –name>logicalNameForServlet</servlet –name>
Create web.xml file <servlet –class>packageName.ClassName</servlet –class>
</servlet>
Configure a Servlet
definition <<View>>
Configure a Servlet ListLeagues
Mapping
Activating the Servlet
in Web
The web container will create only one, Servlet object for each
definition in the deployment descriptor
Configure and Deploy Servlet
CONFIGURE A SERVLET MAPPING
Create dynamic web
project in eclipse

Add Server to project


• The deployment descriptor is also used to configure a URL pattern that is used to invoke
the Servlet component.
Run Server (Apache
Tomcat) • The web container receives HTTP request for specific URLs, and it matches the URL to
either a physical component or a logical mapping to a Servlet component.
Create HTML file

Create Java class(


Servlet)

Create web.xml file

Configure a Servlet
definition
Configure a Servlet
Mapping
Activating the Servlet
in Web
Configure and Deploy Servlet
CONFIGURE A SERVLET MAPPING
Create dynamic web
project in eclipse

Add Server to project Web Server web .xml

Run Server (Apache


Tomcat)
Index.html
Create HTML file http://localhost:8080
/soccer/index.html
Create Java class( <servlet –mapping>
Servlet) <servlet –name>logicalNameForServlet</servlet –nam
<URL –pattern>/urlpattern</url –pattern>
Create web.xml file http://localhost:8080 </servlet -mapping>
/soccer/list_leagues. <<View>>
Configure a Servlet view
definition ListLeagues
Configure a Servlet
Mapping
Activating the Servlet
in Web The web container maps the URL of each request to either a physical web
resource (such as an HTML page) or to a logical web resource (such as a Servlet).
Configure and Deploy Servlet
CONFIGURE A SERVLET MAPPING
Create dynamic web
project in eclipse
When URL pattern becomes http://localhost:8080/projectname/check, Web
Add Server to project container looks in web.xml to find location of its servlet class.

Run Server (Apache <web-app>


Tomcat)
<servlet>
Create HTML file <servlet-name>HelloServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
Create Java class( </servlet>
Servlet)
<servlet-mapping>
Create web.xml file
<servlet-name>HelloServlet</servlet-name>
Configure a Servlet <url-pattern>/check</url-pattern>
definition </servlet-mapping>
Configure a Servlet
Mapping </web-app>
Activating the Servlet
in Web
Check is URL pattern, HelloServlet is logical name for servlet, and MyServlet is
servlet Java class
Configure and Deploy Servlet
ACTIVATING THE SERVLET IN WEB
Create dynamic web
project in eclipse

Add Server to project When the user selects the home page by the way of URL
http://localhost:8080/projectname/urlpattren, the web container responds with the HTML
Run Server (Apache code for the home page.
Tomcat)

Create HTML file

Create Java class(


Servlet)

Create web.xml file

Configure a Servlet
definition
Configure a Servlet
Mapping
Activating the Servlet
in Web
Advanced Java
DEMO—Configure and Deploy Servlet
Advanced Java
Topic 5—ServletsRequest, ServletResponse

• ServletRequest
• ServletRequest Interface
• Servlet Response
ServletRequest

public interface ServletRequest

• It defines an object to provide client request information to a Servlet.

• The Servlet container creates a ServletRequest object.

• Servlet Container calls service method by passing ServletRequest object.

• This object provides data including parameter name and values, attributes, and an input stream.
ServletRequest Interface

java.lang.Object
Returns the value of the named attribute as an object, or returns null if no
getAttribute(java.lang.Str
attribute of the given name exists.
ing name)
java.util.Enumeration Returns an Enumeration containing the names of the attributes available to
getAttributeNames() this request.
java.lang.String
Returns the name of the character encoding used in the body of this request.
getCharacterEncoding()
Returns the length of the request body (in bytes) and is made available by the
int getContentLength()
input stream, or -1 if the length is not known.
java.lang.String Returns the MIME type of the body of the request, or returns null if the type is
getContentType() not known.
ServletInputStream
Retrieves the body of the request as binary data using a ServletInputStream.
getInputStream()
java.util.Locale Returns the preferred Locale that the client will accept content, based on the
getLocale() Accept-Language header.
Returns an Enumeration of Locale objects indicating the locales (in decreasing
java.util.Enumeration
order starting with the preferred locale) that are acceptable to the client based
getLocales()
on the Accept-Language header.
ServletRequest Interface
Returns the host name of the Internet Protocol (IP) interface on
java.lang.String getLocalName()
which the request was received
Returns the Internet Protocol (IP) port number of the interface on
int getLocalPort()
which the request was received
java.lang.String Returns the value of a request parameter as a String, or null if the
getParameter(java.lang.String name) parameter does not exist
java.util.Map getParameterMap() Returns a java.util.Map of the parameters of this request
java.util.Enumeration Returns an Enumeration of String objects containing the names of
getParameterNames() the parameters contained in this request
java.lang.String[] Returns an array of String objects containing all of the values the
getParameterValues(java.lang.String given request parameter has, or returns null if the parameter does
name) not exist
Returns the name and version of the protocol the request uses in
java.lang.String getProtocol() the form protocol/majorVersion.minorVersion, for example,
HTTP/1.1
Retrieves the body of the request as character data using a
java.io.BufferedReader getReader()
BufferedReader
void setAttribute(java.lang.String
Stores an attribute in this request
name, java.lang.Object o)
ServletResponse

public interface ServletResponse

• It defines an object to assist a Servlet in sending a response to the client.

• The Servlet Container creates these objects to call Servlet's service method.

• To send binary data in a MIME body response, use the ServletOutputStream returned by
getOutputStream().

• To send character data, use the PrintWriter object returned by getWriter(). To mix binary and text data,
for example, to create a multipart response, use a ServletOutputStream and manage the character
sections manually.
Advanced Java
Topic 5—ServletConfig, ServletContext

• ServletConfig, ServletContext
• ServletConfig Methods
ServletConfig, ServletContext

ServletConfig:

1. The config object is created by the web container based on the initialization parameters specified in
the deployment descriptor

2. One ServletConfig per Servlet

ServletContext:

1. To share application - specific data across independent web components


2. One ServletContext per application
3. The context object is accessible to all Servlets in web application
4. A ServletContext object is the runtime representation of the web application
ServletConfig Methods

java.lang.String
Returns a String containing the value of the named initialization parameter,
getInitParameter(java.lang.String
or returns null if the parameter does not exist
name)
Returns the names of the servlet's initialization parameters as an
java.util.Enumeration
Enumeration of String objects, or returns an empty Enumeration if the
getInitParameterNames()
servlet has no initialization parameters
ServletContext getServletContext() Returns a reference to the ServletContext in which the caller is executing.
java.lang.String getServletName() Returns the name of this servlet instance
Defines a set of methods that a servlet uses to communicate with its servlet
public interface ServletContext container, for example, to get the MIME type of a file, dispatch requests, or
write to a log file
java.lang.Object
Returns the servlet container attribute with the given name, or returns null
getAttribute(java.lang.String
if there is no attribute by that name
name)
ServletConfig Methods

java.util.Enumeration Returns an Enumeration containing the attribute names available within


getAttributeNames() this servlet context
ServletContext
Returns a ServletContext object that corresponds to a specified URL on the
getContext(java.lang.String
server
uripath)
java.lang.String
Returns a String containing the value of the named context-wide
getInitParameter(java.lang.String
initialization parameter, or returns null if the parameter does not exist
name)
Returns the names of the context's initialization parameters as an
java.util.Enumeration
Enumeration of String objects, or returns an empty Enumeration if the
getInitParameterNames()
context has no initialization parameters
Advanced Java
DEMO—ServletConfig and ServletContext
Advanced Java
Topic 6—Servlet Scopes and Attributes

• Servlet Attributes
• Attribute Specific Methods
Servlet Attributes

Attributes allow data to be stored and used in inter servlet communication.

The methods associated with attribute manipulation are:

Attribute Scope

Attribute Scope of data


ServletRequest Duration of the request
HttpSession While the client is active
ServletContext The life of the web application

We will learn about Session scope in lesson 3 and management.pageContext is described in


JSP (lesson 4)
Attribute Specific Methods

1. public void setAttribute (String name, Object object): This method is used to set the given
object in the application scope.

2. public Object getAttribute(String name): This method is used to return the attribute for the
specified name.

3. public Enumeration getInitParameterNames(): This method is used to return the names of the
context's initialization parameters as an Enumeration of String objects.

4. public void removeAttribute(String name): This method is used to remove the attribute with
the given name from the servlet context.
Advanced Java
Topic 7—Servlet Collaboration

• What is Servlet Collaboration?


• Ways of Servlet Collaboration
• Forwarding and Redirecting
• forward() method
• include() method
• RequestDispatcher Interface
What is Servlet Collaboration?

The Servlet collaboration involves sharing of information among the servlets.

Collaborating servlets is passing the common information that is to be shared directly by one servlet to
another servlet of html or jsp through various invocations of methods.

Servlet should know about the other servlets with which it is collaborated.
Ways of Servlet Collaboration

• Using RequestDispatchers include() and forward() method;

• Using HttpServletResponse sendRedirect() method;

• Using ServletContext setAttribute() and getAttribute() methods;


Forwarding and Redirecting

• RequestDispatcher interface is used to forward request and response objects to another Servlet

• sendRedirect method is used for Redirecting request and response object

• HttpServletResponse has sendRedirect method: response.sendRedirect(“url”);

• HttpServletRequest has getRequestDispatcher method that returns RequestDispatcher object

• There are two methods, forward and include


forward() method

2. forward(-,-)
ServletOne ServletSecond

1. request

Response 3. Response is generated

client 4. Response is sent back to the browser


Response

forward() method
forward() method: Syntax

RequestDispatcher rd=

request.getRequestDispatcher(“url_pattern_for_servlet or html_file_name”);

rd.forward(request,response)
include() method

2. include(-,-)
ServletOne ServletSecond

1. request 3. Response of Servlet2 is


included in Servlet 1 response

4. Final response
is generated

5. Final response is
client sent back to the client
Response Response

include() method
include() method: Syntax

RequestDispatcher rd= request.getRequestDispatcher(“url_pattern_for_servlet or html_file_name”);

rd.include(request,response);
RequestDispatcher Interface

Validate Servlet

NO YES forward to Welcome Servlet


index.html Is
Valid?
include html file

Sorry username and password error! Welcome, username


___________________
___________________
___________________
---------------------------
---------------------------
Key Takeaways

Servlet is a Java program that can perform dynamic operations and send to web
server. The web server then sends this response to web client.

Web container is built on top of the Java SE platform and implements the Servlet
API and the services required to process HTTP (and other Transmission
Control/Internet Protocol [TCP/IP]) requests.

The lifecycle of a Servlet is controlled by the web container in which the Servlet has
been deployed.

Servlet API contains a number of classes and interfaces that defines the contracts
between a servlet class and the runtime environment provided for an instance by
a conforming servlet container.

Collaborating servlets is passing the common information that is to be shared


directly by one servlet to another servlet of HTML or JSP through various
invocations of the methods.
Quiz
QUIZ
Which package contain Servlet interface?
1

a. javax.Servlet

b. javax.Servlet.http

c. None Of the Above

d. Both

e. java.Servlet

The correct answer is b


QUIZ
Which method is called only once?
2

a. init()

b. service()

c. destroy()

d. getServletInfo()

e. getServlet()
The correct answer is b
Thank You
Advanced Java
Lesson 3—Java Servlet II

© Simplilearn. All rights reserved.


Learning Objectives

Discuss Session Management

Explain Listeners in Java EE

Describe Filters in Java EE


Advanced Java
Topic 1—Session Management

• Stateless Web Application


• Stateful Web Application
• Session Management and its types
Stateless Web Application

We have learned that web applications are stateless (by default) if given protocol is HTTP (stateless protocol).

It does not allow or provide data access to previous request during the processing of current request in
the Servlet or JSP.

In stateless web app, there is no way to preserve client data across multiple requests:

Create connection
1 Request 2

Client Server

3 Response 4
Close connection
Stateful Web Application

• A web application that can remember or use the data of previous request during the processing of
current request is a called stateful web application.

• In servlet API, there are different ways of making web application stateful so that it remembers
client data across request from same browser.

• Making web application stateful is known as session tracking or session management.

Create connection
1 Request 2
Server
Client Identifies the previous
request state through
session management
3 Response 4
Close connection
Introduction to Session Management

Session Management is a mechanism used by the web container to store session information for a
particular user.

Session is a conversional state between client and server, and it can consist of multiple requests and
responses between client and server. Sessions are used for maintaining user specific state, including
persistent objects.

User Session: It refers to a series of user application interactions that are tracked by the server.
Types of Session Management

1. Hidden Form Field

2. URL Writing

3. Cookies

4. HttpSession
Hidden Form Field

Hidden Form • When Server sends response for one particular request, it sends one hidden file attached to it
Field
• Client gets response with one Hidden Field
URL Writing
• In Hidden Field name and value are set

Cookie • If the same page sends request the next time, server can recognize it by getting the parameter
of Hidden Field

HttpSession <input type =”hidden field” name=”somename” value=”somename”/>

One of the limitations of a Hidden Form Field is that it requires extra form
submission on each page.
Using Hidden Form Field to Manage Session

Browser Client
Hidden Form
Field Form 1
Request 1
Name Servlet 1
URL Writing
Address
(Servlet 1 sends a hidden file
with name and attribute)
Cookie
Form 2
Request 2 Servlet 2
HttpSession

Age
(Servlet 2 can get Hidden file
(Hidden file with name and attribute) with name and attribute)
URL Writing

Hidden Form
• In URL writing, one token is appended to URL itself
Field
• This token contains one name and one value
URL Writing
• With the help of hyperlink, token’s name and values are passed to server

• A name and a value is separated using an equal = sign, a parameter name/value pair is
Cookie separated from another parameter using the ampersand(&)

• Code: url?name1=value1&name2=value2&?
HttpSession

URL writing works with hyperlinks and sends text information.


URL Writing to Exchange Session Information

Browser Client
Hidden Form
Field Form 1
Request 1
Name Servlet 1
URL Writing
Address

Cookie
Form 2

HttpSession hyperlink Request 2


Servlet 2
Age
url?name1=value1&name2=value2&?
Cookie

Hidden Form • Servlet API provides javax.servlet.http.Cookie class to maintain session


Field
• This class extends Object class and implements Cloneable interface

Url Writing • While creating a cookie, a small amount of information is sent by a Servlet to a web
browser, saved by the browser, and later sent back to the server

Cookie • Cookie has a name, value, and optional attribute

• The browser returns cookies to the servlet by adding fields to HTTP request headers
HttpSession
Attributes of a Cookie

Hidden Form
Field • Name: Name of the cookie
• Value: Value of the cookie
Url Writing • Comment: Text explaining purpose of cookie
• Max-Age: Time in seconds after which the client should not send cookie back to server

Cookie • Domain: Domain to which the cookie should be sent


• Path: The path to which the cookie should be sent
• Secure: Specifies if cookie should be sent via https
HttpSession
Cookies to Exchange Session Information

Hidden Form
Field

Url Writing
Request

Client Server
Response + Cookie
Cookie

Request + Cookie
HttpSession
Constructor and Methods of Cookie Class

• Constructs a cookie with a specified name and value.


Hidden Form
Field public Cookie(java.lang.String name,
java.lang.String value)

Url Writing
• Cookie class has the following methods:

Cookie o getName(): To get the Name of Cookie


o getValue(): To get the value of Cookie
o setMaxAge(): To set maximum age of Cookie
HttpSession
o setValue(): To set value to Cookie
Creating Cookie Object

Code to create Cookie object:


Hidden Form
Field Cookie cookieObj = new Cookie(“name”,”value”);

Code to add Cookie to browser response:


Url Writing
response.addCookie(cookieObj);

Cookie Code to retrieve cookie object:

Cookie cookies[]=request.getCoookies();
HttpSession
for(Cookie cookie : cookies)
{
out.print("name = "+ cookie.getName());
out.print("value="+cookie.getValue());
}
Cookie: Limitations

Hidden Form
Field
• All data for a session are kept on the client. Corruption, expiration, or purging of cookie
files can result in incomplete, inconsistent, or missing information.
Url Writing
• Cookies may not be available for many reasons: the user may have disabled them, the
browser version may not support them, the browser may be behind a firewall that filters
Cookie cookies, and so on.

HttpSession
Session Object APIs

Hidden Form • javax.servlet.http.HttpSession interface provides a way to identify one user across more than
Field one page

• Servlet Container uses this interface to create a session between Http Client and Http Server
Url Writing
• Servlet can view and manipulate the information about servlet

Cookie • javax.servlet.http.HttpSession has method named as getSession

• getSession method gets the current valid session associated with this request if create is
false or, if necessary, it creates a new session for the request
HttpSession
HttpSession Methods

Returns the maximum time interval, in seconds, that


Hidden Form int getMaxInactiveInterval() the servlet container will keep this session open
Field between client accesses.
Returns a string containing the unique identifier
String getId()
assigned to this session.
Url Writing
void Specifies the time, in seconds, between client requests
setMaxInactiveInterval(int interval) before the servlet container will invalidate this session.
Cookie Invalidates this session and then unbinds any objects
Void invalidate()
bound to it.
Returns the current session associated with this
HttpSession HttpSession getSession() request, or if the request does not have a session, it
creates one.
Returns the current HttpSession associated with this
HttpSession
request or, if there is no current session and create is
getSession(boolean create)
true, it returns a new session.
HttpSession for Session Tracking

Browser
Hidden Form Client
Field Form 1
HttpSession Object
Name Request 1
Url Writing
Address Servlet 1
Set attribute
Cookie value. Example:
request
Form 2 attributes can
HttpSession have name and
Servlet 2 address value
Age Request 2
Advanced Java
DEMO—Session Management in Servlet
Advanced Java
Topic 2—Listeners in Java EE

• Events in Servlet API


• Events Class Servlet API
• Event Listener Interface
Events in Servlet API

Change in the state of an object is known as an event, which occurs during the lifecycle of an object.

There are important events related to a web application and Servlets which are handled by event
listener.

To be notified of events, a custom class, that implements the correct listener interface, needs to be
coded and the listener class needs to be deployed via web.xml.
Event Class Servlet APIs

1. ServletRequestEvent
2. ServletContextEvent
3. ServletRequestAttributeEvent
4. ServletContextRequestArrtibuteEvent
5. HttpSessionEvent
6. HttpSessionEventBindingEvent
Event Listener Interface

Listeners are objects that notify whenever any event occurs. They contain event processing logics.

Listener Interfaces in servlet APIs are as follows:


1. ServletRequestListener
2. ServletContextListener
3. ServletRequestAttributeListener
4. ServletContextAttributeListener
5. HttpSessionListener
6. HttpSessionAttributeListener
7. HttpSesionBindingListener
8. HttpSessionActivationListener
Event Listener Interface
ServletRequestList
ener ServletRequestListener

ServletContextList
ener • It handles servlet request event

ServletRequestAttr • It notifies when servlet container is initialized and destroys request object
ibuteListener
• Servlet container generates servlet request event when it creates and destroys servlet.request object
ServletContextAttri
butetListener Methods:

HttpSessionListener void requestInitialized(ServletRequestEvent e)


// when Servlet creates request object
HttpSessionAttribu
teListener void requestDestroyed(ServletRequestEvent e)
// When Servlet destroy request object
HttpSesionBinding
Listener

HttpSessionActivat
ionListener
Event Listener Interface
ServletRequestList
ener ServletContextListener

ServletContextList
ener
• It handles and processes ServletContextEvent.
ServletRequestAttr • It receives notifications when servlet container creates or destroys context object.
ibuteListener

ServletContextAttri
Methods:
buteListener
void contextInitialized()
HttpSessionListener
void contextDestroyed()

HttpSessionAttribu
teListener

HttpSesionBinding
Listener

HttpSessionActivat
ionListener
Event Listener Interface
ServletRequestList
ener ServletRequestAttributeListener

ServletContextList
ener • It receives notification of ServletRequestAttribute event.

ServletRequestAttr • It is used to find out when an attribute has been added, removed, or replaced from request object.
ibuteListener
Methods:
ServletContextAttri
buteListener void attributeAdded(ServletRequestAttributeEvent srae): Receives notification that an

HttpSessionListener
attribute has been added to the ServletRequest
void attributeRemoved(ServletRequestAttributeEvent srae : Receives notification that an
HttpSessionAttribu
teListener attribute has been removed from the ServletRequest

HttpSesionBinding
void attributeReplaced(ServletRequestAttributeEvent srae): Receives notification that
Listener
an attribute has been replaced on the ServletRequest.
HttpSessionActivat
ionListener
Event Listener Interface
ServletRequestList
ener ServletContextAttributeListener

ServletContextList
ener It receives and processes ServletContextAtrribute event.

ServletRequestAttr
ibuteListener
Methods:

ServletContextAttri
buteListener void attributeAdded(ServletContextAttributeEvent event):
Receives notification that an attribute has been added to the ServletContext.
HttpSessionListener
void attributeRemoved(ServletContextAttributeEvent event):
HttpSessionAttribu Receives notification that an attribute has been removed from the ServletContext.
teListener
void attributeReplaced(ServletContextAttributeEvent event):
HttpSesionBinding
Listener Receives notification that an attribute has been replaced from the ServletContext.

HttpSessionActivat
ionListener
Event Listener Interface
ServletRequestList
ener HttpSessionListener

ServletContextList
ener It receives and processes http session events. This listener is used to find out total active users.
ServletRequestAttr
ibuteListener
Methods:

ServletContextAttri void sessionCreated(HttpSessionEvent se): Receives notification that a session has been
buteListener
created.
HttpSessionListene
r void sessionDestroyed(HttpSessionEvent se): Receives notification that a session is

HttpSessionAttribu about to be invalidated.


teListener

HttpSesionBinding
Listener

HttpSessionActivat
ionListener
Event Listener Interface
ServletRequestList
ener HttpSessionAttributeListener

ServletContextList
ener • It handles and processes http session binding event.
• It is used to find out when an attribute has been added or replaced from session.
ServletRequestAttr
ibuteListener
Methods:
ServletContextAttri
buteListener void attributeAdded(HttpSessionBindingEvent event): Receives notification that an

HttpSessionListene attribute has been added to a session


r
void attributeRemoved(HttpSessionBindingEvent event): Receives notification that
HttpSessionAttribu an attribute has been removed from a session
teListener
void attributeReplaced(HttpSessionBindingEvent event): Receives notification that
HttpSesionBinding
Listener
an attribute has been replaced in a session

HttpSessionActivat
ionListener
Event Listener Interface
ServletRequestList
ener HttpSesionBindingListener

ServletContextList
ener
• It handles and processes http session binding event.
ServletRequestAttr • It notifies when the object of the class has been added or removed from the session.
ibuteListener

ServletContextAttri Methods:
buteListener

void valueBound(HttpSessionBindingEvent event): Notifies the object that it is


HttpSessionListene
r
being bound to a session and identifies the session.
HttpSessionAttribu void valueUnbound(HttpSessionBindingEvent event): Notifies the object that it
teListener
is being unbound from a session and identifies the session.
HttpSesionBinding
Listener

HttpSessionActivat
ionListener
Event Listener Interface
ServletRequestList
ener HttpSessionActivationListener

ServletContextList
ener • It receives notification of http session event.

ServletRequestAttr • It notifies when the session migrates from one JVM(Java Virtual Machine) to another.
ibuteListener
Methods:
ServletContextAttri
buteListener
void sessionDidActivate(HttpSessionEvent se) : Notifies that the session has just been activated
HttpSessionListene
r void sessionWillPassivate(HttpSessionEvent se): Notifies that the session is about to be passivated

HttpSessionAttribu
teListener

HttpSesionBinding Application events provide notifications of a change in state of the servlet context (each Web
Listener Application uses its own servlet context) or of an HttpSession object.

HttpSessionActivat
ionListener
Servlet Listener Configuration

@WebListener annotation is used to declare a class as Listener. However, the class should implement
one or more of the Listener interfaces.

To define listener in web.xml:

<listener>
<listener-class>
packagename.ClassNameOfImplementedListener
</listener-class>
</listener>
Advanced Java
DEMO—Implementing Listener Interface to Handle Events
Advanced Java
Topic 3—Filters in Java EE

• Why Filters?
• What is a Filter?
• Filter in Servlets
Why Filters?

Filters are used when there is a need:

• For an operation to occur every time a particular request is made


• To perform one operation on other request in the web application
• To allow one operation to be turned off at deployment

The filter API interface can be found in javax.servlet package


What is a Filter?

• A filer is an interface used to filter tasks on the request to a resource (a servlet or static content), on the
response from a resource, or both

• It has 3 methods (lifecycle)

public void init(FilterConfig config);


public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain);
public void destroy();

• Filters are configured in deployment descriptor of a web application


Filter in Servlets

http request

Filter
request object request object

Servlet Container Servlet

response object response object

http response
Filter Types

1. Request Filter: Contains only pre-request processing logic.

2. Response Filter: Contains post-response generation logic.

3. Request-Response Filter: Contains both pre-request processing and post-response generation logic.
Developing and Mapping a Filter Class

Declaring a Filter in the web.xml

<filter>
<filter-name> onelogicalname </filter-name>
<filter-class> filterclassname </filter-class>
</filter>

Mapping a Filter in the web.xml

<filter-mapping>
<filter-name> onelogicalname </filter-name>
<furl-pattern> /urlpatter </url-pattern>
</filter-mapping>
Writing a Filter Program

To write a filter program:

• Create a Java class to implement Filter interface that has the following three methods:

o init() method – It is called once when the container instantiates a filter


o doFilter() method – It is called for every request intercepted by the filter
o destroy() method - Before the web container removes a filter instance from service, the destroy method is called

• Create one web.xml file to configure the filter


Filter Chain

If multiple filters are configured for servlet, they are executed in the same order in which they are defined in
web.xml

http request

request object request object


Servlet Servlet
Container
response object response object

Pre-filter Filter Post-filter


http response
Key Takeaways

A web application that can remember or use the data of previous request
during the processing of current request is a called stateful web application.

Session Management is a mechanism used by the Web container to store session


information for a particular user.

Hidden Form Field, Url Writing, Cookies, and HttpSession are types of session
management.

To be notified of events, a custom class, that implements the correct listener


interface, needs to be coded and the listener class needs to be deployed via
web.xml.
Quiz
Thank You
Advanced Java
Lesson 4—Java JSP

© Simplilearn. All rights reserved.


Learning Objectives

Discuss JSP Architecture

Understand JSP Lifecycle

Explain how to create a JSP and run it in a Web Application

Discuss JSP elements and Tags

Describe JSTL and Custom Tag Libraries


Advanced Java
Topic 1—Introduction to JSP
What Is JSP?

JSP (Java Server Pages) is a text document consisting of Hyper Text Markup Language(HTML), Extensible
Markup language(XML), and JSP elements which can be expressed in standard and XML syntax.
Advantages of JSP

JSP is used to develop web based applications. It supports the separation of presentation and business
logic as follows:

• Web designers can design and update pages without learning the Java programming language.
• Java technology programmers can write code without having to be concerned with web page design.
• It provides the optional mechanism to configure web application file (web.xml).
• JSP programming eliminates the need for repeated deployment (saving the JSP and making a
request whenever the JSP is changed). The automatic deployment is taken care by container JASPER
[JSP Execution Environment].
• JSP programming provides custom tags development.
• JSP programming environment provides automatic page compilation.

To configure JSP, create a dynamic web project in eclipse, configure Apache Tomcat, and create
JSP file in web content. The steps are already discussed in the installation guide in your LMS.
JSP Architecture

1 Request
(Controller)
5 Response Servlet

2 (Model)
3 Java Bean

BROWSER (View) JSP


4

Application Server Enterprise Server/Data


Sources
Think Through!

JSP is used to dynamically generate web content on a server and return it to the
client. This can also be done using servlet.

Why do we need JSP?


Think Through!

JSP performs a number of tasks.

To understand this, let’s learn about the differences between Java JSP and Servlets.
JSP vs. Servlet

JSP Servlets
JSP is a web page scripting language that can generate Servlets are Java programs that are
dynamic content. Compiled. They create dynamic pages.
It is easier to code in JSP than in Java Servlet. Involves writing a lot of code
In MVC model, JSP acts as a view. In MVC model, Servlets act as controllers.
Custom tag can directly call Java beans. There is no such custom tag.
JSP is generally preferred when there is not much processing Servlets are best for use when there is more
of data required. It runs slower compared to Servlet as it takes processing and manipulation involved.
compilation time to convert into Java Servlet. Servlet runs faster than JSP.
Web Container Responsibilities

What does a web container do in a JSP?

• It provides standard libraries required for coding.

• It provides a suitable environment for execution.

• It calls the call-back methods at appropriate times.

• It maintains the life cycle of the program.


JSP API

JSP technology is based on JSP API. It consists of the following packages:

• javax.servlet.jsp (Classes and interface for core JSP)

• javax.servlet.jsp.tagext (Java server pages library)

• javax.servlet.jsp.el (Expression language)


Advanced Java
Topic 2—JSP Lifecycle
JSP Lifecycle

1. Translation of JSP to Servlet code


2. Compilation of Servlet to bytecode
3. Loading Servlet class
4. Creating Servlet instance
5. Initialization by calling _jspInit() method
6. Request processing by calling _jspService() method
7. Destroying object by calling _jspDestroy() method
Translation of JSP Lifecycle
JSP to Servlet
code TRANSLATION OF JSP TO SERVLET CODE
Compilation of
Servlet to In the first step, the web container translates the JSP file into a Java source file that contains a servlet
bytecode
class definition.
Loading Servlet
class
Web Server
Creating Servlet
instance 1
hello.jsp hello_jsp.java
Initialization by
calling _jspInit()
method
Request
processing by
calling http://localhost:8080/projectname/hello.jsp
_jspService() Web Container
method
Destroying
object by calling
_jspDestroy()
method
Translation of JSP Lifecycle
JSP to Servlet
code COMPILATION OF SERVLET TO BYTECODE
Compilation of
Servlet to
bytecode
hello.jsp public class hello_jsp extends
Loading Servlet HttpServlet
class <html> {
<head> public void
<title> My First JSP</title> _jspService(HttpServletRequest
Creating Servlet request,
instance </head>
<% HttpServletResponse response)
Translation to {
Initialization by int count=0;
servlet PrintWriter out= response.getWriter();
calling _jspInit() %>
method <body> response.setContentType(“text/html”);
Page count is: out.write(“<html><body>”);
Request int count=0;
processing by
<% out.println(++count); %>
<body> out.write(“Page count id “);
calling
_jspService() </html> out.write(++count);
method out.write(“</body></html>”);
}
Destroying
object by calling
}
_jspDestroy()
method
Translation of JSP Lifecycle
JSP to Servlet
code COMPILATION OF SERVLET TO BYTECODE
Compilation of
Servlet to In the second step, the web container compiles the servlet source code into a Java class file.
bytecode

Loading Servlet
class
Web Server

Creating Servlet 1
instance hello.jsp hello_jsp.java

Initialization by
calling _jspInit()
2
method
Request
processing by http://localhost:8080/projectname/hello.jsp
calling Web Container hello_jsp.class
_jspService()
method
Destroying
object by calling
_jspDestroy()
method
Translation of JSP Lifecycle
JSP to Servlet
code LOADING SERVLET CLASS
Compilation of
Servlet to In the third step, the servlet class bytecode is loaded into the web container’s JVM software
bytecode using a class loader.
Loading Servlet
class
Web Server
Creating Servlet 1
instance hello.jsp hello_jsp.java
Initialization by
calling _jspInit()
method 2

Request
processing by http://localhost:8080/projectname/hello.jsp
3
calling
_jspService()
Web Container hello_jsp.class
method
Destroying
object by calling
_jspDestroy()
method
Translation of JSP Lifecycle
JSP to Servlet
code CREATING SERVLET INSTANCE
Compilation of
Servlet to In the fourth step, the web container creates an instance of the servlet class.
bytecode

Loading Servlet
class
Web Server
Creating Servlet 1
instance hello.jsp hello_jsp.java

Initialization by
calling _jspInit()
method 2
Web Container
Request
processing by http://localhost:8080/projectname/hello.jsp hello_jsp 3
calling
_jspService() hello_jsp.class
method 4
<<create>>
Destroying
object by calling
_jspDestroy()
method
Translation of JSP Lifecycle
JSP to Servlet
code INITIALIZATION BY CALLING _jspInit() METHOD
Compilation of
Servlet to In fifth step, the web container initializes the servlet by calling the jspInit method.
bytecode

Loading Servlet
class
Web Server
Creating Servlet
1
instance
hello.jsp hello_jsp.java
Initialization by
calling _jspInit()
method 2
Web Container
Request
processing by http://localhost:8080/projectname/hello.jsp
calling hello_jsp 3
_jspService() hello_jsp.class
method 5 4
Destroying jspInit <<create>>
object by calling
_jspDestroy()
method
Translation of JSP Lifecycle
JSP to Servlet
code REQUEST PROCESSING BY CALLING _jspService() METHOD
Compilation of
Servlet to The initialized servlet can now service requests. With each request, the web container can call the
bytecode
_jspService methods for the converted JSP page.
Loading Servlet
class
Web Server
Creating Servlet
instance 1
hello.jsp hello_jsp.java
Initialization by
calling _jspInit() 6
method 2
_jspService Web Container
Request
processing by
calling http://localhost:8080/projectname/hello.jsp hello_jsp 3
_jspService() hello_jsp.class
method 5 4
Destroying jspInit <<create>>
object by calling
_jspDestroy()
method
Translation of JSP Lifecycle
JSP to Servlet
code DESTROYING OBJECT BY CALLING _jspDestroy() METHOD
Compilation of
Servlet to When the web container removes the JSP servlet instance from services, it first calls the jspDestroy
bytecode method to allow the JSP page to perform any requirement clean up.
Loading Servlet
class
Web Server
Creating Servlet 1
instance hello.jsp hello_jsp.java
Initialization by
6
calling _jspInit() 7
method 2
_jspService
Web Container
Request
processing by http://localhost:8080/projectname/hello.jsp
calling
hello_jsp 3
_jspService() hello_jsp.class
method 5 4
Destroying jspInit <<create>>
object by calling
_jspDestroy()
method
What are Implicit Objects?

Implicit objects are the Java objects that the JSP Container makes available to the developers in each page;
the developers can call them directly without explicitly declaring them.

• JSP technology has 9 implicit variables. They represent commonly used objects for servlets that JSP page
developers might need to use.

• You can retrieve HTML from parameter data by using the request variable, which represents the
HttpServletRequest object.
Implicit Variables

Variable Name Class Name Description

request javax.servlet.http.HttpServletRequest The HttpServletRequest object associated with the request

response javax.servlet.http.HttpServletResponse The HttpResponse object associated with the response that is
sent back to the browser

out javax.servlet.jsp.JspWriter The JspWriter object associated with the output stream of the
response
session javax.servlet.http.HttpSession The HttpSession object associated with the session for the
given user of the request—only meaningful if the JSP page is
participating in an HTTP session
application javax.servlet.ServletContext The ServletContext object for the web application

config javax.servlet.ServletConfig The ServletConfig object for the web application

pageContext javax.servlet.jsp.PageContext The pageContext object that encapsulates the environment of


a single request for this JSP page
exception java.lang.Object.Throwable The Throwable object that was thrown by some other JSP
page—only available in a JSP error page
page java.lang.Object Represents current JSP page
Advanced Java
Topic 3—Creating a JSP and running it in a Web Application
Creating a JSP and Running It In a Web Application

Unlike servlets, deploying JSP pages is as easy as deploying static pages. JSP pages can be placed in the
same directory hierarchy as HTML pages.

In the development environment, JSP pages are placed in the web directory. In the deployment
environment, JSP pages are placed in the top-level directory of the web application.

Apache Tomcat

Webapps

myproject

firstjspexample.jsp

index.html
Creating a JSP and Running It In a Web Application

1. Configure Server
2. Create Dynamic Web Project
3. Create JSP file in WebContent Folder
4. Create html file in WebContent folder
Advanced Java
DEMO—Writing JSP Program with Implicit Objects
Advanced Java
Topic 4—Working with JSP Elements
JSP Elements

JSP elements in a JSP page can be expressed in two types of syntax:

1. standard
2. XML

Syntax Elements Standard Syntax XML Syntax

1. Comments <% -- -- %> <!-- -->

<jsp: declaration>
2. Declaration <% ! %>
</jsp: declaration>
<%@ include %> <jsp : directive include../>
3. Directives <% @page %> <jsp:directive page ../>
<%@taglib %> <xmlns :prefix = “tag library url”>
<jsp:expression>
4. Expression <% = %>
</jsp:expression>
<jsp:scriptlet>
5. Scriptlets <% %>
</jsp:scriptlet>
JSP Comment Tag

• JSP comment is used when you are creating a JSP page and want to put in comments about what
you are doing.

• JSP comments are only seen in the JSP page.

• These comments are not included in servlet source code during translation phase; they do not
appear in the HTTP response.

Comment Tag Declaration Tag Directive Tag Expression Tag Scriptlets Tag
JSP Declaration Tag

• We can declare a variable or method in JSP inside declaration tag.

• Declaration is made inside the Servlet class but outside the service (or any other method).

• We can declare static member, instance variable, and method inside declaration tag.

Comment Tag Declaration Tag Directive Tag Expression Tag Scriptlets Tag
JSP Directive Tag

This tag is used for special instruction to web container. It includes three tags:

• <% @ page %> defines page dependent properties such as language session error page.

• <%@ taglib %> declares tag library used in the page.

• <%@ include %> defines file to be included.

Comment Tag Declaration Tag Directive Tag Expression Tag Scriptlets Tag
JSP Directive Tag
<% @ page %>

• <% @ page %> defines page-dependent properties such as language session error page.
<% @ page %>
• It defines a number of page-dependent properties that communicate with the web container.

<%@ taglib %>

Syntax:-
<%@ include %>
<% @ page attribute =”value” %>

Comment Tag Declaration Tag Directive Tag Expression Tag Scriptlets Tag
JSP Directive Tag
<% @ page %> ATTRIBUTES

• import
• language
<% @ page %> • extends
• session
<%@ taglib %> • isThreadSafe
• isErrorPage
<%@ include %> • errorPage
• contentType
• autoFlush
• buffer

Comment Tag Declaration Tag Directive Tag Expression Tag Scriptlets Tag
JSP Directive Tag
<%@ taglib %>

<%@ taglib %> declares the tag library used in the page. JSP allows you to define custom JSP
<% @ page %> tags that look like HTML or XML tags:

• A tag library is a set of user-defined tags that implements custom behavior.


<%@ taglib %>
• A taglib directive is used to define the tag library that the current JSP page uses.
• A JSP page might include several tag libraries.
<%@ include %>

Comment Tag Declaration Tag Directive Tag Expression Tag Scriptlets Tag
JSP Directive Tag
<%@ include %>

• <%@ include %> defines the file to be included and the source code.
<% @ page %>
• It has an attribute for file.

<%@ taglib %>

<%@ include %>

Comment Tag Declaration Tag Directive Tag Expression Tag Scriptlets Tag
JSP Expression Tag

• Expressions are evaluated when a JSP page is requested. The results are converted into String and
fed to the print method of the implicit object.

• If the result cannot be converted into string, an error will be raised at translation time.

• If this is not detected at translation time, a classCastException will be raised at request processing
time.

Comment Tag Declaration Tag Directive Tag Expression Tag Scriptlets Tag
JSP Scriptlet Tag

• Scriptlet tag allows you to write java code inside JSP page.

• Scriptlet tag implements the _jspService method functionality by writing script/Java code.

• Everything written inside the scriptlet tag is compiled as Java code.

Comment Tag Declaration Tag Directive Tag Expression Tag Scriptlets Tag
Caution
WHEN TO USE DECLARATION TAG OVER SCRIPLET TAG

• If you want to include any method in your JSP file, use declaration tag.

• During translation phase of JSP, methods and variables inside the declaration tag become instance
methods and instance variables and are also assigned default values.

• Anything we add in scriplet tag goes inside the _jspService() method. We cannot add any function inside
the scriplet tag as it creates a function inside the service method during compilation, which is not
allowed in a Java method.
Advanced Java
DEMO—Writing JSP Program with Tags
Advanced Java
Topic 5—Working with JSP Standard Action
JSP Standard Action Elements

• Standard action elements are basically the tags that can be embedded into a JSP page.

• During compilation, they are also replaced by the Java code that corresponds to the pre-defined task.

• Action tags can be written only in XML syntax and can be used for communication.
List of JSP Standard Action Elements

• <jsp : forward >


• <jsp : include >
• <jsp : plugin >
• <jsp : param>
• <jsp : params >
• <jsp : fallback >
• <jsp:usebean>
• <jsp:setProperty>
• <jsp:getProperty>
UseBean Tag

This tag is used to interact with a JavaBean component using the standard tags in a JSP page.

Syntax :

<jsp:useBean id=”beanName” scope=”page | request | session | application “


class =”className” / >

• id attribute specifies the attribute name of the bean.


• Location of the bean is specified by the cope attribute.
• The class attribute specifies the fully qualified classname.
setProperty Tag

The setProperty tag is used to store data in the JavaBeans instance.

Syntax:

<jsp:setProperty name=”beanName” property_expresion / >

• Name attribute specifies the name of the JavaBeans instance.


• This must match the id attribute used in useBean tag.
• The property_expression can be represented as follows:

property=”*” | property =”propertyName” | property=”propertyName”


param=”parameterName” | property=”propertyName” value=”propertyValue”

Property attribute specifies the property within the bean that will be set.
The getProperty Tag

The getProperty tag is used to retrieve a property from a JavaBeans instance and display it in the output stream.

Syntax:

<jsp:getProperty name=”beanName” property_expresion / >

• Name attribute specifies the name of the JavaBeans instance.


• This must match the id attribute used in useBean tag, where property attribute specifies the
property used for the get method.
Action Tag

• The action tag is used to insert the output of another JSP page into the current JSP page.
• The syntax for the jsp:include action has two forms.

jsp:include element that does not have a parameter name / value pair.
<jsp:include page = “relative URL” flush”true”/>

This syntax is used to pass information to the included resources.


<jsp:include page =”relative url” flush =”true”>
<jsp:param… />
</jsp:include>
Difference between Include Directive and Include Action

include directive include action

include directive includes the source code, so it is


include action includes the output so it is dynamic.
static

include directive has an attribute for file. include action has an attribute for page.

It can be written in HTML or XML syntax. It can be written in XML syntax only.

It can include source code of a JSP and HTML, but not


It can include the output of Servlet JSP and HTML.
Servlet.

We can pass the expression as a value to the page


We can’t pass the expression as a value to a file.
attribute.
JSP–Expression Language (EL)

JSP EL allows you to create arithmetic expression and logical expression. It uses integers, floating point
numbers, strings, the built-in constants (true and false for Boolean values), and null.

It allows you to access application data stored in JavaBeans components easily.

Syntax:

It allows to specify an expression for any of attribute values as follows:

${expr}

Where expr specifies the expression

Example: <jsp:setProperty name = “rectangle” property=“area” value=


“${length*width}”/>
EL Implicit Object

pageScope Provides access to variable stored in page scope level


requestScope Provides access to variable stored in page request scope
sessionScope Provides access to variable stored in page session scope
applicatrionScope Provides access to variable stored in page application scope
param Gives you access to the parameter values available through the
request.getParameter
paramValues Gives you access to the parameter values available through the
request.getParameterValue
header Gives you HTTP request headers as strings
headerValues Gives you HTTP request headers as collections of strings
initParam Used as Context-initialization parameter
cookie Maps the given cookie name to the cookie value
pageContext Provides access to object request, session, etc.
Advanced Java
DEMO—Writing JSP Program to demonstrate JSP Standard Action Elements
Advanced Java
Topic 6—JSTL and Custom Tag Libraries
JSTL

• JSTL 1.2 is a part of java EE 5 platform

• JSP standard tag library (JSTL) represents a set of tags used to simplify development of JSP

• We can use the JSTL tags in various pages

• It avoids the use of scriptlet tag

JSTL Jar files can be downloaded from: http://www.oracle.com/technetwork/java/index-


137889.html
JSTL Tags

Tag Uses URL Prefix


Core Tags Provide: http://java.sun.com/jsp/jstl/core c
• Variable Support
• URL Management
• Flow Control
Sql tags Provide SQL support httlp://java.sun.com/jsp/jstl/sql sql
XML tags Provide flow control and httlp://java.sun.com/jsp/jstl/xml x
transformation
Internationalization Provide support for message http://java.sun.com/jsp/jstl/fmt fmt
tags formatting and number and date
formatting.
Function tags Provide support for String httlp://java.sun.com/jsp/jstl/funct fn
manipulation & String length and ions
flow control
Core JSTL Tag: Example
<c:out>

Core JSTL tag is used to write expression and render data to page.

Welcome.html

<form action =“ process.jsp” method = “post”>


First name: <input type = “text” name =“fname”/> </br>
Last name <input type = “text” name = “fname”/> </br/>
<input type = “Submit” value = “submit”/>
</form>

Process.jsp

<%@taglib uri = “http://java.sun.com/jsp/jstl/core” prefix =


“c”%>
First name: <c: out value = “${ param.fname}”> </c: out> <br/>
Second name: <c:out value = “${param.fname}”> </c:out> <br/>
Core JSTL Tag: Example
<c:if>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


<html>
<head>
<title>Core Tag Example</title>
</head>
<body>
<c:set var="income" scope="session" value="${3000*4}"/>
<c:if test="${income > 8000}">
<p>My income is: <c:out value="${income}"/><p>
</c:if>
</body>
</html>

Attribute Description
Test Condition to evaluate
Var Name of the variable to store the condition result
Scope Scope of the variable to store the conditions result
Core JSTL Tag: Example
<c:catch>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Core Tag Example</title>
</head>
<body>

<c:catch var ="catchtheException">


<% int x = 2/0;%>
</c:catch>

<c:if test = "${catchtheException != null}">


<p>The type of exception is : ${catchtheException} <br />
There is an exception: ${catchtheException.message}</p>
</c:if>

</body>
</html>

Attribute Description
Var The name of the variable to hold the java.lang. Throwable if thrown by element in the body
Custom Tag Syntax Rules

JSP allows you to create your own tags. They are known as custom tags. They uses XML syntax. There are
four fundamental XML rules that all custom tags must follow:

1. Standard tag syntax must conform to the following structure:

<prefix:name { attribute ={“value” | ‘value’ } } * >


body
</prefix:name>

2. Empty tag syntax must conform to the following structure:

<prefix :name { attribute ={ “value” | ‘value’ } } * />

3. Tag name, attributes and prefix are case sensitive

4. Tag must follow nesting rule:


<tag1>
<tag2>
</tag2>
</tag1>
Advanced Java
DEMO—Writing JSP Program to demonstrate JSP Tags
Key Takeaways

JSP (Java Server Pages) is a text document consisting of Hyper Text Markup
Language(HTML), Extensible Markup language(XML), and JSP elements that can
be expressed in standard and XML syntax.

Implicit variables are the Java objects that the JSP Container makes available to the
developers in each page; the developers can call them directly without explicitly
declaring them.

JSP elements in a JSP page can be expressed in two types of syntax: standard and
XML
JSP EL allows you to create arithmetic and logical expressions. It uses integers,
floating point numbers, strings, the built-in constants true and false for Boolean
values and null.
Quiz
Thank You
Advanced Java
Lesson 5—Java Hibernate

© Simplilearn. All rights reserved.


Learning Objectives

Discuss Hibernate basics

Explain Hibernate ORM feature

Set up a Project with Hibernate

Describe Hibernate Annotations

Explain Hibernate CRUD Operation


Advanced Java
Topic 1—Hibernate Basics
Getting Started

• Hibernate Framework was built by Gavin King in 2001

• The latest version of Hibernate is 5.2.10


Think Through!

Let's start by discussing why we need Hibernate and why it was created?
Think Through!

Hibernate is a framework that simplifies the development of Java application to


interact with the database.

Lets understand it why we need it with the help of two scenarios.


Scenario 1: Changing Database
Let’s consider a scenario where a user has a program with MySQL database connectivity. The user needs to
write MySQL specific code to create database connection.

MySQL

Database Connectivity Code (MySQL specific)


+
USER Business Logic
Change in DB The user has to
change the codes
and queries to map
Database Connectivity Code (Oracle specific) them to Oracle
+ database
Oracle
Business Logic

Hibernate converts database-specific queries automatically, based on dialect provided. It uses


HQL (hibernate Query Language), which is independent of Database.
Scenario 2: Billing Record

Let’s consider a scenario of a user with various billing records.

The USER and the BILLING RECORDS data needs to be stored in DBMS. For this, the user class has to
be mapped to user table, and the Billing Records has to be mapped to the BillingRecords table.

BILLING RECORDS

USER
Scenario 2: Billing Record
CLASS REPRESENTATION

Creating the SQL schema for USER and BILLINGRECORDS classes

class User create table USER


{ {
private int id; id number (3) primary key not
private String name; null,
private Set billingrecords name varchar(50) not null,
// getter method address varchar(40),
//setter method age number (3) ,
} }

class BillingRecords create table BILLINGRECORDS


{ {
private int accountNo; accountnumber number (10) primary key not
private String accountType; null,
private User user; acccounttype varchar (6) not null,
// getter method ……
//setter method id number(3) foreign key references user
} }
Scenario 2: Billing Record
OBJECT RELATIONAL MISMATCH PROBLEMS

What could be the possible problems?

• Association: Java can use association by having another class variable as member; in SQL, no standard
concept is available to represent association

• Navigating data: It is different in Java and SQL

• Cost mismatching due to manual handling of object/relational mismatching


Scenario 2: Billing Record
ADDING SUBCLASSES

Let's add two subclasses CREDITCARD and DEBITCARD to the records:

BILLING RECORDS

USER

CREDIT CARD DEBIT CARD


Scenario 2: Billing Record
ADDING SUBCLASSES: RELATED PROBLEMS

What could be the possible problems?

• Structured Query Language (SQL) does not support supertable-subtable relationship

• Table is not a ‘type,’ so it is difficult to create supertable-subtable relationship

• Writing SQL query for polymorphic relation is difficult


Scenario 2: Billing Record
ADDING SURROGATE KEY COLUMN

• In USER table, id is the primary key. This is a foreign key for BILLINGRECORD table.

• It is difficult to change id; we need to update not only the id column in USER, but also the foreign key
column in BILLINGRECORD

• Add surrogate key in USER and BILLINGRECORD table

• Surrogate key isn’t presented to the user and is only used for identification of data inside the software
system
Scenario 2: Billing Record
ADDING SURROGATE KEY COLUMN: RELATED PROBLEMS

• user_surroagte_id and account_number_id are system generated values. It is difficult to decide whether these
columns should be added to data model or not.
• Different persistence solutions have chosen different strategies. This can cause confusion.
What is the Solution?

Hibernate provides Object Relational Mapping, which takes care of these issues.
Advanced Java
Topic 2—ORM and its Features
ORM

ORM refers to the automated (and transparent) persistence of objects in a Java application to the tables in a
relational database, using metadata that describes the mapping between the objects and the database.

Mapping

Java class User Table

class User id name It has two


{ column ids
It has two private int id; and names.
members ids private String name;
and names //getter methods Column id and name of user table
//setter methods are representing members of User
} class id and name respectively.
Advantages of using ORM

• It can significantly reduce the development time

• It involves writing less code

• It increases system performance

• You can support different database management systems by adopting ORM. It provides portability
ORM: Features

• By mapping between logical business model and physical storage model, ORM implements domain
model pattern

• It navigates object relational transparency

• ORM provides one way to translate query to appropriate database syntax

• It provides concurrency support

• It provides a host of services that enable developers to focus on business logics

• It provides cache management to reduce load on database

• Surrogate key, Identifier, and other key features can be automated in ORM
ORM Architecture

Java Application

ORM API: facilitates basic CRUD operation

Mapping Information
ORM Engine: facilitates creation of mapping information

Generates and sends SQL statements

JDBC API and JDBC Driver connect Java application to database


Advanced Java
Topic 3—Hibernate as an ORM Framework
Hibernate as an ORM Framework

“As an Object/Relational Mapping (ORM) framework, Hibernate is concerned with data


persistence as it applies to relational databases (via JDBC).”

Reference : http://hibernate.org/orm/
Hibernate Configuration Files

DBMS-specific details and mapping file details are specified in hibernate.cfg.xml and mappingfile.xml.
Hibernate engine uses these files to generate DBMS-specific SQL syntax.

Hibernate

hibernate.cfg.xml

Database Management
Java Application
System

mappingfile.hbm.xml
Features of Hibernate ORM

• Hibernate ORM provides its own native API, in addition to full JPA (Java Persistence API) supports.
• It maps Java POJO’s (Plain Old Java Object ) to relational database.
• It provides rich tool set.
• Performance: Fetch strategies, caching, byte code enhancement
• It is part of JBoss community.

You can download the latest version of Hibernate from: http://www.hibernate.org/downloads


JPA (Java Persistence Application Programming Interface)

• Java EE 5.0 platform provides a standard persistence API named JPA. As part of the EJB 3.0
specification effort, it is supported by all major vendors of the Java industry.

• Hibernate model implements Java Persistence object relational API.

• Hibernate persistence provider can be used in any environment of Java platform, Java SE or Java EE.
Hibernate Programming Model

Create org.hibernate.cfg.configuration object

Load the Meta information

Create org.hibernate.SessionFactory object

Make hibernate API call on session object

Close the session

Close the sessionfactory object


Hibernate Architecture

Transaction Factory
JNDI
Session Factory
Connection Provider

Java Persistent JDBC


Session
Application Object

Transaction JTA

Core objects of Hibernate Framework Internal API used


by Hibernate
Persistent Object

Session object is created within the Database Layer in every DAO method. It is known as persistence
object.

It has three lifecycle states:

1. Transient: An object is transient if it has just been instantiated using the new operator, and it is not
associated with a Hibernate Session.

2. Persistent: A persistent instance has a representation in the database and an identifier value. It
might just have been saved or loaded; however, it is by definition in the scope of a Session.

3. Detached: A detached instance is an object that has been persistent, but its Session has been
closed. The reference to the object is still valid, of course, and the detached instance might even be
modified in this state.
Hibernate Core APIs

1. Configuration (org.hibernate.cfg): It gives two services in hibernate application:

• Loads mapping file and configuration file into memory and makes them available to hibernate engine
• Acts as factory to create the SessionFactory

2. SessionFactory (org.hibrnate.SessionFactory)

• Hibernate (engine) implements SessionFactory interface


• SessionFactory is one per DBMS (mostly one per application)
• SessionFactory is Thread safe
• SessionFactory is not a Singleton
• It creates Session object, SessionFactory encapsulates, second level cache, connection pool, meta
information cache, and pool of session
Hibernate Interface

3. Session (org.hibernate.Session)

• Hibernate engine implements Session interface


• Session object acts as persistent manager
• Session object is a light weight object
• It encapsulates connection and first-level cache
• Session object is not thread-safe
• In every dao method, Session object is created
• It is used for CRDD operation

4. Transaction (org.hibernate.Transaction)

• Hibernate engine implements this interface


• When database connection is created by hibernate, connection associated with session is in
autocommit disable mode.
• Whenever any CRUD operation is performed, the changes will not be reflected in the database
unless connection is maintained in auto-commit enabled mode.
Hibernate Interface
IdentifierGenerator

All the generator classes implement the org.hibernate.id.IdentifierGenerator interface.

The application programmer may create one's own generator classes by implementing the
IdentifierGenerator interface.

Hibernate framework provides many built-in generator classes:

• assigned: Default, value has to be explicitly assigned to persistent object before persisting it.
<generator class = assigned/>
• increment: It increments value by 1. It generates short, int, or long type identifier.
• native: It uses identity, sequence, or hilo, depending on the database vendor.
• sequence: It uses the sequence of the database. If there is no sequence defined, it creates a
sequence automatically. For example, in case of Oracle database, it creates a sequence named
HIBERNATE_SEQUENCE.
• hilo: It uses high and low algorithm to generate the id of type short, int, and long.
• identify: It is used in Sybase, My SQL, MS SQL Server, DB2, and SQL to support the id column.
The returned id is of type short, int, or long.
Advanced Java
Topic 4—Setting up a Project with Hibernate
Setting Up a Project with Hibernate
1. Create a Java project and add required jars from the required folder of hibernate downloads
2. Add ojdbc14.jar or mysqlconnector.jar depending on the SQL vendor you are connecting to
3. Create the POJO class and save it in src folder
4. Create the hibernate.cfg.xml file in src folder(configuration file) with specific RDBMS dialect
RDBMS Dialect

Oracle (any version) org.hibernate.dialect.OracleDialect

Oracle9i org.hibernate.dialect.Oracle9iDialect

Oracle10g org.hibernate.dialect.Oracle10gDialect

MySQL org.hibernate.dialect.MySQLDialect

DB2 org.hibernate.dialect.DB2Dialect

5. Create the ClassName.hbm.xml file in src folder (mapping file)


6. Create the class that retrieves or stores the persistent object and save it in src folder
7. Run the application
Setting Up a Project with Hibernate: Step 1
Create a Java project and add
required jars from the required
folder of hibernate downloads

Add ojdbc14.jar or 1. Download the latest version of Hibernate from http://hibernate.org/orm/downloads/


mysqlconnector.jar depending
on the SQL vendor you are 2. Right click on project
connected to
3. Click on build path
Create the POJO class and save
it in src folder 4. Click on add External JARs
5. Add all required Hibernate JARs
Create the hibernate.cfg.xml
file in src folder (configuration
file)

Create the
ClassName.hbm.xml file in src
folder (mapping file)

Create the class that retrieves


or stores the persistent object
and save it in src folder

Run the application


Setting Up a Project with Hibernate: Step 2
Create a Java project and add
required jars from the required
folder of hibernate downloads
Download mysqlconnector.jar from:
Add ojdbc14.jar or
mysqlconnector.jar depending
on the SQL vendor you are https://dev.mysql.com/downloads/connector/j/
connected to
Download link for ojdbc14.jar for Oracle 11g:
Create the POJO class and save
it in src folder http://www.java2s.com/Code/Jar/o/Downloadojdbc14jar.htm
Create the hibernate.cfg.xml
file in src folder (configuration
file)

Create the
ClassName.hbm.xml file in src
folder (mapping file)

Create the class that retrieves


or stores the persistent object
and save it in src folder

Run the application


Setting Up a Project with Hibernate: Step 3
Create a Java project and add
required jars from the required
folder of hibernate downloads

Add ojdbc14.jar or
mysqlconnector.jar depending
on the SQL vendor you are class Student
connected to
{
Create the POJO class and save private int rollNo ;
it in src folder
private String name;
Create the hibernate.cfg.xml
file in src folder (configuration // setter menthods
file)
//getter methods
Create the
ClassName.hbm.xml file in src }
folder.(mapping file)

Create the class that retrieves Student is a POJO class containing two member variables, rollNo and name.
or stores the persistent object
and save it in src folder
It uses setter methods to set the values for member variables and getter methods
to fetch the values.
Run the application
Setting Up a Project with Hibernate: Step 4
Create a Java project and add
required jars from the required
folder of hibernate downloads Hibernate configuration file configures class Student to table studentname using
<hibernate-mapping> tag. Hibernate.cfg.xml is used to mention database detail.
Add ojdbc14.jar or
mysqlconnector.jar depending
on the SQL vendor you are <?xml version='1.0' encoding='UTF-8'?>
connected to <!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
Create the POJO class and save "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
it in src folder
<hibernate-configuration>
Create the hibernate.cfg.xml
<session-factory>
file in src folder (configuration
<property name="dialect">org.hibernate.dialect.MySQLDialect
file)
</property>
Create the <property name="connection.url">jdbc:mysql://localhost:3306/databasename</pro
ClassName.hbm.xml file in src perty>
folder (mapping file) <property name="connection.username">username</property>
<property name="connection.password">password</property>
Create the class that retrieves <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
or stores the persistent object <property name="hbm2ddl.auto">create</property>
and save it in src folder <mapping resource=“Student.hbm.xml"/>
</session-factory>

Run the application </hibernate-configuration>


Setting Up a Project with Hibernate: Step 5
Create a Java project and add
required jars from the required
folder of hibernate downloads <?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
Add ojdbc14.jar or
mysqlconnector.jar depending "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
on the SQL vendor you are "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
connected to
<hibernate-mapping>
Create the POJO class and save <class name=“Student" table=“studenttable">
it in src folder <id name="id">

Create the hibernate.cfg.xml </id>


file in src folder (configuration
file) <property name=“name"></property>
Create the
ClassName.hbm.xml file in src
folder (mapping file) </class>

Create the class that retrieves </hibernate-mapping>


or stores the persistent object
and save it in src folder
POJO class name is student. The mapping file name would be Student.hbm.xml
Run the
Runapplication
the application which maps student class to student table.
Setting Up a Project with Hibernate: Step 6
Create a Java project and add
required jars from the required
folder of hibernate downloads

Add ojdbc14.jar or
Creating configuration object and hibernate.cfg.xml file:
mysqlconnector.jar depending
on the SQL vendor you are public class Client
connected to
{
StandardServiceRegistry standardRegistry = new
Create the POJO class and save .
it in src folder
StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build
();
Create the hibernate.cfg.xml
file in src folder (configuration
file) Metadata metaData = new
MetadataSources(standardRegistry).getMetadataBuilder().build();
Create the sessionFactory = metaData.getSessionFactoryBuilder().build();
ClassName.hbm.xml file in src
folder (mapping file) }
Create the class that retrieves
or stores the persistent object
and save it in src folder

Run the application


Setting Up a Project with Hibernate: Step 7
Create a Java project and add
required jars from the required
folder of hibernate downloads

Add ojdbc14.jar or Use <property name="hbm2ddl.auto">update</property> to avoid creating


mysqlconnector.jar depending studenttable manually.
on the SQL vendor you are
connected to
Hibernate will automatically create studenttable.
Create the POJO class and save
it in src folder Run the program to map the:

Create the hibernate.cfg.xml 1. Student class to Student table.


file in src folder (configuration 2. int rollNo (member of class Student) to column rollNo
file)
3. String name (member of class Student) to column name
Create the
ClassName.hbm.xml file in src Output:
folder (mapping file)
Hibernate: drop table if exists studenttable
Create the class that retrieves Hibernate: create table studenttable (rollNo integer not
or stores the persistent object
and save it in src folder
null,name varchar(5) );

Run the application


Advanced Java
Topic 5—Hibernate Annotations
Hibernate Annotation

You have Learned how Hibernate uses XML mapping file for the transformation of data from POJO to
database tables and vice versa

Hibernate annotation is the newest way to define mappings without the use of XML file. You can use
annotations in addition to or as a replacement of XML mapping metadata.
Creating POJO Class With Annotation

@Entity // Every persistent POJO class is an entity and is declared using the @Entity
annotation (at the class level):

@Table // @Table annotation, hibernate will use the class name as the table name by default

public class Student


{
@Id // @Id declares the identifier property of this entity.
public int id ;

private String name; // @Column annotation specifies the details of the column for this
property or field.
If // if it is is not specified, property name will be used as the column name by default.

// setter and getter methods


}

Use POJO class student, hibernate.cfg.xml file, and annotations instead of hibernate mapping file.
Creating POJO Class With Annotation
RUNNING THE APPLICATION

public class Client


{
public static void main(String [] args)
{
Configuration configuration= new Configuration().configure();
StandardServiceRegistry standardRegistry = new
StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
Metadata metaData = new
MetadataSources(standardRegistry).getMetadataBuilder().build(); sessionFactory
= metaData.getSessionFactoryBuilder().build();

}
}
Advanced Java
Topic 6—Hibernate CRUD Operation
CRUD Operation

The acronym CRUD stands for Create, Read, Update, and Delete

They are four basic operations that any data-driven application performs often

CREATE

READ
Application
UPDATE

DELETE

Hibernate also supports CRUD operation by means of Session interface.


Hibernate CRUD Operation
LIMIATATIONS OF USING SESSION METHODS

1. Multiple persistent objects can’t be retrieved


2. Multiple delete and update operations are not possible
3. Required criteria can’t be expressed to perform some complex CRUD operation

To overcome the above limitations, the following are used:

a. HQL (Hibernate Query Language)


b. Criteria API
c. Native SQL (Structured Query Language)
HQL

• It gives query language provided by Hibernate.


HQL
• It is same as SQL (Structured Query Language), but it doesn't depends on the table of the
CRITERIA API database. It uses classes.

NATIVE SQL
Criteria

HQL • It is one way of querying the DB in the hibernate application


• It can be used for DML (Database Manipulation Language) operations
CRITERIA API
• Criteria API is an object oriented after native for HQL to read data from database

NATIVE SQL • Criteria API supports compile time checking for the query that we build, unlike HQL
Hibernate CRUD Operation
CREATE
Create and insert: The student table is created with two columns, rollNo and name. Let’s add data
for one student through the following code:
public class Client
{
CREATE public static void main(String [] args)
{
READ Configuration configuration= new Configuration().configure();
StandardServiceRegistry standardRegistry = new
StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
UPDATE Metadata metaData = new
MetadataSources(standardRegistry).getMetadataBuilder().build();
sessionFactory = metaData.getSessionFactoryBuilder().build();
DELETE Session s = factory.openSession();
Transaction t=s.beginTransaction();
Student s1=new Student ();
s1.setRollNo(1);
s1.setName(“yachaan”);
s.save(s1);
t.commit();
s.close();
} POJO class and hibernate.cfg.xml file remains same
}
Hibernate CRUD Operation
READ

To read and retrieve data, create a Student object with existing ID and sessionobject.get (Class clazz, Serializable id).

public class Client


CREATE {
public static void main(String [] args)
{
READ
Configuration configuration= new Configuration().configure();
StandardServiceRegistry standardRegistry = new
UPDATE StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build(); Metadata
metaData = new MetadataSources(standardRegistry).getMetadataBuilder().build();
sessionFactory = metaData.getSessionFactoryBuilder().build();
DELETE Session s = factory.openSession();
Transaction t=s.beginTransaction();
// now we are retrieving students record
Student s1=s.get(Student.class,1);
System.out.print(s1.getId()+” “ + s1.getName());
}
}
Hibernate CRUD Operation
UPDATE

Create a Student object with existing ID and use sessionobject.update (Object object)

public class Client


CREATE {
public static void main(String [] args)
{
READ Configuration configuration= new Configuration().configure();
StandardServiceRegistry standardRegistry = new
StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build(); Metadata
UPDATE metaData = new MetadataSources(standardRegistry).getMetadataBuilder().build();
sessionFactory = metaData.getSessionFactoryBuilder().build();
DELETE Session s = factory.openSession();
Transaction t=s.beginTransaction();
// now we are retrieving students record
Student s1=s.get(Student.class,1);
s.update(s1);
}
}
Hibernate CRUD Operation
DELETE

Create a Student object with existing ID and use sessionobject.delete (Object object)

public class Client


{
CREATE
public static void main(String [] args)
{
READ Configuration configuration= new Configuration().configure();
StandardServiceRegistry standardRegistry = new
StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build(); Metadata
UPDATE metaData = new MetadataSources(standardRegistry).getMetadataBuilder().build();
sessionFactory = metaData.getSessionFactoryBuilder().build();
Session s = factory.openSession();
DELETE Transaction t=s.beginTransaction();
// now we are retrieving students record
Student s1=s.get(Student.class,1);
s.delete(s1);
}
}
Key Takeaways

Hibernate converts database-specific queries automatically, based on dialect


provided. It uses HQL (hibernate Query Language), which is independent of
Database.

As an Object/Relational Mapping (ORM) framework, Hibernate is concerned with


data persistence as it applies to relational databases (via JDBC).

Hibernate annotations is the newest way to define mappings without the use of
XML file. You can use annotations in addition to or as a replacement of XML
mapping metadata.

Hibernate supports CRUD operation by means of Session interface.


Quiz
QUIZ
Which of the following is the hibernate configuration file?
1

a. hibernate.xml

b. hibernate.config.xml

c. hibernate.properties

d. hibernate.cfg.xml
QUIZ
Which of the following is the hibernate configuration file?
1

a. hibernate.xml

b. hibernate.config.xml

c. hibernate.properties

d. hibernate.cfg.xml

The correct answer is d.


hibernate.cfg.xml is the hibernate configuration file.
QUIZ
Which of the following is true about Hibernate?
2

a. Hibernate is an open source framework

b. Hibernate is a framework based on business logic

c. Hibernate is an ORM tool

d. Hibernate doesn’t use JDBC internally


QUIZ
Which of the following is true about Hibernate?
2

a. Hibernate is an open source framework

b. Hibernate is a framework based on business logic

c. Hibernate is an ORM tool

d. Hibernate doesn’t use JDBC internally

The correct answer is a and c.


Hibernate is a open source framework and an ORM tool.
Thank You
Advanced Java
Lesson 6—Hibernate Queries and Relationships

© Simplilearn. All rights reserved.


Learning Objectives

Discuss HQL

Describe Native SQL Query and Criteria Query

Explain caching in Hibernate

Explain Transaction management


Advanced Java
Topic 1—Hibernate Query Language (HQL)
Why HQL: Example
Analyze the following code to retrieving student record from student table:

public class Test


{
org.hibernate.cfg.Configuration cfg= new
org.hibernate.cfg.Configuration().config
// POJO class
ure("onetomany/hibernate.cfg.xml");

class Student
StandardServiceRegistryBuilder id name
{
hibernate.cfg.xml builder= new
private int id;
StandardServiceRegistryBuilder().applySe
private String name;
ttings(cfg.getProperties());
// getter and setter 1 John
SessionFactory
methods
factory=cfg.buildSessionFactory(builder.
}
build());
Session s=
factory.openSession();
s.beginTransaction();
Person user=new Person();
Student s1=user.get(Person.class,1);

}
Student table
Why HQL?

To retrieve the student’s data, we provide primary key value for that Student: user.get(Person.class,1);

If one table doesn’t have a primary key, the records cannot be retrieved.

Hibernate provides its own language known as Hibernate Query Language, to solve such problems.
The syntax is quite similar to database SQL language,
What Is HQL?

HQL is used to communicate with a database.


It is a Hibernate language for relational database management systems. HQL statements are used
to perform tasks such as updating data on a database or retrieving data from a database.

HQL Queries

Hibernate

Retrieve data
HQL vs. SQL

HQL SQL
It is related to hibernate framework It is related to a specific database
HQL queries are object queries SQL queries are table queries
Example: Example: Student table

class Student
{ Id name
String name;
int id;
}

HQL Query :- from Student


where Student is one class name

HQL Query: from Student, where Student is one SQL Query: Select * from Student, where Student
class name is one table name
Features of HQL

• HQL is object-oriented

• It understands notions like inheritance, polymorphism, and association

• Its queries are case-insensitive, unlike queries in Java classes.

Example: For HQL queries, SeLeCT is the same as sELEct


but for Java class org.hibernate.eg.STUDENT is not equal to org.hibernate.eg.Student.
Uses of HQL

Using HQL, we can create required CRUD operations:

• UPDATE
• DELETE
• SELECT

Using HQL, we can move table data to another table. However, we cannot insert
data using HQL.
Creating HQL Query

1. Create configuration object and hibernate.cfg.xml file

StandardServiceRegistry standardRegistry = new


StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();

2. Create SessionFactory object

Metadata metaData = new


MetadataSources(standardRegistry).getMetadataBuilder().build();
sessionFactory sf =
metaData.getSessionFactoryBuilder().build();

3. Open Session

Session sn = sf.openSession();

4. Create query

Query query = sn.createQuery(“Here you can write HQL Query”);


Methods of Query Interface

1. getReturnType() - Return the Hibernate types of the query result set

1. iterate() - Return the query results as an Iterator

1. list() - Return the query results as a List


Hibernate Parameter Building

Named parameters: This is the most common way method followed by a parameter name (:example) to
define a named parameter. Suppose we have Stock table with stockCode column.

setParameter: The setParameter discovers the parameter data type

String hql = "from Stock s where s.stockCode = :stockCode";


List result = session.createQuery(hql) .setParameter("stockCode",
“1111") .list();

setString: This informs Hibernate that the parameter date type is String

String hql = "from Stock s where s.stockCode = :stockCode";


List result = session.createQuery(hql) .setString("stockCode", “1111") .list();

setProperties: This can be used to pass an object to the parameter binding. Hibernate will automatically
check the object’s properties and match them with the colon parameter

Stock stock = new Stock(); stock.setStockCode(“1111");


String hql = "from Stock s where s.stockCode = :stockCode";
List result = session.createQuery(hql) .setProperties(stock) .list();
HQL Syntax

1. from clause
2. Aliasing
3. Aggregate functions and select clause
4. where clause
5. Expressions
6. order by clause
7. Associations and Joins
HQL Syntax
from clause

from clause
from packagename.class_name returns all instances of the class.

Aliasing Suppose there is a Student table with rollNo and name member variable corresponding to Student
class.
Aggregate
functions and To fetch the data from Student table, use the following syntax:
select clause
String hql = "FROM Student";
where clause Query query = session.createQuery(hql);
List results = query.list();

Expressions

order by
clause

Associations
and Joins
HQL Syntax
Aliasing

from clause
You can assign an alias that is a different name to the class. Suppose alias name is als. The syntax
can be:
Aliasing
from ClassName as als
Aggregate
functions and
select clause
This query assigns the alias als to ClassName instances, so that you can use that alias later.

where clause

Expressions

order by
clause

Associations
and Joins
HQL Syntax
Aggregate functions and select clause

from clause
To get results of aggregate functions on the properties select avg(std.marks), sum(std.marks),
max(cat.marks), and count(std)from Student std, the supported aggregate functions are:
Aliasing
• avg(...), sum(...), min(...), max(...)
Aggregate
functions and • count(*)
select clause
• count(...), count(distinct ...), count(all...)
where clause
You can use arithmetic operators and concatenation

Expressions

order by
clause

Associations
and Joins
HQL Syntax
where clause

from clause
The where clause allows you to refine the list of instances.

Aliasing • from ClassName where column_name='Ram‘: If there is an alias, use a qualified property name

Aggregate • from ClassName as als where als.column_name='Ram‘: This returns instances of ClassName
functions and named 'Ram'
select clause

where clause

Expressions

order by
clause

Associations
and Joins
HQL Syntax
Expressions

from clause Expressions include:


• mathematical operators: +, -, *, /
Aliasing • binary comparison operators: =, >=, <=, <>, !=, like
• logical operations: and, or, not
Aggregate • Parentheses ( ) that indicate grouping
functions and
select clause • in, not in, between, is null, is not null, is empty, is not empty, member of, and not member of
• "Simple" case, case ... when ... then ... else ... end, and "searched" case, case when ... then ... else ... end
where clause • string concatenation ...||... or concat(...,...)
• current_date(), current_time(), and current_timestamp()
Expressions • second(...), minute(...), hour(...), day(...), month(...), and year(...)
• Any function or operator defined by EJB-QL 3.0: substring(), trim(), lower(), upper(), length(), locate(),
order by
abs(), sqrt(), bit_length(), mod()
clause • coalesce() and nullif()
• str() for converting numeric or temporal values to a readable string
Associations
and Joins
HQL Syntax
order by clause

from clause
This clause uses a ordered list by any property that is either ascending (ASC) or descending (DESC).

Example:
Aliasing
Suppose there is a list of employees and you need to find their salaries in decreasing order. The
Aggregate
functions and following syntax can be used:
select clause
"FROM Employee E ORDER BY E.salary DESC";
where clause

Expressions

order by
clause

Associations
and Joins
HQL Syntax
Associations and Joins

from clause
Join is used to associated entities or elements of a collection of values.

Aliasing The join types are as follow:

Aggregate • inner join


functions and
select clause • left outer join
• right outer join
where clause
• full join

Expressions The inner join, left outer join ,and right outer join constructs may be abbreviated.
You may supply extra join conditions using the HQL with keyword
order by
clause

Associations
and Joins
Advanced Java
DEMO—Programs on HQL
Advanced Java
Topic 2—Native SQL Queries
Native SQL Queries

1. createSQLQuery() method is used to create native SQL Query for the session.
2. You can create SQL, including stored procedure, for all create, update, delete operations using Hibernate 3.x.
3. The result can be added to Hibernate entity.

How to write SQL Query :


Session s;
SQLQuery query = s.createSQLQuery(“ Here you can write native SQL Queries“
);

Hibernate provides an option to execute native SQL queries through the use of SQLQuery object.
Native SQL: Example
Consider a table that has the following data:
Person

PERSONID FIRSTNAME LASTNAME


-------- ---------- ---- -----------
1 Marry SMITH
1 Carl SMITH
2 JOHN SMITH

Name the database as record. POJO class for creating above table:

Class Person
{
private int id;
private String firstNmae;
private String lastName;
// public getter and setter methods
}

Lets create a list of all persons record using Native SQL Query.
Native SQL: Example
/* Code to READ all the Person record using Entity Query */

Session session; // Let assume We have already created Session object by previous discussed steps.
Transaction tx = null;
try{
tx = session.beginTransaction();
String sql = "SELECT * FROM PERSON";
SQLQuery query = session.createSQLQuery(sql);
query.addEntity(Person.class);
List person = query.list();

for (Iterator iterator = person.iterator(); iterator.hasNext();)


{
Person person = (Person) iterator.next();
System.out.print("First Name: " + person.getFirstName());
System.out.print(" Last Name: " + person.getLastName());
}
tx.commit();
}
catch (HibernateException e)
{
if (tx!=null) tx.rollback();
e.printStackTrace();
}
finally
{
session.close();
}
Advanced Java
Topic 3—Criteria Queries
What Is Criteria Query?

Criteria Query allows you to apply filtration rule and logical condition with query.

org.hibernate.Criteria Query is a method provided by Criteria API that helps in creating criteria query
programmatically.
Restriction Class

The criterion package may be used by applications as a framework for building new kinds of criteria.

However, it is intended that most applications will simply use the built-in criterion types via the static factory
methods of Restrictions class:

Restriction class Description


static SimpleExpression eq(String
Applies an "equal" constraint to the named property
propertyName, Object value)
static SimpleExpression gt(String
Applies a "greater than" constraint to the named property
propertyName, Object value)
static PropertyExpression
neProperty(String propertyName, String Applies a "not equal" constraint to two
otherPropertyName)
static SimpleExpression like(String
Applies a "like" constraint to the named property
propertyName, Object value)
static Criterion between(String
Applies a "between" constraint to the named property
propertyName, Object lo, Object hi)
Criteria Query: Example

Let’s assume we have one table named student, and one class named Student mapped to student
table, which has following structure:

Roll no Name Age Marks

Structure for Student class:

class Student
{
private int rollno;
private String name;
private int age;
private int marks;
//getter and setter methods
}
Applying Criteria Query

Criteria Query in given table can be applied in two ways:

1. Criteria Query without restrictions

Session s; s.createCriteria(Student.class).list();

This will show data of student table in the form of a list.

2. Criteria Query with restrictions

Session s;
Criteria crt = s.createCtriteria(Student.class);
crt.add(Restrictions.gt(“age”,23));
List <Student> list = crt.list();

This will show data of student table in form of a list with age greater than 23.
Advanced Java
Topic 4—Catching in Hibernate
Cache and Caching

• Cache is a component that stores data temporarily so future requests for that data can be served faster
• Cache is a temporary storage area
• Caching is a process to store data in cache
• Caching in Hibernate avoids database hits and increases performance of critical applications
Cache Hierarchy in Hibernate

Hibernate follows multilevel cache schema, as shown:

Hibernate

Java Application First Level Session Second Level


Cache Object Cache
Types of Cache in Hibernate

First - Level Cache:

1. All caches must pass through First-Level Cache.


2. When you close the Session object, all objects being cached are lost and persist or are updated in database.

Second - Level Cache:

1. It is an optional cache
2. It uses a common cache for all the session objects of a session factory.

Example:

JBoss cache as a Hibernate Second - Level Cache. It is tree-structured, clustered, transactional cache.
Advanced Java
Topic 4—Mapping Relationship with Hibernate
Why Mapping?

Hibernate mapping is used for the following:

• To map inheritance hierarchy classes with the table of the database


• To meet the need of mapping collection elements of Persistent class in Hibernate
• To map dependent object as a component
• Hibernate mapping is used to map Java data type to SQL data type and vice versa. Hibernate
uses Hibernate Type, which is different from Java data type and SQL data type
Hibernate Types

1. Value type has the following types:

• Basic value Type: Hibernate provides a number of built-in basic types


• Composite type: Components represent aggregation of value into a single Java type
• Collection type: To map collection, Hibernate provides collection type

2. Entity type: Entities are classes that correlate with row in table

3. Custom type: Hibernate allows you to create your own value types
Types of Mapping in Hibernate

1. Inheritance Mapping
2. Association Mapping
3. Collection Mapping
4. Component Mapping
Types of Mapping in Hibernate
INHERITANCE MAPPING

Java inheritance relationship between classes is represented as follows:

Inheritance
Mapping class ParentClass
{
Association
Mapping
}
Collection
Mapping extends
Component
Mapping
class ChildClass extends ParentClass
{

We can map the inheritance hierarchy classes with the table of the database using inheritance mapping.
Types of Mapping in Hibernate
INHERITANCE MAPPING: TYPES

There are three types of inheritance mapping:


Inheritance
Mapping
• Single Table per Class Hierarchy Strategy: the <subclass> element in Hibernate
Association
Mapping • Table per class: the <union-class> element in Hibernate

Collection • Joined Subclass Strategy: the <joined-subclass> element in Hibernate


Mapping
Component
Mapping
Types of Mapping in Hibernate
INHERITANCE MAPPING: SINGLE TABLE PER CLASS HIERARCHY STRATEGY

It is also known as Table per class. It uses one table. To distinguish classes, it uses discriminator
column. Lets take an example. Consider two classes as shown:

Inheritance Person class


Mapping @Entity
Association @Inheritance Employee class
@DiscriminatorColumn(
Mapping name="discriminator", @Entity
discriminatorType=DiscriminatorType.STRING) @DiscriminatorValue("E")
Collection @DiscriminatorValue(“P") public class Employee extends Person {
Mapping public class Person private String departmentName;
{ private Date joiningDate;
Component @Id //setter and getter methods
Mapping private int personId;
private String fName; }
private String lName;
// setter and getter method;
}

Single Table per Class Joined Subclass


Table per class
Hierarchy Strategy Strategy
Types of Mapping in Hibernate
INHERITANCE MAPPING: SINGLE TABLE PER CLASS HIERARCHY STRATEGY

Let’s create object for Employee class


Person person = new Person();
person.setFirstname(“john");
Inheritance person.setLastname(“sully");
Mapping person.setPersonId(1);

Association
Mapping Employee employee = new Employee(“linda", “watson", "Tech", new Date());
s.save(person);
Collection s.save(employee);
Mapping
Component discriminator id fName lName departmentName joiningDtae
Mapping
P 101 John Sully null null

E 102 Linda Watson tech 2017-08-08 17:53:58

Columns declared by the subclasses may not have NOT NULL constraints.

Single Table per Class Joined Subclass


Table per class
Hierarchy Strategy Strategy
Types of Mapping in Hibernate
INHERITANCE MAPPING: TABLE PER CLASS

Table Per class contains three tables in the database that are not related to each other. There
are two ways to map the table with table per concrete class strategy.
Inheritance
• By union-subclass element
Mapping
Association • By Self creating the table for each class
Mapping
Syntax:
Collection
Mapping
@Entity
Component @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
Mapping public class Flight implements Serializable
{
...
}

Single Table per Class Joined Subclass


Table per class
Hierarchy Strategy Strategy
Types of Mapping in Hibernate
INHERITANCE MAPPING: PROPERTIES OF TABLE PER CLASS

1. Each sub-table has a column for all properties, including inherited properties.
Inheritance
Mapping 2. Column name is the same in all sub tables.

Association 3. Primary key seed is shared in all sub tables.


Mapping
Collection
Mapping
Component
Mapping

Single Table per Class Joined Subclass


Table per class
Hierarchy Strategy Strategy
Types of Mapping in Hibernate
INHERITANCE MAPPING: JOINED SUBCLASS STRATEGY

• It is also known as One Table Per Subclass


Inheritance
• It uses n number of tables, where n = total number of classes, including sub and super
Mapping
classes
Association
Mapping • It uses one-to-one association
Collection • All subtables use primary key association with super table
Mapping
• The @PrimaryKeyJoinColumn and @PrimaryKeyJoinColumns annotations define the primary
Component key(s) of the joined subclass table
Mapping

Single Table per Class Joined Subclass


Table per class
Hierarchy Strategy Strategy
Types of Mapping in Hibernate
INHERITANCE MAPPING: JOINED SUBCLASS STRATEGY

The @PrimaryKeyJoinColumn and @PrimaryKeyJoinColumns annotations define the primary


key(s) of the joined subclass table:
Inheritance
Mapping
Association Person
Mapping person_id:Integer
Collection firstname: Char
Mapping lastname: Char

Component
Mapping Employee Owner
person_id:Integer person_id:Integer
joining_date: Date stocks: Integer
department name: Char department name: Char

Single Table per Class Joined Subclass


Table per class
Hierarchy Strategy Strategy
Types of Mapping in Hibernate
INHERITANCE MAPPING: JOINED SUBCLASS STRATEGY

Person class Employee class


@Entity
@Entity
@Table(name = "PERSON")
@Table(name="EMPLOYEE")
Inheritance @Inheritance(strategy=InheritanceType.JOINED)
@PrimaryKeyJoinColumn(name="PERSON_ID")
public class Person {
Mapping public class Employee extends Person {
@Id
@Column(name="joining_date")
Association @GeneratedValue
private Date joiningDate;
@Column(name = "PERSON_ID")
Mapping private Long personId;
@Column(name="department_name")
private String departmentName;
@Column(name = "FIRSTNAME")
Collection public Employee() {
private String firstname;
Mapping @Column(name = "LASTNAME")
}
public Employee(String firstname,
private String lastname;
Component public Person() {
String lastname, String departmentName, Date
Mapping }
joiningDate) {
super(firstname, lastname);
public Person(String firstname, String
this.departmentName =
lastname) {
departmentName;
this.firstname = firstname;
this.joiningDate = joiningDate;
this.lastname = lastname;
}
}
// Getter and Setter methods,
// Getter and Setter methods,
}
}

Single Table per Class Joined Subclass


Table per class
Hierarchy Strategy Strategy
Types of Mapping in Hibernate
INHERITANCE MAPPING: JOINED SUBCLASS STRATEGY

Owner class
@Entity
Inheritance @Table(name="OWNER")
@PrimaryKeyJoinColumn(name="PERSON_ID")
Mapping
public class Owner extends Person {
Association @Column(name="stocks")
Mapping private Long stocks;
@Column(name="partnership_stake")
Collection private Long partnershipStake;
Mapping public Owner() {
}
Component public Owner(String firstname, String lastname, Long stocks, Long
Mapping partnershipStake) {
super(firstname, lastname);
this.stocks = stocks;
this.partnershipStake = partnershipStake;
}
// Getter and Setter methods,
}

Single Table per Class Joined Subclass


Table per class
Hierarchy Strategy Strategy
Types of Mapping in Hibernate
INHERITANCE MAPPING: JOINED SUBCLASS STRATEGY

Database representation:
Person table
Inheritance
Mapping person_id firstname lastname
1 Steve Balmer
Association
Mapping 2 James Gosling
3 Bill Gates
Collection
Mapping
Employee table Owner table
Component
Mapping person_id joining_date department_name person_id stocks partnership_stake
2 2011-12-23 Marketing 3 300 20

Single Table per Class Joined Subclass


Table per class
Hierarchy Strategy Strategy
Types of Mapping in Hibernate
ASSOCIATION MAPPING

It is a mapping relationship between two objects in Java

Inheritance class classdiagram


Mapping
Association
Mapping Car Customer
Collection
owner • address: String
Mapping • modelNumber: String
Component • contactNumber: String
• owner: Customer
Mapping • name: String
Types of Mapping in Hibernate
ASSOCIATION MAPPING: TYPES

Inheritance 1. One to One


Mapping 2. One to Many
Association 3. Many to One
Mapping
4. Many to Many
Collection
Mapping
Component
Mapping
Types of Mapping in Hibernate
ASSOCIATION MAPPING: ONE TO ONE

A one-to-one relationship occurs when one entity is related to exactly one occurrence in
another entity.

Inheritance Example:
Mapping
Association Person Passport
Mapping
Collection
Mapping One person is associated with one passport, and one passport belongs to one person. Here,
Person class and Passport class have one-to-one relationship.
Component
Mapping
class Person{ class Passport
private int id; {
private String name;
private int id;
private Date valid_date;
} }

One to One One to Many Many to One Many to Many


Types of Mapping in Hibernate
ASSOCIATION MAPPING: ONE TO ONE

The annotation used to generate one to one mapping between person and passport table is
@OneToOne .
Inheritance Person class Passport class
Mapping
@Entity @Entity
Association @Table (name=”PERSON”) @Table (name=”PASSPORT”)
Mapping class Person{ class Passport
@Id {
Collection private int id; @Id
Mapping private String name; private int id;
@OneToOne private Date valid_date;
Component private Passport passport; }
Mapping }

Hibernate creates one column in Person table corresponds to PASSPORT table id column.

When member variable is sent to Person, set Passport member of Person class can be
avoided.

One to One One to Many Many to One Many to Many


Types of Mapping in Hibernate
ASSOCIATION MAPPING: ONE TO ONE

Let’s create the object of Person class and Passport class:

Inheritance Person p=new Person(); Person Table


Mapping p.setId(1); id name passport_id
p.setName(“John”);
Association Passsport k=new Passport(); 1 John 101
Mapping k.setId(101);
k.setValue(“abc); Passport Table
Collection p.setPassport(k);
Mapping session.save(p); id value
Component session.save(k);
101 abc
Mapping

If foreign key is added, annotation used should be @JoinColumn(name="passport_fk").

One to One One to Many Many to One Many to Many


Types of Mapping in Hibernate
ASSOCIATION MAPPING: ONE TO MANY

Consider a scenario where one Employee has multiple phone numbers and one phone number
Inheritance belongs to one Employee.
Mapping
Association Phone
Mapping Employee One to many
mapping Phone
Collection • address Address
Phone
Mapping • id integer
• name String • areaCode String
Component • phones Vector • id integer
Mapping
One to one mapping • owner Employee
Java Class (source) • number String

Java Classes (target)

One to One One to Many Many to One Many to Many


Types of Mapping in Hibernate
ASSOCIATION MAPPING: ONE TO MANY

Creating classes:
Employee Class:
Inheritance class Person Phone Class:
@Entity
Mapping { @Table(name="EMPLOYEE") @Entity
int id; public class Employee { @Table(name="Phone")
Association public class Phone {
String name; @Id
Mapping private int @Id
} private int
Collection employeeId;
@OneToMany PhoneId;
Mapping class Phone
private int
private collection
{ PhoneNumber;
Component <Phone>=new ArrayList <
int id; //setter and getter methods
Mapping phone>();
int phoneNumber; // setter getter methods }
} }

Add user defined name using the following annotation:


@JoinTable(name=”USER_VEHICLE”, join Column=@Join Column(name=”USER_ID”)
inverseJoinColumns=@JoinColumn(name=”VEHICLE_ID”)

One to One One to Many Many to One Many to Many


Types of Mapping in Hibernate
ASSOCIATION MAPPING: ONE TO MANY

Creating objects for Person and Phone classes:

Person table
Inheritance Person user=new Person();
Mapping
user.setId(1); id name
user.setName(“john”); 1 john Person_Phone table
Association Phone p1= new Phone();
p1.(101); 2 Stella
Mapping person_id phone_id
p1.(123456789);
Phone table 1 101
Collection user.getPhone().add(p1);
Mapping Phone p2= new Phone(); id phoneNumber 1 102
p2.(102);
Component p2.(1112131415); 101 123456789
Mapping user.getPhone().add(p2); 102 1112131415
session.save(user);
session.save(p1);session.save(p2);

One to One One to Many Many to One Many to Many


Types of Mapping in Hibernate
ASSOCIATION MAPPING: MANY TO ONE

Let’s consider the same scenario again. Many phone numbers can belong to one person.

Inheritance
Mapping
Employee Phone
Association One to many
mapping Phone
Mapping
• address Address
Phone
Collection • id integer
Mapping • name String • areaCode String
• phones Vector • id integer
Component
• owner Employee
Mapping Java Class (source)
One to one mapping
• number String

Java Classes (target)

One to One One to Many Many to One Many to Many


Types of Mapping in Hibernate
ASSOCIATION MAPPING: MANY TO ONE

Creating classes: Person Class: Phone Class

Inheritance class Person @Entity


Mapping { @Table(name="Phone")
@Entity
int id; public class Phone {
@Table(name="PERSON")
Association String name; public class Person {
@Id
Mapping } @Id
private int Id;
private int
Collection private int id;
class Phone phoneNumber;
private String name;
Mapping { @ManytoOne
// setter getter methods
int id; private Person person
Component int phoneNumber;
}
//setter and getter methods
Mapping } }

One to One One to Many Many to One Many to Many


Types of Mapping in Hibernate
ASSOCIATION MAPPING: MANY TO ONE

Creating objects for Person and Phone class

Inheritance Person user=new Person(); Person table


Mapping user.setId(1);
id name
user.setName(“john”);
Association Phone p1= new Phone(); 1 john
Mapping p1.(101); 2 Stella
p1.(123456789);
Collection p1.setPerson(user); Phone table
Mapping Phone p2= new Phone();
p2.(102); id phoneNumber
Component p2.(1112131415); 101 123456789
Mapping p2.setPerson(user);
102 1112131415
session.save(user);
session.save(p1);session.save(p2);

One to One One to Many Many to One Many to Many


Types of Mapping in Hibernate
ASSOCIATION MAPPING: MANY TO MANY

A many-to-many association is defined logically using the @ManyToMany annotation. You also
have to describe the association table and the join conditions using the @JoinTable annotation.
Inheritance
Mapping
Association Employee Meeting
Mapping 1 1
Collection employee_id meeting_id
Mapping
firstname subject
Component Employee_Meeting
lastname meeting_date
Mapping
employee_id

meeting_id

One to One One to Many Many to One Many to Many


Types of Mapping in Hibernate
COLLECTION MAPPING

Hibernate allows you to map collection elements of Persistent class. It can be done by
Inheritance declaring the type of collection in Persistent class from one of the following types:
Mapping
Association • java.util.List
Mapping
• java.util.Set
Collection
• java.util.SortedSet
Mapping
• java.util.Map
Component
Mapping • java.util.SortedMap
• java.util.Collection
• or write the implementation of org.hibernate.usertype.UserCollectionType
Types of Mapping in Hibernate
COMPONENT MAPPING

Component refers to the object-oriented notation.

Inheritance For example: Student class has one class member: Name. Name is also one class that has two
Mapping members, firstName and lastName.

Association
Phone Class
Mapping Person Class
@Entity
Collection @Entity
@Table(name="Phone")
Mapping @Table(name="PERSON")
public class Phone {
public class Person {
@Id
Component @Id
private int Id;
Mapping private int id;
private int
private String name;
phoneNumber;
@ManytoMany
@ManytoOne
private Collection<Meeting>=new
private Collection <Person > person=new
ArrayList();
ArrayList();
// setter getter methods
//setter and getter methods
}
}
Types of Mapping in Hibernate
COMPONENT MAPPING

Creating objects for Person and Phone class:

Person user=new Person();


Person table Phone table
Inheritance user.setId(1);
Mapping user.setName(“john”); id name id phoneNumber person_id
Meeting p1= new Meeting();
Association p1.(101); 1 john 101 123456789 1
Mapping p1.(123456789); 2 Stella 102 1112131415 1
p1.getPerson().add(user);
Collection Phone p2= new Phone();
Mapping meeting_person TABLE person_meeting TABLE
p2.(102);
p2.(1112131415);
Component meeting_id person_id id phoneNumber
p2.getPerson().add(user);
Mapping user.getMeeting().add(p1); 101 1 1 101
user.getMeeting().add(p2);
session.save(user); 102 1 1 102
session.save(p1);session.save(p2);

In component mapping, the dependent object is mapped as a component. A component is an object that is
stored as a value rather than entity reference. This is mainly used if the dependent object doesn't have
primary key. It is used in case of composition (HAS-A relation). That is why it is termed component.
Advanced Java
Topic 5—Transaction Management
What Is Transaction Management?

A transaction simply represents a unit of work if one step fails, the whole transaction fails.

It is described by ACID properties (Atomicity, Consistency, Isolation, and Durability).

Transaction succeeded
commit

Initial state Transaction

rollback
Transaction failed
Transaction Interface

In hibernate framework, we have transaction interface that defines the unit of work.

• A transaction is associated with Session and instantiated by calling session.beginTransaction().

• void begin() starts a new transaction

• void commit() ends the unit of work unless you are in FlushMode.NEVER.

• void rollback() forces this transaction to rollback.

• void setTimeout(int seconds) sets a transaction timeout for any transaction started by a subsequent call to
begin on this instance.

• boolean isAlive() checks if the transaction is still alive.

• void registerSynchronization(Synchronizations) registers a user synchronization callback for this transaction.

• boolean wasCommited() checks if the transaction was committed successfully.

• boolean wasRolledBack() checks if the transaction was rolled back successfully.


Key Takeaways

Hibernate provides its own language known as Hibernate Query Language. The
syntax is quite similar to database SQL language.

HQL is a Hibernate language for relational database management


systems. HQL statements are used to perform tasks such as updating data on a
database or retrieving data from a database.

The criterion package may be used by applications as a framework for building


new kinds of criterion.

Hibernate provides the option to execute native SQL queries through the use
of SQLQuery object.

Criteria Query allows you to apply filtration rule and logical condition with query.
org.hibernate.Criteria Query is a method provided by Criteria API that helps in
creating criteria query programmatically.
Quiz
Thank You
Advanced Java
Lesson 7—Introduction to Spring

© Simplilearn. All rights reserved.


Learning Objectives

Discuss Spring and its Architecture

Describe IOC and DI

Understand SpringBean Lifecycle

Explain Bean Wiring and Bean Scope


Advanced Java
Topic 1—Spring Basics
Recall: Java EE Architecture

Application Layer

Data
Client Layer Server Business Data
Access
Layer Layer
Layer

Presentation Layer
Shortcomings of the Java EE Architecture

• Java EE specifications don’t help in understanding the implementation of the specification and the
environment.

• The components in the architecture are written in a way that only the container can understand or handle
them.
Why Spring?

• Spring is a framework that can help simplify the Java EE architecture by reducing the complexity involved
in enterprise application development by using Java EE technologies directly.

• Its gives abstract layer for all the layers involved in Java EE architecture.
Why Spring: Example

Let’s consider Database Provider and Utilizer:

ConnectionUtilizer1.java ConnectionUtilizer1.java
public class ConnectionUtilizer1 public class ConnectionUtilizer1
{ {
public static void main(String[] args) public static void main(String[] args)
{ {
System.out.print(“Utilizer is using Oracle System.out.print(“Utilizer is using MySQL
Connection”); Connection”);
} }

We modify the Utilizer class according to the service type.

Observe that the Utilizer is tightly coupled with one particular Provider. This implies that we need to
modify our code every time we need a new Provider.

Due to this, it is always advisable to write different classes for Utilizer logic and Provider logic.
Why Spring: Example

OracleConeectionProvider.java MysqlConeectionProvider.java
public class OracleConnectionProvider public class MysqlConnectionProvider
{ {
public static String getOracleProvider() public static String getMysqlProvider()
{ {
return “Utilizer is using Oracle Connection”; return “Utilizer is using Mysql Connection”;
} }
} }

ConnectionUtilizer.java
public class ConnectionUtilizer
{
public static void main(String[] args)
{
OracleConnectionProvider connection=new OracleConnectionProvider(); // It we want to get
Mysql Connection we need to create its object
String name=connection.getOracleConnectionProvider(); To get connection from Oracle Provider, we call this
System.out.print(name); method of OracleConnectionProvider. For MySQL, we
} would use a different method. This involves calling two
} different methods from two different classes.

It is advisable to have a contract between Service Provider and Utilizer to avoid calling two different method
names. In Java, we can provide contract with interface.
Why Spring: Example

Service Utilizer Contract OracleConnectionProvider

OracleConeectionProvider.java
ConnectionUtilizerOne.java
public class OracleConnectionProvider
public class ConnectionUtilizerOne
{
{
public static String getConnection()
public static void main(String[] args)
{
{
return “Utilizer is using Oracle
Connection contarct=new
Connection”;
OracleConnectionProvider();
}
String name=contarct.getConnection(); Connetion.java
}
System.out.print(name);
} public interface Connection
} {
public String getConnection(); MysqlConnectionProvider
ConnectionUtilizerTwo.java
public class ConnectionUtilizerTwo }
{ MysqlConeectionProvider.java
public static void main(String[] args) public class OracleConnectionProvider
{ {
Connection contarct=new public static String getConnection()
MysqlConnectionProvider(); {
String name=contarct.getConnection(); return “Utilizer is using Mysql
System.out.print(name); Connection”;
} }
} }
Why Spring: Example

To change the provider class, the application needs to be compiled.

To do so, it is advisable to use either properties file or XML file. We can write one container that reads the
requirement and provides required objects dynamically.

Service Utilizer Contract OracleConnectionProvider

Specifying
Required
MysqlConnectionProvider
Provider Class
Myproperties.properties

MyContainer
Calling getBean() methods
Why Spring: Example

Next, create Myproperties.properties file to mention the provider name.

Suppose our provider is OracleConnectionProvider. It should be written as:

Myproperties.properties

1.provider=OracleConnectionProvider
Why Spring: Example

Let’s create a MyContainer class to fetch the properties from the Myproperties.properties file.

public class MyContainer {


private static Properties;
static{
properties = new Properties();
properties.load(MyContainer.class.getClassLoader().getResourceAsStream(“myproperties.properties”
));
}
public static Object getBean(String provideKey) {
Object object=null;
String providerClassName=properties.getProperty(providerKey);
Class c= Class.forNamw(providerClassName);
Object=c.newInstance();
return object;
} }
Why Spring: Example

Next, write the Utilizer code to create object of MyContainer class.

public class ConnectionUtiliaer{


private static MyContainer container = new MyContainer();
public static void main(String args[]) {
Connection contract=(Connection) container.getBean(“provider”);
String name=contract.getConncetion();
} }

If you want to change the provider class, just change the properties file. It creates loose coupling
between the provider and service object.

Spring provides the container and spring configuration file (XML) to configure the required
provider classes instead of properties file. This can make the process easy.
Spring Basics

• Spring was Invented by Rod Johnson

• The latest version of spring is Spring 4.0

Spring 4.0 can be downloaded


from: http://maven.springframework.org/release/org/springframework/spring/4.2.0.RELEASE/

Link to download common loggings:


http://www.java2s.com/Code/Jar/o/Downloadorgapachecommonsloggingjar.htm
What is Spring?

“Spring Framework is a Java platform that provides comprehensive infrastructure support for
developing Java applications. Spring handles the infrastructure to ensure focus on your application.”

Spring framework :

• Is an open source framework


• Is a lightweight framework
• Is developed in Java
• Eliminates common code
• Is from SpringOpensource community
What’s New in Spring 4.0?

Spring 3.0 (Version before 4.0) Spring 4.0


It does not give comprehensive support Spring Framework 4.0 provides support for several Java 8
for JDK8. features. You can make use of lambda expressions and method
references with Spring’s call-back interfaces.
It provides Spring MVC Test Framework Spring Framework 4.0 introduces several new features for use in
unit and integration testing.
There is no support for Date-Time JSR-310 provides Date-Time value types for Spring data binding
and formatting.
Features of Spring

• It supports multiple transaction environments such as JTA, Hibernate, and JDBC (Java Database
Connectivity).

• It encourages good object-oriented design practices (e.g., interfaces, layers, separation of concerns).

• It provides IOC/DI (Inversion of Control/Dependency Injection) container.

• It supports annotation.

• POJOs (Plain Old Java Object) are faster than XML (Extensible Markup Language) Descriptor. Spring
supports POJO.
Advanced Java
Topic 2—Spring Architecture
Spring Architecture

Spring Framework Runtime

Data Access/Integration Web (MVC/Remoting)

JDBC ORM Web Servlet

OXM JMS Portlet Struts

Transactions

AOP Aspects Instrumentation

Core Container

Expression
Beans Core Context
Language

Test
Spring Architecture
DATA ACCESS/INTEGRATION LAYER

Data Access/Integration

JDBC ORM

OXM JMS

Transactions

• JDBC (Java Database Connectivity) provides a JDBC-abstraction layer that removes the need for traditional
JDBC coding.
• ORM (Object XML Mappers) provides integration layers for popular object-relational mapping APIs.
• OXM provides an abstraction layer that supports Object/XML mapping implementation.
• Spring provides Java Message Service integration to simplify the use of the JMS API.
• Spring framework provides an abstract layer on top of different underlying transaction management APIs
in transaction layer of spring.
Spring Architecture
WEB LAYER

Web (MVC/Remoting)

Web Servlet

Portlet Struts

• Web: Web module provides basic web-oriented integration features.

• Web-Servlet: The Web-Servlet module contains Spring's model-view-controller (MVC) implementation.

• Web-Portlet modules: The Web-Portlet module provides the MVC implementation to be used in a
portlet environment and mirrors the functionality of Web-Servlet module.

• Web-Struts: The Web-Struts module contains the support classes for integrating a classic Struts web
tier within a Spring application.
Spring Architecture
CORE CONTAINER

Core Container

Expression
Beans Core Context
Language

• Beans: It provides BeanFactory (factory pattern). This allows you to decouple the configuration and
specification of dependencies from your actual program logic.

• Core: It provides Inversion of Control and Dependency Injection features.

• Context: The Context module inherits its features from the Beans module and adds support for
internationalization (using, for example, resource bundles), event-propagation, and resource-loading.

• Expression Language modules: These provide a powerful expression language for querying and
manipulating an object graph at runtime.
Spring Architecture
MODULES

AOP (Aspect-oriented programming): It develops proxies for business layer and works as a solution for
cross cutting problem.

Test: This module supports the testing of Spring components with JUnit or TestNG.

Design Pattern: Includes Singleton, MVC, Factory, etc.


Advanced Java
Topic 3—Inversion of Control (IOC)
Recall

We have discussed that Spring provides the container and provides spring configuration file (XML file) to
configure our required provider classes instead properties file.

Spring container is an IOC (Inversion of Control) container.


What is IOC?

• IOC is a design principle that explains how object creation, dependency injection, object life cycle
management, object destruction, etc., can be managed using an external entity.

• Spring Container is the external entity that implements the principles of IOC.
Spring IOC Container

It is the core container of the Spring Framework. It performs the following operations:

1. Create the objects


2. Wire them together
3. Configure them
4. Manage their lifecycle till destruction

Java classes that are handled by this container are called spring beans.
Uses of Spring IOC Container

Containers are used for the following functions:

1. Instantiation of object
2. Dependency injection
3. Initialization to read configuration metadata
Spring Framework's IOC Container Package

There are two IOC container packages:

• org.springframework.beans

• org.springframework.context packages
IOC Container: Working

Spring container uses POJO classes and configures metadata to produce fully configured and executable beans.

POJO

Meta Data
IOC Container

Output

Results
Types of IOC Container

There are two types of Spring Container, which are based on the following interface:

BeanFactory (I)

extends

ApplicationContext (I)

BeanFactory and ApplicationContext are the interface for container.


Implementation for XMLBeanFactory

XMLBeanFactory class gives the implementation for BeanFactory interface.

BeanFactory (interface)

implements

XMLBeanFactory (class)
Containers based on BeanFactory Interface

• Spring bean is configured in configuration file. Beanfactory container loads that bean. It is a lightweight
container.

• It manages the life cycle of spring bean.

• The lifecycle of Bean starts from calling the getBean(“ “) method.

• It is generally used in the application where data volume and speed is significant, for example, mobile
devices or applet-based applications.
Implementation for ApplicationContext

ApplicationContext

implements

ClassPathXMLApplicationContext FileSystemXmlApplicationContext XmlWebApplicationContext


Container Based on ApplicationContext Interface

• If you use FileSystemXmlApplicationContext container, you need to pass the spring configuration file to this
constructor.

• If you change the project location once, you have to change it every time.

• If you use ClassPathXmlApplicationContext, you don’t have to specify the complete path of configuration file.

• If you change project location, your file will work without modification.

• If you use XmlWebApplicationContext, you can use Spring MVC module.

• Container based on ApplicationContext provides all the features of BeanFactory. In addition to this, it
provides the following features:
o Event-Handling
o EJB integration
o Transaction
o Securities
Creating Bean Container using XmlBeanFactory Class

Creating Spring Bean Container involves creating an object of any implemented class in XmlBeanFactory.

Resource resource=new ClassPathResource("applicationContext.xml");

OR

Resource resource=new ClassPathResource("path/applicationContext.xml");


BeanFactory factory=new XmlBeanFactory(resource);
Implementation of Resource Interface

Constructor of XmlBeanFactory class takes Resource object as an argument. This represents spring
configuration file.

There are two implementations of Resource interface:

Resource

Absolute Path Relative Path

FileSystemResource ClassPathResource
Creating SpringBean Container

Creating Spring Bean Container involves creating an object of any implemented class.

Creating Spring Bean Container using FileSystemXmlApplicationContext class

ClassPathXmlApplicationContext .

ApplicationContext context=new ClassPathXmlApplicationContext


("path/applicationContext.xml");

Creating Spring Bean Container using ClassPathXmlApplicationContext class

ClassPathXmlApplicationContext .

ApplicationContext context=new ClassPathXmlApplicationContext


("applicationContext.xml");
Advanced Java
Topic 4—Spring in Eclipse
Creating Spring Applications in Eclipse

1. Create a Java project in eclipse and add a name to it: Click New  Click Project  Click Java Project,
Add a name  Click Next

2. Add spring jar files: Right click on project  Click Buildpath  Click Library  Click on add external
library and add spring libraries. You can also Click on user library and add spring jar to this user-
defined library folder.

3. Create the class: Right click project  Create Java class in src folder  Add a name Write private
properties inside Java class  Select properties and click on right  Click Source  Generate setter
and getter method.

This class is called spring bean. The syntax is provided below:

class ClassName
{
//public constructor
//private variable ;
//public getter and setter methods for variable;
}
Creating Spring Applications in Eclipse

4. Create the xml file to provide the values: Right click project  Create xml file  Add a name  Click Next.
This is called configuration file.

5. Create a test class inside src folder. Steps to write code for test class:

• Create spring container using either XmlBeanFactory or ApplicationContext


• Call get id method and pass reference variable name

SpringBeanName
reference_variable=(SpringBeanName)factory.getBean("reference_id_for_class_objec
t");

This can access all the methods of


SpringBean class.
Configuration File Tags

• <beans
• xmlns="http://www.springframework.org/schema/beans"
• xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
• xmlns:p="http://www.springframework.org/schema/p"
• xsi:schemaLocation="http://www.springframework.org/schema/beans
• http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
• <bean id="refernce_id_for_class_object" class="ClassName">
• </bean>
• </beans>
Advanced Java
Topic 5—Dependency Injection
Dependency Injection: Example

Let’s look at an example to understand DI in Spring:

class Author class Book


{ {
private String name;
private Book book; private String name;
} private String type;
}

• Class Author is dependent on Book class


• Class Book will get injected into class A by the IOC
• Resolving the dependencies among the beans is called Dependency Injection
Types of DI

In Spring, DI is achieved in two ways:

• Setter injection: If dependency is injected to dependent object via setter method, it is known as setter
injection.

• Constructor injection: If dependency is injected to dependent object via constructor, it is known as


constructor injection.
Advantages of Using DI

• The dependency object can be changed dynamically.


• Provide loose coupling between dependent and dependencies.
• The codes appear clean and readable.
• DI and IOC make managing dependencies between objects simple.
Implementing Setter Injection

1. Create Spring bean class


2. Declare member variable
3. Define setter methods
4. Use <property> tag in bean configuration file
5. Provide values for member variable in configuration file
Implementing Constructor Injection

1. Create Spring bean class


2. Declare member variable
3. Define constructor, which will take variable as parameter
4. Use <constructor-arg> tag in bean configuration file
5. Provide values for member variable in configuration file
Spring Configuration file
SETTER INJECTION

<beans…>
<bean id=” “ class=” “ >
<property name=”nameOfClassMemberVariable” value =” “ >
</property>

or

<property name=”nameOfClassMemberVariable” value =” “ />

or

<property name =”nameOfClassMemberVariable”> <value> </value>


</property>
</bean>
</beans>
Spring Configuration file
SETTER INJECTION WHERE DEPENDENCY IS OBJECT TYPE

<beans…>
<bean id=” “ class=” “ >
<property name=”nameOfClassMemberVariable” ref =”dependency_class_id
“ > </property>

or

<property name=”nameOfClassMemberVariable” ref =”dependency_class_id


“ />

or

<property name =”nameOfClassMemberVariable”> <ref local/bean/pparent


”dependency_class_id” />
</property>
</bean>
</beans>
Implementing Constructor Injection

Spring configuration file


<beans…>
<bean id=” “ class=” “ >
<constructor-arg value =” “ type=” data_type”> </constructor-arg >

or

<constructor-arg value =” “ />

or

<constructor-arg>
<value> </value>
</constructor-arg>
</property>
</bean>
</beans>
Implementing Constructor Injection
IMPLEMENTATION OF CONSTRUCTOR INJECTION WHERE DEPENDENCY IS OBJECT TYPE

Spring configuration file


<beans…>
<bean id=” “ class=” “ >
<constructor-arg ref=” ”> </constructor-arg >

or

<constructor-arg ref =” “ />

or

<constructor-arg>
<ref local/bean/parent=”providerRef”/>
</constructor-arg>
</property>
</bean>
</beans>
Injecting Collection Object

To pass multiple values to bean, we use collection injection. Spring offers four types of collection
configuration elements:

Element Description

<list> inject list of values, allowing duplicates

<set> inject set of values without duplication

<map> inject name-value pair

<props> inject name-value pair where name and value are both Strings
Configuration File for Injecting Collection Injection

<beans…>
<bean id=” “ class=” “ >
<property name=”nameOfClassMemberVariable” >
<list>
<value> …... < /value>
<value>.......</value>
<value>......</value>
</list>
</property>
</bean>
</beans>

In case of set, replace <list> tag with <set> tag


Configuration File for Injecting Collection Injection
OBJECT TYPE DEPENDENCY

<beans…>
<bean id=” “ class=” “ >
<property name=”nameOfClassMemberVariable” >
<list>
<ref bean=” reference_id1“ />
<ref bean=” reference_id2“ />
<ref bean=” reference_id3“ />
</list>
</property>
</bean>
</beans>

In case of set, replace <list> tag with <set> tag


Constructor Injection vs. Setter Injection

Constructor Injection Setter Injection


In constructor injection, partial injection of In setter injection, partial injection of
dependencies is not possible. This is because we dependencies is possible
must pass all the arguments to call constructor.
Constructor injection cannot override the values Setter injection overrides the values injected by
injected by setter. constructor.
For dependencies > 15, setter method is not Ideal for dependencies > 15
recommended.
Constructor injection makes bean class object Setter injection makes bean class object mutable
immutable (cannot be changed). (can be changed).
Advanced Java
DEMO—Constructor and Setter Injection
Advanced Java
Topic 5—SpringBean Lifecycle
Spring Container

Recall: Springbean factory is responsible for managing the life cycle of beans created through spring
container.

Spring container controls the life cycle of spring bean. It creates the object for bean, injects
dependencies, performs initialization operation, calls business methods, and removes it from the
container (when bean is no longer required).
SpringBean Lifecycle

Instantiation Populate properties BeanNameAware BeanFactoryAware

InitializingBean
or
init-method Initialization ApplicationContextAware
or
@PostConstruct

DisposableBean
or Bean is removed
Bran is ready Container is destroy-method from the
to use shutdown or container
@PreDestro
SpringBean Lifecycle Components

1. Instantiate: Creation of object is done by spring container

2. Populate properties: Spring bean properties are populated by dependency injection

3. BeanNameAware: An interface used to override its method setBeanName(String) and get bean name

4. BeanFactoryAware: It is used to get container information in which spring bean is available

5. Initialization: There are three options for controlling Initialization;


1. InitializingBean
2. custom init()
3. @PostConstruct annotations

6. Method Ready State: In this state, object is ready for use and business methods can be called.

7. Destruction: Three options for controlling Initialization


1. DisposibleBean
2. custom destroy()
3. @PreDestroy annotations
Initialization
InitializingBean

It is an interface used to implement its method afterPropertiesSet(). Initialization can be written


inside this method.

Syntax:

class SpringBeanExample implements InitializingBean


{
public void afterPropertiesSet()
{
}
}

@PostConstruct
InitializingBean custom init()
annotations
Initialization
custom init()

In the case of XML-based configuration metadata, you can use the init-method attribute to specify the
name of the method.

Syntax:

<bean id=”idName” class=”SpringBeanExample” init-method=”init”/>

@PostConstruct
InitializingBean custom init()
annotations
Initialization
@PostConstruct annotations

In the case of Annotation–based configuration metadata , you can use @PostConstruct annotation of JDK at
the top of the method to specify the method as initialization method.

Syntax:

public class SpringExampleBean


{
@PostConstruct
public void myinit()
{
// do some initialization work
}
}

@PostConstruct
InitializingBean custom init()
annotations
Destruction
DisposibleBean

It is an interface used to implement the destroy() method. You can write initialization inside this method.

Syntax:

class SpringBeanExample implements


DisposibleBean
{
public void destroy()
{
}
}

@PreDestroy
DisposibleBean custom destroy()
annotations
Destruction
custom destroy()

In the case of XML-based configuration metadata, you can use the destroy method attribute to specify the
name of the method.

Syntax:

<bean id=”idforbean” class=”SpringBeanExample” destroy-method=”destroy”/>

@PreDestroy
DisposibleBean custom destroy()
annotations
Destruction
@PreDestroy annotations

In the case of Annotation–based configuration metadata , you can use @PreDestroy annotation of JDK at
the top of the method to specify the method as destruction method.

Syntax:

public class SpringExampleBean


{
@PreDestroy
public void mydestroy()
{
// do some initialization work
}
}

@PreDestroy
DisposibleBean custom destroy()
annotations
Advanced Java
Topic 6—Bean Wiring
What is Bean Wiring?

The Spring container can autowire relationships between collaborating beans without
using <constructor-arg> and <property> elements. This is known as Bean Wiring.
AutoWiring

• AutoWiring refers to injecting the dependencies automatically


• It is used for object injection as it provides one way of injecting object dependency without<property>
and <constructor-arg> injection.
• To implement autowiring, use autowire attribute of <bean> tag
Types of AutoWiring

1. constructor
2. byName
3. byType
4. autodetect
Types of AutoWiring
constructor

When autowire=”constructor” the container checks the constructor parameter type.

constructor Example:

byName SpringBeanClass(Student std) // constructor having parameter Student class type


{
}
byType
The container looks for beans configured with the name Student. If found, it injects all beans.
autodetect

If a class has multiple constructors, then it checks parameter type.


Types of AutoWiring
byName

When autowire=”byName” the container checks all the setter methods (that have only one parameter)
constructor within the bean.

Example:
byName
setExamDetail(ExamDetail exed);// method having parameter ExamDetail class type
byType
The container looks for beans configured with the name ExamDetail. If found, it injects all beans.
autodetect

It doesn’t bother about setter method parameter type; it only considers setter method names.
Types of AutoWiring
byType

When autowire=”byType” the container checks all the setters methods (that have one parameter) type
constructor in that bean.

Example:
byName
setExamDetail(ExamDetail exed);// method having parameter ExamDetail class type
byType
The container looks for beans configured with the name ExamDetail. If found, it injects all beans.
autodetect

It doesn’t bother about setter method name and bean id; it only considers setter method
parameter type.
Types of AutoWiring
autodetect

When autowire=”autodetect” , the Spring first tries to wire using autowire by constructor, if it does
constructor
not work, Spring tries to autowire by byType.

byName

byType

autodetect

This is deprecated as of Spring 3.0.


Advanced Java
DEMO—Perform AutoWiring by constructor, byName, byType
Advanced Java
Topic 7—Bean Scope
Bean Scope

When defining a <bean>, you have the option of declaring a scope for that bean. There can be two choices.

1) You want Spring to return the same bean instance each time one is needed

2) You want to force Spring to produce a new bean instance each time one is needed
Scope Attributes

Scope attribute has following values:

1) singleton: Create the configured spring bean only once in the container

2) prototype: Create the configured spring bean each time it is requested

3) request: Create the configure spring bean once per web request. It is applicable only in web
module

4) session: Create the configured spring bean once per HttpSession. It is applicable only in web
module

5) thread: Create the configured spring ben once per each thread
Key Takeaways

Spring Framework is a Java platform that provides comprehensive infrastructure


support for developing Java applications. Spring handles the infrastructure to
ensure focus on your application.

Spring container is IOC (Inversion of Control) container. IOC is a design principle


that explains how object creation, dependency injection, object life cycle
management, object destruction, etc., can be managed using an external entity.

Spring container controls the life cycle of spring bean. It creates the object for
bean, injects dependencies, performs initialization operation, calls business
methods, and removes it from the container (when bean is no longer required).

The Spring container can autowire relationships between collaborating beans


without using <constructor-arg> and <property> elements. It is known as Bean
Wiring.
Quiz
QUIZ
The Beans in Spring are ________ by default.
1

a. prototype

b. singleton

c. request

d. session
QUIZ
The Beans in Spring are ________ by default.
1

a. prototype

b. singleton

c. request

d. session

The correct answer is b. singleton


The Beans in Spring are singleton by default.
QUIZ
Which of the following is true of Spring?
2

a. It is a lightweight framework

b. It is an opensource framework

c. It doesn't accept struts and hibernate

d. Both (a) and (b)


QUIZ
Which of the following is true of Spring?
2

a. It is a lightweight framework

b. It is an opensource framework

c. It doesn't accept struts and hibernate

d. Both (a) and (b)

The correct answer is d. Both (a) and (b)


Spring is a lightweight and opensource framework.
Thank You
Advanced Java
Lesson 8—Spring AOP

© Simplilearn. All rights reserved.


Learning Objectives

Explain AOP and its terminology

Configure AOP in a Java Application using AspectJ Approach


Advanced Java
Topic 1—Introduction to Spring AOP (Aspect-Oriented Programming)
Why AOP?

AOP is used in applications that have cross-cutting concerns, that is, pieces of logic or code that are written
in multiple classes/layers as per the requirements.

Common examples:

• Transaction Management
• Logging
• Exception Handling (especially when you may want to have detailed traces or have some plan of
recovering from exceptions)
• Security aspects
• Instrumentation
Understanding Concerns

A concern is a piece of code that performs a specific task. There are two types of concerns:

1) “Core” concerns are codes used for business logic

2) “Cross concerns” are functions that are conceptually separate from the application's business logic
but affect the entire service layer.

Example: logging, auditing, declarative transactions, security, caching

Aspect-Oriented Programming provides one way to decouple dynamically core concern from
crosscutting concern.
What Is AOP?

1) It is one of the basic components of Spring framework.

2) The main idea of AOP (Aspect-Oriented Programing) is to isolate the cross-cutting concerns
from the application code, thereby modularizing them as a different entity.

3) Services layer deals with two types of concerns: Core and cross cutting concerns.
Uses of AOP

• Spring AOP provides declarative enterprise services such as declarative transaction management.
• It allow users to implement custom aspects.
• Spring AOP is used to track user activity in large business applications.
• It uses Proxy as a mechanism to implement cross-cutting concerns in a non-intrusive way.
AOP Terminologies

• Aspect: A feature or functionality that cross-cuts over objects. It has a set of APIs (Application
Programming Interface) that provides cross-cutting requirements.

• JoinPoint: It defines the various execution points where an Aspect can be applied

• Pointcut: A Pointcut tells us about the Join Points where Aspects will be applied

• Advice: An advice provides concrete code implementation for the Aspect

• Target: It is a business object that comprises of Aspect business core concern


AOP Terminologies

• Weaving: It represents a mechanism of associating cross cutting concern to core concern dynamically.

• Proxy: Proxy is an object produced through weaving. There are two types: static proxy and dynamic proxy.

o In static proxy, static method is used to develop and maintain proxy classes for each business method.
o In dynamic proxy, proxy is developed at run time.

• Weaver: Code that produces proxies

• Proxy design pattern: Actual object (business object) is wrapped into another object knows as proxy and
substitutes that object in place of actual object

We will discuss JoinPoint, Pointcut, and Proxy in this lesson.


AOP Terminologies
Pointcut

Pointcut defines where exactly the Advices have to be applied in various Join Points.
Generally, they act as Filters for the application of various Advices into the real implementation.
AOP Terminologies
Pointcut: TYPES
Springs defines two types of Pointcut:

1. Static: It verifies whether the join point has to be advised or not. It does this once the result is catched @reused.
2. Dynamic: It verifies every time as it has to decide the Join Point based on the argument passes to method call.

Pointcut

StaticMethodMatcher DynamicMethodMatcher
Pointcut Pointcut

ControlFlowPointcut
NameMatchMethod AbstractRegexpMethod
Pointcut Pointcut

JdkRegexMethod PerlRegexMethod
Pointcut Pointcut
AOP Terminologies
StaticMethodMatcherPointcut

StaticMethodMatcherPointcut has two types of Pointcuts:

1. NameMatchMethodPointcut: It interrupts a method via ‘pointcut’ and ‘advisor’

2. AbstractRegexpMethodPointcut: Besides matching method by name, it can match the method’s name by
using regular expression pointcut.

This pointcut is used to verify join point based on pattern of the method name instead of name.
AOP Terminologies
AbstractRegexpMethodPointcut

1. JdkRegexMethod Pointcut: It is represented by org.springframework.aop.JdkRegexpMethodPointcut

2. PerlRegexMethodPointcut: It is represented by org.springframework.aop.support.Perl5RegexpMethodPointcut


AOP Terminologies
DynamicMethodMatcherPointcut

This pointcut is used to verify the context from which business method call is made. If method
call is made in specific flow, it will be advice; otherwise, it won’t.
AOP Terminologies
POINTCUT INTERFACE

Pointcut is an interface; it is represented by org.springframework.aop.Pointcut.

public interface Pointcut


{
ClssFilter getClassFilter()
MethodMatcher getMethodMatcher()
}

The getClassFilter() method returns a


ClassFilter object which determines
whether the classObject argument passed
to the matches() method should be
considered for giving Advices
AOP Terminologies
Joinpoint

A Joinpoint is a candidate point in the Program Execution of the application where an aspect can be
plugged in.

This point could be a method being called, an exception being thrown, or even a field being modified.

These are the points where your aspect’s code can be inserted into the normal flow of your application to
add new behavior.

A pointcut defines the Joinpoints where associated Advice should be applied.


AOP Terminologies
Joinpoint METHODS

Return Type Method Name Description


AccessibleObject getStaticPart() Return the static part of Joinpoint
Object getThis() Return the object that holds the current Joinpoint
static part
Object proceed() Proceed to the next interceptor in the chain
How Does AOP work?

Proxy interrupts the call made by caller to original object. It will have chance to decide whether and
when to pass on the call to original object. In the meantime, any additional code can be executed.

Spring uses the dynamic proxy approach.

Proxy object

Caller call to business Original


on original object Object

A dynamic proxy class is a class that implements a list of interfaces specified at runtime
so that a method invocation through one of the interfaces on an instance of the class will
be encoded and dispatched to another object through a uniform interface.
AOP Terminologies
Proxy

• In proxy pattern, a class represents functionality of another class. This type of design pattern is a
structural pattern.

• It creates an object that has original object to interface its functionality to outer world. Proxy design
pattern is used when we want to provide controlled access to a functionality.

• It is also used to save on the amount of memory used. Similarly, if you want to control access to an
object, the pattern becomes useful.
Ways to Generate Dynamic Proxy

1. jdk approach: When the business class implements interface, jdk creates proxy for the business object

2. cglib approach: cglib.jar is used when a business class fails to implement any interface, and jdk is
unable to create proxy
AOP Terminologies
Advice

Advice refers to the actual implementation code for an Aspect. Spring supports Method Aspect.

Different types of aspects available in Spring are:

1. Before advice: It executes before a Joinpoint but does not have the ability to prevent execution flow
proceeding to the Joinpoint

2. After advice: It is executed after business method call.

3. Around advice: It surrounds a Joinpoint such as a method invocation. It can perform custom behavior
before and after method invocation.

4. Throws Advice is executed if actual method throws exception.


AOP Terminologies
Steps to Configure Advice

1. To configure these advices, we have to depend on ProxyFactoryBean. This Bean is used to create Proxy
objects for the implementation class along with the Advice implementation.

2. The property ‘proxyInterface’ contains the Interface Name for which the proxy class has to be generated.

3. The ‘interceptorNames’ property takes a list of Advices to be applied to the dynamically generated proxy
class.

4. Finally, the implementation class is given in the ‘target’ property.


Before Advice

• It is used to intercept before the method execution starts. For example, a system may need to perform
some logging operations before allowing users to access resources

• Whenever caller calls the business method, all before advice code is executed prior to the business
method.

If exception occurs in the method, afterReturning() method will never be called.


Configuring Before Advice

1) Develop a business interface and its implemented class


2) Develop a class that implements AfterReturningAdvice interface
3) Override its afterReturning() method[(Method method, Object[] args, Object target )]. Cross
cutting code is written here.
• afterReturningMethod method - target method to be invoked
• Object[] args - various arguments that are passed on to the method
• Object target - target reference to the object that is calling the method
4) Get a proxy
5) Make a method call
Steps Diagram: Before Advice

Client Proxy Before Advice CustomerServicelmpl

call Business() method

proxy call before

control will return back

proxy call business() method


After Advice

• It is used to intercept after the method execution. For example, a system needs to perform some
delete operations after logging out.

• After Advice is executed after business method.


Configuring After Advice

1. Develop a business interface and its implemented class


2. Develop a class that implements AfterReturningAdvice interface
3. Override its afterReturning (Method method, Object[] args, Object target) method. Cross
cutting code is written here.
• Method method - target method is invoked
• Object[] args - various arguments that are passed to the method
• Object target - target reference to the object that is calling the method
4. Get a proxy
5. Make a method call

If exception occur in the method, afterReturning() method will never be called.


Steps Diagram: After Advice

Client Proxy Before Advice CustomerServicelmpl

call Business() method

proxy call business() method

proxy call afterReturnning()

return will come back


Around Advice

• It can change the return argument of the method call.


• It provides finer control regarding whether the target method has to be called or not.
• It can be performed before business logic or after business logic.
Configuring Around Advice

• Develop a class that implements MethodInterceptor interface


• Override its invoke method. Write cross cutting code
• Get a proxy
• Make a method call
• Parameter of invoke method()

public Object invoke(MethodInvocation methodInvocation)


Steps Diagram: Around Advice

Client Proxy Before Advice CustomerServicelmpl

call Business() method

proxy call business() method

invoke()

internally calls business() method


Throws Advice

When an exception happens during the execution of a method, Throws Advice can be used through the
means of org.springframwork.aop.ThrowsAdvice to handle the exception.

• This advice is executed only when exception is raised

• Advice has to implement org.springframework.aop.ThrowsAdvice. It is just a marker interface

• Exception handling code is considered cross cutting code and can be done for entire service layer in
Throwsadvice with different kinds of exception parameters.
Configuring Throws Advice

1. Develop a business interface and its implemented class


2. Develop a class that implements ThrowsAdvice interface
3. Override its afterThrowing method. Cross cutting code is written here.
4. Get a proxy
5. Make a method call
6. Throws Advice can take any of the following forms:

public void afterThrowing(Exception ex)

public void afterThrowing(Method method,Object[] args,Object target,Exception


exception)
Advanced Java
DEMO—Program on Advices
Advanced Java
Topic 3—Configuring AOP in Java Application using AspectJ Approach
AspectJ Based AOP

There are two ways to use Spring AOP AspectJ implementation:

1. By annotation

2. By XML configuration

AspectJ jar files (aspectjrt.jar, aspectjweaver.jar, aspectj.jar, aopalliance.jar) can be


downloaded from https://eclipse.org/aspectj/downloads.php
Annotation Based AOP

1. @Before declares the before advice. It is applied before calling the actual method.
2. @After declares the after advice. It is applied after calling the actual method and before returning result.
3. @Around declares the around advice. It is applied before and after calling the actual method.
4. @AfterReturning declares the after returning advice. It is applied after calling the actual method and before
returning result. But, you can get the result value in the advice.
5. @AfterThrowing declares the throws advice. It is applied if actual method throws exception.
6. The @Pointcut annotation is used to define the pointcut.
• @Pointcut("execution(public * *(..))") is applied on all the public methods.
• @Pointcut("execution(public Operation.*(..))") is applied on all the public methods of Operation class.
• @Pointcut("execution(* Operation.*(..))") is applied on all the methods of Operation class.
• @Pointcut("execution(public Employee.set*(..))") is applied on all the public setter methods of Employee
class.
• @Pointcut("execution(* Operation.*(..))")
• private void doSomething() {}
• The name of the pointcut expression is doSomething().
7. @Aspect declares the class as aspect

@Before, @After, and @Around will be covered in the scope of this lesson.
@Before

Let’s look at Perform and TrackPerformance classes. Assume that Perform class contains actual business methods.

The AspectJ Before Advice is applied before the actual business logic method USING @Before advice.

public class Perform{


public void msgone{System.out.println("msg method invoked");}
Perform class public int msgtwo(){System.out.println("m method invoked");return 2;}
public int msgthree(){System.out.println("k method invoked");return 3;}
}

@Aspect
public class TrackPerformance{
@Pointcut("execution(* Operation.*(..))")
public void k(){}//pointcut name
TrackPerformance
class @Before("k()")//applying pointcut on before advice
public void myadvice(JoinPoint jp)//it is advice (before advice)
{
System.out.println(“Before advice is called");
}
}
@Before

When object of Perform class is created, the following output is generated:

calling msg...
Before advice is called
msg() method invoked
calling m...
Before advice is called
msgone() method invoked
calling k...
Before advice is called
Msgtwo() method invoked
@After

For @After annotation, use the same Person class and TrackPerformance.
Person class is the same, but @After annotation in TrackPerformance class is used in this case.

@Aspect
public class TrackPerformance{
@Pointcut("execution(* Operation.*(..))")
public void k(){}//pointcut name
TrackPerformance @After("k()")//applying pointcut on before advice
class public void myadvice(JoinPoint jp)//it is advice (before advice)
{
System.out.println(“After advice is called");
}
}

@After("k()")//apply Pointcut on after advice


@After

When object of Person class is created, the following output is generated:

calling msg...
msgone() method invoked
After advice is called
calling m...
msgtwo() method invoked
After advice is called
calling k...
msgthree() method invoked
After advice is called
@Around

In this example, @Around annotation in TrackPerformance class is used.

@Aspect
public class TrackPerformance
{
@Pointcut("execution(* Operation.*(..))")
public void abcPointcut(){}

@Around("abcPointcut()")
public Object myadvice(ProceedingJoinPoint pjp) throws Throwable
{
System.out.println("Additional Concern Before calling actual method");
Object obj=pjp.proceed();
System.out.println("Additional Concern After calling actual method");
return obj;
}
}
@Around

When object of Person class is created, the following output is generated:

Additional Concern Before calling actual method


msgone () is invoked
Additional Concern After calling actual method
Additional Concern Before calling actual method
msgtwo() is invoked
Additional Concern After calling actual method
Additional Concern Before calling actual method
msgthree() is invoked
XML Configuration Based AOP

It uses the following XML elements to define advice:

• aop:before: It is applied before calling the actual business logic method.


• aop:after: It is applied after calling the actual business logic method.
• aop:after-returning: It is applied after calling the actual business logic method. It can be used to intercept
the return value in advice.
• aop:around: It is applied before and after calling the actual business logic method.
• aop:after-throwing: It is applied if actual business logic method throws exception.
XML Configuration Based AOP
applicationContext.xml for implementing advice

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


<beans
<aop:aspectj-autoproxy />

<bean id="opBean" class="com.javatpoint.Operation"> </bean>


<bean id="trackAspect" class="com.javatpoint.TrackOperation"></bean>

<aop:config>
<aop:aspect id="myaspect" ref="trackAspect" >
<!-- @Before -->
<aop:pointcut id="pointCutBefore" expression="execution(* Perform.*(..))" />
<aop:before method="myadvice" pointcut-ref="pointCutBefore" />
</aop:aspect>
</aop:config>

</beans>

<!-- @After -->


<aop:pointcut id="pointCutAfter" expression="execution(* Perform.*(..))" />
<aop:after method="myadvice" pointcut-ref="pointCutAfter" />
Advice vs. Aspectj

Advice Aspectj
Spring AOP is best used for application-specific
AspectJ contains friendly design-patterns.
tasks such as security, logging, transactions, etc.
This is proxy-based AOP. You can use method-
This supports all Pointcuts.
execution Pointcut only.
There is less runtime overhead than that of
There can be a little runtime overhead.
Spring AOP.
You need extra build process with AspectJ
It needs Spring jar files only. Compiler or have to setup LTW (load-time
weaving).
Key Takeaways

AOP is used in applications that have cross cutting concerns i.e. a piece of logic
or code that is written in multiple classes/layers as per the requirements.

Springs defines two types of Pointcut:


Static: It verifies whether the join point has to be advised or not. It does this once the
result is catched @reused.
Dynamic: It verifies every time as it has to decide the Join Point based on the argument
passes to method call.

Spring uses the dynamic proxy approach. A dynamic proxy class is a class that
implements a list of interfaces specified at runtime so that a method invocation
through one of the interfaces on an instance of the class will be encoded and
dispatched to another object through a uniform interface.
Quiz
QUIZ
The Beans in Spring are ________ by default.
1

a. prototype

b. singleton

c. request

d. session
QUIZ
The Beans in Spring are ________ by default.
1

a. prototype

b. singleton

c. request

d. session

The correct answer is b. singleton


The Beans in Spring are singleton by default.
Thank You
Advanced Java
Lesson 9—Spring JDBC and Transaction Management

© Simplilearn. All rights reserved.


Learning Objectives

Explain Spring JDBC/DAO (Data Access Object)

Explain how to Implement Spring JDBC in an Application

Integrate Spring with Hibernate

Explain how to create Application using Spring Hibernate Template

Describe Spring JDBC Transaction Management


Advanced Java
Topic 1—Spring JDBC /DAO (Data Access Object)
Spring JDBC /DAO (Data Access Object)

• It is used to build Data Access Layer of enterprise application.

• It is a mechanism to connect to the database and execute SQL queries.

• The database-related logic has to placed in separate classes, called DAO classes.
JDBC vs. Spring JDBC
Difference based on JDBC Spring JDBC
Transaction Management Logic:
(enable or disable transactions
It doesn’t support Spring JDBC supports
declaratively)

Distribution based Transaction It doesn’t support Spring JDBC supports


Management
Annotation based transaction It doesn’t support Spring JDBC supports
management
Spring provides
Connection, Statement, and
Resource Allocating Logic org.springframework.jdbcTemplate
PreparedStatement have to be allocated
object. It abstracts the Database
explicitly by the developer in JDBC.
Resource Allocation Logic.
Spring provides
Resource Releasing Logic In JDBC, developer explicitly writes the
org.springframework.jdbc.core.jdbcTe
logic to release the database resources.
mplate object.
JDBC throws java.sql.SQLException. There Spring provides Fine Grind Exception
Exception Handling
won’t be specific exceptions for specific Handling mechanism to deal with
problems. Database.
Spring JDBC Architecture

DAO Classes Spring JDBC Framework

JDBC API
Advantage of Spring JDBC API

• It provides the capability to establish the connection and interact with database
• It simplifies the development of JDBC, Hibernate, JPA ,and JDO
• It provides multiple templates to interact with DB:

1. JdbcTemplate
2. HibernateTemplate
3. JdoTemplate
4. JpaTemplate
Terminologies of Spring JDBC API
CONNECTION POOLING

When a connection is opened and closed (when required) in an application, object utilization becomes
difficult and the cost of implementation increases. In such cases, connection pooling is used.

It is a mechanism of pre-creating a group of database connections and keeping them in cache memory for
use and reuse. It provides high performance and efficient resource management.
Terminologies of Spring JDBC API
java.sql.DataSource

It is an interface that is an object-oriented representation of connection pooling. It a connection factory for


Java application. It is an alternative for DriverManager and provides Database connections to the Java
application.

Its implementation classes are provided by the following connection pooling mechanisms:

1. >Apache BasicDatasource
2. >Spring DriverManagerDatasource
3. >C3p0ComboPoolDatasource
Spring JDBC Template

Spring JDBC provides a class called “JdbcTemplate” to handle the common logic.

JdbcTemplate is the abstraction of JDBC technology.

Methods provided by JdbcTemplate

1. For insert(), update(), and delete() methods of JDBC, Spring JdbcTemplate provides update()
method

2. For findByAccno(), findByBalance(), findAll(), rowCount() methods of JDBC, Spring Template


provides query(), queryForInt(), queryObject(), queryForMap(), and queryForList()

3. To handle batch updates, JdbcTemplate has convenient methods


Spring JDBC Template Methods

public int update (String query) public int update (String query)
public int update (String query) inserts, updates, and deletes records using
PreparedStatement using given arguments
public void execute (String query) executes DDL query
public T execute (String sql, executes the query by using PreparedStatement callback
PreparedStatementCallback action)

public T query (String sql, fetches records using ResultSetExtractor


ResultSetExtractorrse)
public List query (String sql, RowMapper fetches records using RowMapper
rse)
Advanced Java
Topic 2—Spring JDBC Implementation in an Application
Implementing Spring JDBC in an Application

1. Create database and table in the database


2. Create Java project in eclipse
3. Create Spring Bean class (POJO class)
4. Create a DAO class
5. Configure DataSource and Spring Bean spring configuration XML file
6. Create Spring container either by XmlBeanFactory or ApplicationContext
Implementing Spring JDBC in an Application
Create database and CREATE DATABASE AND TABLE IN THE DATABASE
table in the database

Create Java project in Syntax to create database: create database databasename;


eclipse
Syntax to create table:
Create Spring Bean
class (POJO class) CREATE TABLE table_name (
column1 datatype,
column2 datatype,
Create a DAO class column3 datatype,
....
);
Configure DataSource
and Spring Bean
spring configuration
XML file

Create Spring
container either by
XmlBeanFactory or
ApplicationContext
Implementing Spring JDBC in an Application
Create database and CREATE JAVA PROJECT IN ECLIPSE
table in the database

Create Java project in


eclipse

Create Spring Bean


class (POJO class) We have already discussed the steps to create Java project in eclipse in previous
lessons. Please refer to them.
Create a DAO class

Configure DataSource
and Spring Bean
spring configuration
XML file

Create Spring
container either by
XmlBeanFactory or
ApplicationContext
Implementing Spring JDBC in an Application
Create database and CREATE SPRING BEAN CLASS (POJO CLASS)
table in the database

Consider a user class that has three member variables: id, name, and salary.
Create Java project in
eclipse
public class User {
private int id;
Create Spring Bean
private String name;
class (POJO class)
private float salary;
//no-arg and parameterized constructors
Create a DAO class //getters and setters
}

Configure DataSource
and Spring Bean
spring configuration
XML file

Create Spring
container either by
XmlBeanFactory or
ApplicationContext
Implementing Spring JDBC in an Application
Create database and CREATE A DAO CLASS
table in the database
public class UserDao {
private JdbcTemplate jdbcTemplate;
Create Java project in
eclipse public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
Create Spring Bean
class (POJO class) public int saveUser(User e){
String query="insert into user values(
'"+e.getId()+"','"+e.getName()+"','"+e.getSalary()+"')";
Create a DAO class return jdbcTemplate.update(query);
}
public int updateUser(User e){
Configure DataSource String query="update user set
and Spring Bean
name='"+e.getName()+"',salary='"+e.getSalary()+"' where id='"+e.getId()+"' ";
spring configuration
XML file return jdbcTemplate.update(query);
}
Create Spring
public int deleteUser(User e){
container either by String query="delete from user where id='"+e.getId()+"' ";
XmlBeanFactory or return jdbcTemplate.update(query);
ApplicationContext }
Implementing Spring JDBC in an Application
Create database and CONFIGURE DATASOURCE AND SPRING BEAN SPRING CONFIGURATION XML FILE
table in the database

Create Java project in JDBC driver can be used to establish connectivity to the database during development or basic
eclipse unit or integration testing.

Spring has two data source classes:


Create Spring Bean
class (POJO class)
1. DriverManagerDataSource: Returns a new connection every time a connection is required

2. SingleConnectionDataSource: Returns the same connection every time a connection is


Create a DAO class
required

Configure DataSource
and Spring Bean
spring configuration
XML file

Create Spring
container either by
XmlBeanFactory or
ApplicationContext
Implementing Spring JDBC in an Application
Create database and CONFIGURE DATASOURCE AND SPRING BEAN SPRING CONFIGURATION XML FILE
table in the database

Create Java project in <bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">


eclipse
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql:3306//localhost/databasename" />
<property name="username" value="username" />
Create Spring Bean
class (POJO class)
<property name="password" value="password" />
</bean>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">


Create a DAO class
<property name="dataSource" ref="ds"></property>
</bean>
Configure DataSource
and Spring Bean <bean id="edao" class="UserDao">
spring configuration <property name="jdbcTemplate" ref="jdbcTemplate"></property>
XML file </bean>

Create Spring
container either by Configure DriverManagerDataSource, JdbcTemplate, and UserDAO class in
XmlBeanFactory or applicationContext.xml file.
ApplicationContext
Implementing Spring JDBC in an Application
Create database and CREATE SPRING CONTAINER EITHER BY XmlBeanFactory OR ApplicationContext
table in the database

Create Java project in To run the application, a Spring container based on ApplicationContext is used:
eclipse

public class Test {


Create Spring Bean
class (POJO class) public static void main(String[] args) {
ApplicationContext ctx=new
ClassPathXmlApplicationContext("applicationContext.xml");
Create a DAO class
UserDao dao=(UserDao)ctx.getBean("edao");
int status=dao.saveUser(new User(101,"John",350000));
Configure DataSource
and Spring Bean
System.out.println(status);
spring configuration
XML file

Create Spring }
container either by
XmlBeanFactory or
ApplicationContext
Advanced Java
Topic 3—Integrating Spring with Hibernate
Why Integrate Spring with Hibernate?
Spring Framework provides integration with Hibernate, Toplink, Ibatis, and JPA.

Reasons to integrate Spring with Hibernate:

• In large applications, this integration makes the maintenance very easy.


• When integrated, caching and other performance tuning is handled automatically.
• Database can be changed easily without affecting the application code.
• Integrating hibernate application with spring avoids creating the hibernate.cfg.xml file. All information can be
contained in the applicationContext.xml file.
Integrating Spring with Hibernate

1. Configure application.xml.
2. Configure session factory using the class AnnotationSessionFactoryBean.
3. Define HibernateTemplate by passing session factory.
4. For the database transaction, define HibernateTransactionManager. Using the transaction manager,
configure AOP.
HibernateTemplate Class

HibernateTemplate is a helper class that simplifies Hibernate data access code.

It automatically converts HibernateExceptions into DataAccessExceptions by following


the org.springframework.dao exception hierarchy.

Structure of HibernateTemplate class:

org.springframework.orm.hibernate3
public class HibernateTemplate
extends HibernateAccessor
implements HibernateOperations
Methods of HibernateTemplate Class

Method Description
void persist(Object entity) Persists the given object.
Serializable save(Object entity) Persists the given object and returns id.
Persists or updates the given object. If id is found, it
void saveOrUpdate(Object entity)
updates the record; otherwise, it saves the record.
void update(Object entity) Updates the given object
void delete(Object entity) Deletes the given object on the basis of id.
Object get(Class entityClass, Serializable id) Returns the persistent object on the basis of given id.
Object load(Class entityClass, Serializable id) Returns the persistent object on the basis of given id.
List loadAll(Class entityClass) Returns all the persistent objects.
Advanced Java
Topic 4—Creating Application using Spring Hibernate Template
Creating Application using Spring Hibernate Template

1. Create database.
2. Create Java project in eclipse.
3. Create User.java file. It is the persistent class.
4. Create UserDao.java file. It is the DAO class that uses HibernateTemplate.
5. Create applicationContext.xml file. It contains information of DataSource, SessionFactory, etc.
6. Create Test.Java file. It calls methods of UserDao class.
Creating Application using Spring Hibernate Template
CREATE DATABASE

Create database

Syntax to create database: create database databasename;


Create Java project in
eclipse

Create User.java file

Create UserDao.java
file

Create
applicationContext.x
ml file

Create Test.Java file


Creating Application using Spring Hibernate Template
CREATE JAVA PROJECT IN ECLIPSE

Create database

Create Java project in


eclipse

We have already discussed the steps to create Java project in eclipse in previous
Create User.java file
lessons. Please refer to them.
Create UserDao.java
file

Create
applicationContext.x
ml file

Create Test.Java file


Creating Application using Spring Hibernate Template
CREATE User.java FILE

User.java is an annotated POJO that represents User instance.


Create database

In the User class, there is an ID and Name of user. @Id makes column the primarykey,
Create Java project in
eclipse @Entity
public class User implements Serializable {
Create User.java file private static final long serialVersionUID = 1L;
@Id
private int id;
Create UserDao.java
file private String name;
// constructor
Create // public setter and getter methods
applicationContext.x }
ml file

Create Test.Java file


Creating Application using Spring Hibernate Template
CREATE UserDao.java FILE

This method performs the task of saving data in Database.


Create database
public class PageDao {
private HibernateTemplate hibernateTemplate;
Create Java project in
eclipse public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
Create User.java file
public void persist(){
Create UserDao.java User u1= new User(1,"Ankita");
file hibernateTemplate.save(u1);

Create User u2= new User(2,"Renu");


applicationContext.x hibernateTemplate.save(u2);
ml file }
}
Create Test.Java file
In this example, MySQl database is used. The instance of HibernateTemplate is fetched by
spring injection and saved to database using HibernateTemplate.
Inside persist method, there are two User Objects.
Creating Application using Spring Hibernate Template
CREATE applicationContext.xml FILE

application.xml contains all the declarations of DAOs and other transactional configurations.
Create database To inject HibernateTemplate into DAO classes, a bean
org.springframework.orm.hibernate3.HibernateTemplate has been created.

Create Java project in <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">


eclipse <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/database"></property>
<property name="username" value="username"></property>
Create User.java file <property name="password" value="password"></property>
</bean>
<bean id="mysessionFactory"
Create UserDao.java class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
file <property name="dataSource" ref="dataSource"></property>
<property name="mappingResources">
Create <list>
applicationContext.x <value>employee.hbm.xml</value>
ml file </list>
</property>
<property name="hibernateProperties">
Create Test.Java file <props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
Creating Application using Spring Hibernate Template
CREATE applicationContext.xml FILE

Create database
Code continuation

</property>
Create Java project in
</bean>
eclipse
<bean id="template"
class="org.springframework.orm.hibernate3.HibernateTemplate">
Create User.java file <property name="sessionFactory" ref="mysessionFactory"></property>
</bean>
<bean id="d" class="com.javatpoint.EmployeeDao">
Create UserDao.java <property name="template" ref="template"></property>
file </bean>

</beans>
Create
applicationContext.x
ml file

Create Test.Java file


Creating Application using Spring Hibernate Template
CREATE Test.Java FILE

Find the class SpringDemo.java. SpringDemo calls the persist method from the PageDao to
Create database save the data in database. Run the command.

Create Java project in public class SpringDemo {


eclipse
public static void main(String... args) {
ApplicationContext context = new
Create User.java file ClassPathXmlApplicationContext("application.xml");
PageDao pd=(PageDao) context.getBean("pageDao");
pd.persist();
Create UserDao.java }
file }
Create
applicationContext.x Output:
ml file
Hibernate: insert into User (name, id) values (?, ?)
Create Test.Java file Hibernate: insert into User (name, id) values (?, ?)
Advanced Java
Topic 5—Spring JDBC Transaction Management
Spring JDBC Transaction Management

Spring provides extensive support for transaction management. This helps developers to focus on
business logic rather than worrying about the integrity of data in case of any system failures.

Spring provides an abstract layer on top of different transaction management APIs.

It helps application developers to focus on the business problem, without having to know much
about the underlying transaction management APIs.
ACID

The concept of transactions can be described using the following four key properties, known as ACID.

Atomicity requires that each transaction be ‘all or nothing’. If one part of the transaction
A fails, then the entire transaction fails, and the database state is left unchanged.

D
ACID

The concept of transactions can be described using the following four key properties, known as ACID.

Atomicity requires that each transaction be ‘all or nothing’. If one part of the transaction
A fails, then the entire transaction fails, and the database state is left unchanged.

Consistency property ensures that any transaction will bring the database from one
C valid state to another.

D
ACID

The concept of transactions can be described using the following four key properties, known as ACID.

Atomicity requires that each transaction be ‘all or nothing’. If one part of the transaction
A fails, then the entire transaction fails, and the database state is left unchanged.

Consistency property ensures that any transaction will bring the database from one
C valid state to another.

I Isolation property ensures that the concurrent execution of transactions results in a system state
that would be obtained if transactions were executed serially, that is, one after the other.

D
ACID

The concept of transactions can be described using the following four key properties, known as ACID.

Atomicity requires that each transaction be ‘all or nothing’. If one part of the transaction
A fails, then the entire transaction fails, and the database state is left unchanged.

Consistency property ensures that any transaction will bring the database from one
C valid state to another.

I Isolation property ensures that the concurrent execution of transactions result in a system state
that would be obtained if transactions were executed serially, that is, one after the other.

D Durability property ensures that once a transaction has been committed, it will remain so, even in
the event of power loss, crashes, or errors.
Transaction Management Interface

PlatformTransactionManager is a general interface for all Spring transaction managers:

public interface PlatformTransactionManager {


TransactionStatus getTransaction(TransactionDefinition definition);
throws TransactionException;

void commit(TransactionStatus status) throws TransactionException;


void rollback(TransactionStatus status) throws TransactionException;
}

Spring has several built-in implementations of this interface that can be used with different transaction
management APIs like DataSourceTransactionManager, HibernateTransactionManager, and
JpaTransactionManager
Methods of PlatformTransactionManage

Method Description
TransactionStatus This method returns a currently active transaction or
getTransaction(TransactionDefinition creates a new one, according to the specified
definition) propagation behavior.
This method commits the given transaction, with
void commit(TransactionStatus status)
regard to its status.
This method performs a rollback of the given
void rollback(TransactionStatus status)
transaction.
TransactionDefinition Interface
TransactionDefinition is the core interface of the transaction support in Spring, and it is defined as follows:

public interface TransactionDefinition


{
int getPropagationBehavior();
int getIsolationLevel();
String getName();
int getTimeout();
boolean isReadOnly();
}
Methods of TransactionDefinition

Method Description
This method returns the propagation behavior. Spring offers
int getPropagationBehavior()
all of the transaction propagation options offered by EJB CMT.
This method returns the degree to which this transaction is
int getIsolationLevel()
isolated from the work of other transactions.
String getName() This method returns the name of the transaction.
This method returns the time (in seconds) in which the
int getTimeout()
transaction must complete.
boolean isReadOnly() This method queries whether the transaction is read only.
TransactionStatus Interface

TransactionStatus interface provides a simple way for transactional code to control transaction execution
and query transaction status.

public interface TransactionStatus extends SavepointManager {


boolean isNewTransaction();
boolean hasSavepoint();
void setRollbackOnly();
boolean isRollbackOnly();
boolean isCompleted();
}
Methods of TransactionStatus

Method Description
This method returns whether this transaction internally carries
boolean hasSavepoint() a savepoint, i.e., has been created as nested transaction based
on a savepoint.
This method returns whether this transaction is completed,
boolean isCompleted()
i.e., whether it has already been committed or rolled back.
This method returns true in case the present transaction is
boolean isNewTransaction()
new.
This method returns whether the transaction has been
boolean isRollbackOnly()
marked as rollback-only.
void setRollbackOnly() This method sets the transaction as rollback-only.
Types of Transaction Management

Spring supports two types of transaction management:

1. Programmatic transaction management


2. Declarative transaction management
Types of Transaction Management
PROGRAMMATIC TRANSACTION MANAGEMENT

• It manages transactions with the help of programming.


Programmatic • It uses PlatformTransactionManager directly to implement the programmatic approach, to
transaction implement transactions, and to create instance of TransactionDefinition with the appropriate
management transaction attributes.

Declarative • Once the TransactionDefinition is created, you can start your transaction by
transaction calling getTransaction() method, which returns an instance of TransactionStatus.
management
• The TransactionStatus objects helps in tracking the current status of the transaction.

• Programmatic Transaction Management uses commit() method


of PlatformTransactionManager to commit the transaction.
Types of Transaction Management
DECLARATIVE TRANSACTION MANAGEMENT

• Separates transaction management from the business code.


Programmatic
transaction • Allows you to manage the transaction with the help of configuration instead of hard coding
management in your source code.

Declarative • Uses annotations or XML-based configurations to manage the transactions.


transaction
management • Uses <tx:advice /> tag. This creates a transaction-handling advice and defines a Pointcut
that matches all methods needed for the transaction at the same time.
Key Takeaways

Spring JDBC is used to build Data Access Layer of enterprise application. It is a


mechanism to connect to the database and execute SQL queries. The database-
related logic has to placed in separate classes called DAO classes.

Connection pooling is a mechanism of pre-creating a group of database


connections and keeping them in cache memory for use and reuse. It provides high
performance and efficient resource management.

Spring supports two types of transaction management: Programmatic transaction


management and Declarative transaction management
Quiz
Thank You
Advanced Java
Lesson 10—Spring MVC

© Simplilearn. All rights reserved.


Learning Objectives

Explain Spring MVC architecture and components

List the steps to write Spring MVC program in Eclipse


Advanced Java
Topic 1—Spring MVC Architecture and Components
Why Spring MVC ?

Problems in Enterprise Application development with Servlet and JSP Technology

1. Servlet and code are not reusable


2. Web designing tools can’t be used in case of servlet
3. Parallel development is not possible

Solution

To solve the above problems, Sun microsystem introduced two design patterns for developing
enterprise applications:

1. Model 1 (Page Centric Model)


2. Model 2 (MVC)
Model 1: Page Centric Model
ARCHITECTURE

request 1

JSP
response
4
Enterprise
Browser 2 Server/Data
Source
3
JavaBean

Application Server
Model 1: Page Centric Model
WORKFLOW

1. Request is sent by the browser and received by JSP.


2. Java bean object is created and business methods are called. If required, it communicates with
the database to get the required data
3. JSP displays the processed data to the end user
Model 1: Page Centric Model
LIMITATIONS

• There is no clear separation of responsibilities


• JSP acts as both controller and view
• Business logic is separated using Java Bean
Model 2: MVC Model
ARCHITECTURE

request 1

Controller (Servlet)
response 2
5
Enterprise
browser 3 Model Server / Data
Java Bean Source

View (JSP)
4

Application Server
Model 2: MVC Model
WORKFLOW

1. Controller or Servlet receives request from browser and captures the input
2. Controller invokes the business method of the model or Java bean
3. Model connects with the database and gets business data
4. Model sends response to controller (Keeps the process data in heap memory request, session, and ServletContext)
5. Controller switches the control to appropriate view of the application
Model 2: MVC Model
LIMITATIONS

• Clear separation of responsibilities


• Code reusability
• Single point entry for the application
• Support for multiple view technologies
Advantages of Spring MVC

• Spring MVC is used to develop the web application that uses MVC design pattern

• Spring MVC is meant to make web application development faster, cost-effective, and flexible
Spring MVC Architecture

HandlerMapping

2. Request

3. Controller

5. Calls Business
1. Request Method Dispatcher
Dispatcher
Dispatcher 4. handlerRequest (req, res) Servlet Servlet
Service
Servlet Controller
11. ModelAndView 10. Response
16. Response

6. Calls Dao method


9. Response
15. Response 14. Model 12. ViewName
7. Contact
Database
Dispatcher Dispatcher
Servlet
View 13. view ViewResolver Servlet
DAO
8. Response
Spring MVC Workflow

1. Client requests a resource in the Web Application


2. The Spring Front Controller (DispatcherServlet) requests the HandlerMapping to identify the particular
controller for the given URL
3. HandlerMapping identifies the controller and sends to the DispatcherServlet
4. DispatcherServlet calls handleRequest (req, res) method and passes these two objects to that controller
5. Controller calls the business method
6. Service class calls the DAO method for business data
7. DAO interacts with the database to get the data
8. Database shares the result
9. DAO returns this result data to service
10. DAO data is processed according to business requirement and returns to Controller
11. Controller returns ModelAndView object back to front Controller
12. Dispatcher resolves actual View by consulting the View Resolver object
13. ViewResolver renders View to the Dispatcher
14. DispatcherServlet consults the View to the DispatcherServlet
15. View executes and returns HTML to the DispatcherServlet
16. DispatcherServlet sends output to the Browser
Components of Spring MVC

1. DispatcherServlet (org.springframework.web.servlet)
2. HandlerMapping (org.springframework.web.servlet)
3. Controller
4. ModeAndView (org.springframework.web.servlet)
5. ViewResolver
Components of Spring MVC
DispatcherServlet

1. It is given by org.springframework.web.DispatcherServlet
DispatcherServlet
2. It follows FrontController Design Pattern
3. Whatever URL comes from the Client, Servlet intercepts the Client Request before passing the
Request object to the Controller
HandlerMapping
4. In web configuration file, write <servlet-mapping> in such a way that Dispatcher Servlet is invoked
for ClientRequest
Controller
<servet>
<servlet-name> front-controller</servlet-name>
ModelAndView
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
</servlet>
ViewResolver
<servlet-mapping>
<servlet-name> front-controller </servlet-name>
<url-pattern>*.extensionname</url-pattern>
</servlet-mapping>

Definition given in the web.xml to invoke Spring’s Dispatcher


Components of Spring MVC
HandlerMapping

• It is an Interface implemented by objects to define mapping between requests and


DispatcherServlet
handler objects.

HandlerMapping • When a request is made to Spring’s dispatcher servlet, it hands over the request to
handler mapping.

Controller • Handler mapping inspects the request and identifies the appropriate handler execution
chain and delivers it to dispatcher servlet.
ModelAndView

ViewResolver
Components of Spring MVC
HandlerMapping: Example

Hander mapping provided by Spring’s MVC module can be implemented in many ways.
Lets take a example:
DispatcherServlet
BeanNameUrlHandlerMapping: It is the default handler mapping class, that maps the URL
HandlerMapping request to the names of the beans.
<bean…>
<bean class=“org.springframework.web.servlet.handler.
Controller BeanNameUrlHandlerMapping”/>
<bean name=“/welcome.htm” class=“WelcomeController”/>
ModelAndView
<bean name=“/streetName.htm” class=“StreetNameController”/>
<bean name=“/process*.htm” class=“ProcessController”/>
If URL pattern:
ViewResolver

• /welcome.htm is requested; DispatcherServlet will forward the request to the “WelcomeController.”


• /streetName.htm is requested; DispatcherServlet will forward the request to the
“StreetNameController.”
• /processCreditCard.htm or /process{anything}.htm is requested; DispatcherServlet will forward the
request to the “ProcessController.”
Components of Spring MVC
Controller

• Controllers are components that are called by the Dispatcher Servlet for any kind of Business
DispatcherServlet
logic.
• All controllers implements Controller interface.
HandlerMapping

Types of Controllers:
Controller
1. AbstractController
2. MultiActionController
ModelAndView
3. AbstractwizardFormController

ViewResolver
There are components called ViewResolver. Their job is to provide mapping between the Logical
View Name and the actual Physical Location of the View Resource.
Components of Spring MVC
ModelAndView

• It is represented by the class org.springframework.web.servlet.ModelAndView and is returned by


DispatcherServlet
the Controller object back to the DispatcherServlet
• This class is just a CONTAINER CLASS FOR HOLDING THE mODEL AND THE vIEW information
HandlerMapping
• The Model object represents some piece of information that can be used by the View to display
the information. These give abstraction in the Spring framework
• Any kind of View Technology (org.springframework.web.servlet.View) can be plugged into the
Controller Framework
Excel, Jasper Reports, Pdf, Xslt, freeMarker, Html, Tiles are supported frameworks.

ModelAndView

Example:
ViewResolver
ModelAndView mv=new ModelAndView(“successView”, “greetingMsg”, “greetingMessage);
Components of Spring MVC
ModelAndView

It is an Interface implemented by objects to resolve views using name.Spring’s MVC module.


DispatcherServlet
It encapsulates the model object and the view object in a single entity, which is represented by the
object of class ModelAndView.
HandlerMapping

To resolve the view object, DispatcherServlet ViewResolver is used.


Controller

ModelAndView

ViewResolver

All view resolvers implement the interface org.springframework.web.servlet.ViewResolver.


Components of Spring MVC
ModelAndView: Types

InternalResourceViewResolver
DispatcherServlet
It resolves the logical name of the view to an internal resource by prefixing the logical view name
with the resource path and suffixing it with the extension.
HandlerMapping

BeanNameViewResolver
Controller
It resolves the logical name of the view to the bean name, which will render the output to the user.
The bean should be defined in the Spring app context file.
ModelAndView
XMLFileViewResolver
ViewResolver
This view resolver is the same as BeanNameViewResolver. The only difference is that instead of
looking for the beans in Spring’s application context file, it looks for beans defined in a separate
XML file (/WEB-INF/views.xml by default).
Advanced Java
Topic 2—Spring MVC Program in Eclipse
Writing Spring MVC Program in Eclipse

1. Create dynamic web project in eclipse


2. Create 'index.jsp' (View)
3. Create HelloWorldController.java (Controller)
4. Create mvc-dispatcher-servlet.xml file. (Spring Configuration)
5. Create web.xml (Deployment Descriptor)
6. Run the project
Writing Spring MVC Program in Eclipse
Create 'index.jsp' (View)
Create dynamic web
project in eclipse
In this case, “view” is a JSP page. We can display the value “hello Spring MVC” that is stored in
the model “msg” via expression language (EL) ${msg}
Create 'index.jsp'
(View)
HelloWorldPage.jsp
Create
HelloWorldController <%@ taglib prefix="c"
.java (Controller) uri="http://java.sun.com/jsp/jstl/core"%>
Create mvc- <html>
dispatcher- <body>
servlet.xml file. <h1>Spring MVC Hello World Example</h1>
(Spring
Configuration)
<h2>${msg}</h2>
Create web.xml </body>
(Deployment
Descriptor)
</html>

Run the project We have already discussed the steps to create a web project in eclipse in the
previous lessons.
Writing Spring MVC Program in Eclipse
Create HelloWorldController.java (Controller)
Create dynamic web
project in eclipse Spring has Controllers. Here, AbstractController overrides the handleRequestInternal() method

Create 'index.jsp' public class HelloWorldController extends AbstractController{


(View)
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest
Create request,HttpServletResponse response) throws Exception {
HelloWorldController
ModelAndView model = new ModelAndView("HelloWorldPage");
.java (Controller)
model.addObject("msg", "Welcome");
Create mvc- return model;
dispatcher- }
servlet.xml file. }
(Spring
Configuration)

Create web.xml ModelAndView(“HelloWorldPage”) identifies which view should return to the user. In this
(Deployment example, HelloWorldPage.jsp will be returned.
Descriptor)
model.addObject (“msg”, “Welcome”) adds a “welcome” string into a model named “msg.” You
Run the project can later use EL ${msg} to display the “hello world” string.
Writing Spring MVC Program in Eclipse
Create mvc-dispatcher-servlet.xml file. (Spring Configuration)
Create dynamic web
project in eclipse
Declare the Spring Controller and viewResolver (mvc-dispatcher-servlet.xml).
Create 'index.jsp'
(View)
<beans xmlns="http://www.springframework.org/schema/beans"
Create xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
HelloWorldController xsi:schemaLocation="http://www.springframework.org/schema/beans
.java (Controller) http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean name="/welcome.htm"
Create mvc-
class="HelloWorldController" />
dispatcher-
servlet.xml file. <bean id="viewResolver"
(Spring class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
Configuration) <property name="prefix">
<value>/WEB-INF/pages/</value>
Create web.xml </property>
(Deployment
<property name="suffix">
Descriptor)
<value>.jsp</value>
</property>
Run the project </bean>
</beans>
Writing Spring MVC Program in Eclipse
Create mvc-dispatcher-servlet.xml file. (Spring Configuration)
Create dynamic web
project in eclipse

1. Controller declares a bean name /welcome.htm and maps it to HelloWorldController. If a URL


Create 'index.jsp'
(View)
with /welcome.htm pattern is requested, the HelloWorldController controller will handle the
request.
Create
HelloWorldController 2. viewResolver defines how Spring will look for the view template. In this case, the controller
.java (Controller) HelloWorldController will return a view named HelloWorldPage, and the viewResolver will find
Create mvc- the file with the following mechanism: prefix + view name + suffix, which is /WEB-
dispatcher- INF/pages/HelloWorldPage.jsp.
servlet.xml file.
(Spring
Configuration)

Create web.xml
(Deployment
Descriptor)

Run the project


Writing Spring MVC Program in Eclipse
Create web.xml (Deployment Descriptor)
Create dynamic web
project in eclipse
web.xml declares a DispatcherServlet servlet to act as the front-controller to handle all the web
requests that end with htm extension.
Create 'index.jsp'
(View)
web.xml
Create
<web-app >
HelloWorldController <display-name>Spring Web MVC Application</display-name>
.java (Controller) <servlet>
<servlet-name>mvc-dispatcher</servlet-name>
Create mvc- <servlet-class>
dispatcher-
org.springframework.web.servlet.DispatcherServlet
servlet.xml file.
(Spring
</servlet-class>
Configuration) <load-on-startup>1</load-on-startup>
</servlet>
Create web.xml <servlet-mapping>
(Deployment <servlet-name>mvc-dispatcher</servlet-name>
Descriptor)
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
Run the project </web-app>
Writing Spring MVC Program in Eclipse
Run the project
Create dynamic
web project in
eclipse To run application, the following URL is used:

Create 'index.jsp' http://localhost:8080/projectname/welcome.htm


(View)

Create
HelloWorldControll
er.java (Controller)

Create mvc-
dispatcher-
servlet.xml file.
(Spring
Configuration)

Create web.xml
(Deployment
Descriptor)

Run the project


Key Takeaways

Spring MVC is used to develop the web application that uses MVC design
pattern. Spring MVC is used to make web application development faster, cost-
effective, and flexible

DispatcherServlet (org.springframework.web.servlet), HandlerMapping


(org.springframework.web.servlet), Controller, ModeAndView
(org.springframework.web.servlet), and ViewResolver are the components of
spring MVC.
Quiz
Thank You
Advanced Java
Lesson 11—SOA and Web Services

© Simplilearn. All rights reserved.


Learning Objectives

Explain SOA Architecture

Explain Web Services

List the steps to create a SOAP based Web Service

List the steps to create a RESTful Web Service


SOA and Web Services
Topic 1—Basics of SOA and SOA Architecture

• Phases of Software Evolution


• What is SOA?
• Advantages of SOA
• SOA Architecture
• Implementing SOA: Example
• SOA Service Description
• Web Service as Implementation of SOA
Phases of Software Evolution

The software evolution has distinct phases. These layers are built up one by one over many years.

Software evolution begins with understanding the concept of 1 and 0 (bits) that gives rise to
machine language. This is followed by assembly, procedure oriented, object oriented, component
oriented, and service oriented languages.

Structured
Oriented/Procedure Object Component Service
Oriented Oriented Oriented Oriented

https://www.researchgate.net/publication/215571061
Phases of Software Evolution
STRUCTURE ORIENTED/PROCEDURE ORIENTED

Structure A procedural language is a type of computer programming language that specifies a series of
Oriented/Procedure
well-structured steps and procedures within its programming context to compose a program.
Oriented
It contains a systematic order of statements, functions, and commands to complete a
Object
computational task or program.
Oriented

Component
Oriented

Service
Oriented
Phases of Software Evolution
STRUCTURED ORIENTED/PROCEDURE ORIENTED LANGUAGE: LIMITATIONS

Structured
Oriented/Procedure • Structure/procedure oriented language is unable to model real world problems.
Oriented
• It uses global data concept and is thus accessed by all the functions.
Object
Oriented • It is difficult to maintain because the line of code is high.

Component
Oriented

Service
Oriented
Phases of Software Evolution
OBJECT ORIENTED

Structured
Oriented/Procedure It refers to a type of computer programming (software design) in which the
Oriented programmers define the data type of a data structure and the types of operations (functions)
that can be applied to the data structure.
Object
Oriented

Component
Oriented

Service
Oriented
Phases of Software Evolution
OBJECT ORIENTED: LIMITATIONS

Structured Although it offers better implementation, data security, code reusability, and flexibility, It is
Oriented/Procedure
difficult to manage complex applications.
Oriented

Object
Oriented

Component
Oriented

Service
Oriented
Phases of Software Evolution
COMPONENT ORIENTED

Structured Component-based software engineering (CBSE), also called component-based development


Oriented/Procedure
(CBD), is a branch of software engineering that emphasizes the separation of concerns with
Oriented
respect to the wide-ranging functionality available throughout a given software system.
Object
Oriented A component modifies complexity through the use of a component container and its services.

Component
Oriented

Service
Oriented
Phases of Software Evolution
COMPONENT ORIENTED: LIMITATIONS

Structured
Component development is a complex task and comes with the following limitations:
Oriented/Procedure
Oriented
• Component maintenance costs
Object
• Reliability and sensitivity to changes
Oriented
• Unsatisfied requirements
Component
Oriented

Service
Oriented
Phases of Software Evolution
SERVICE ORIENTED

Structured Web Services are self-describing services that will perform well-defined tasks and can be accessed
Oriented/Procedure through the Web.
Oriented
Service Oriented approach follows an architecture, called SOA (Service Oriented Architecture), that
Object focuses on building systems through the use of different Web Services and integrating them to
Oriented make up the whole system.

Component
Oriented

Service
Oriented
What is SOA?
AN ARCHITECTURAL SOLUTION

SOA is the architectural solution for integrating diverse systems by providing an architectural style that
promotes loose coupling reuse.

It is a programming model or paradigm where web service and contracts becomes a dominant design for
interoperability
SOA Architecture

Processes
Discovery, Aggregation, Choreography…

Base Technologies: XML, DTD, Schema


Base Technologies: XML, DTD, Schema
Descriptions
Web Services Descriptions (WSDL)

Messages

Management
Security

SOAP Extensions
Reliability, Correlation, Transactions….

SOAP

Communications
HTTP, SMTP, FTP, JMS, IIOP
What Is SOA?
A COLLECTION OF SERVICES

SOA is a collection of Services.

The following diagram shows how an Online Shopping website selling gadgets is involved with different
services like Ordering, Tracking, and Checkout to give service to its customers.

Ordering
Service

Tracking
Service

Customers
Online shopping website Checkout
selling gadget Service
What Is SOA?
ESTABLISHING COMMUNICATION

It helps in establishing communication between all services (applications).

SOA
Service Consumer Service Provider
SOA is a solution for making
two software communicate to
each other
Advantages of SOA

SOA Services Uses


Service • Improved information flow
• Ability to expose internal functionality
• Organizational flexibility
Service Re-use Lower software development and management costs
Messaging Configuration flexibility
Message Monitoring • Business intelligence
• Performance measurement
• Security attack detection
Message Control • Application of management policy
• Application of security policy
Message Transformation Data translation
Message Security Data confidentiality and integrity
Complex Event Processing • Simplification of software structure
• Ability to adapt quickly to different external environments
• Improved manageability and security
Implementing SOA: Example
The Corporate Network

Business
Enterprise Service Bus Process
Software Development Modeling
Workflow Presentation Service
Adapter Programming Tools
Engine App Servers SOA
In House Portal Services
DBMS Repository
apps Device Services
Modelling Tools
Messaging Services
SOA Testing Tools
Registry SOA App
Adapter
Testing
Packaged
Data Service
apps Service
Broker Data Federation SOA
ETL and Metadata
Data Archiving Governance
Adapter Infrastructure Service
Other SOA
Supervisor Message management
apps System management
Security management
Provisioning
Identity and Authentication
SOA Service Description

Directory

Service
Description

Service Service
Consumer Provider

Consumer queries the directory to


locate a service and communicate
with the provider
SOA Service Description

Directory

Service
Description

Service Service
Consumer Provider

Service Provider publishes


its service description and
directory
Web Service as Implementation of SOA

Implementation
Service Consumer Service Provider Web Service

Web Service is an
implementation of
SOA
SOA and Web Services
Topic 2—Web Services

• Why Use Web Services?


• What Are Web Services?
• Web Services Operational Model
• Web Services: Example
• Types of Web Services
Why Use Web Services?

1. Web applications enable interaction between an end user and a website. Web services are service-
oriented and enable application-to-application communication over the Internet and easy
accessibility to heterogeneous applications and devices.

2. Web services can be invoked through XML-based RPC mechanisms across firewalls.

3. Web services provide a cross-platform, cross-language solution based on XML messaging.

4. Web services facilitate ease of application integration using a lightweight infrastructure without
affecting scalability.

5. Web services enable interoperability among heterogeneous applications.


What Are Web Services?

• Web services are based on the concept of service-oriented architecture (SOA).

• According to Gartner research (June 15, 2001), “Web services are loosely coupled software
components delivered over Internet standard technologies.”

• Web services are self-describing and modular business applications that expose the business logic as
services over the Internet. This is done through programmable interfaces and Internet protocols to
provide ways to find, subscribe, and invoke those services.
Web Services Operational Model
Web Service operational model can be conceptualized as a simple operational model that has a lot in
common with a standard communication model:

Service
Broker

Service Service
Requestor Provider
Invoke Service

Operations are conceived as involving three distinct roles and relationships that define the Web
Services provider and users.
Web Services: Example

Consider the following scenario:

1. A Travel service provider deploys its Web services by exposing the business applications obtained from
different travel businesses like airlines, car-rental, hotel accommodation, credit card payment, and so forth.

2. The service provider registers its business services with descriptions using a public or private registry. The
registry stores the information about the services exposed by the service provider.

3. The customer discovers the Web services using a search engine or by locating it directly from the registry
and then invokes the Web services to perform travel reservations and other functions over the Internet
using any platform or device.

4. In the case of large-scale organizations, the business applications consume these Web services to provide
travel services to their own employees through the corporate intranet.
Web Services: Example

Travel Services Registry Airline


Wireless
Reservation
Device
System

Find Register
Services Services Rental car
Desktop Reservation
System
Invoke Services

Hotel
Service Requestor Travel Reservation Reservation
PDA
Services Provider System

Map and
Weather
Automobile Information
System

Credit card
Organization Payment
System
Types of Web Services

Web services are based on the following key standards:

1. Extensible Markup Language (XML) based messaging

2. Universal Description, Discovery, and Integration (UDDI)

3. Web Services Description Language (WSDL)

4. Simple Object Access Protocol (SOAP)


Types of Web Services
EXTENSIBLE MARKUP LANGUAGE (XML)

These technologies are interoperable at a core level as they use XML as data
Extensible representation layer for all web service protocols and technologies that are created
Markup
Language (XML) Process 1 Process 2
Universal
Description,
Discovery and
Integration
(UDDI)
XML Generator/ XML Generator/
Web Services Interpreter Interpreter
Description
Language (WSDL)
Simple Object
Access Protocol
(SOAP)
Communication Communication
Manager Manager
Types of Web Services
WEB SERVICES WITH XML

Extensible
Directory
Markup
Language (XML)
Service
Universal Description
Description,
Discovery and
Integration
(UDDI)
Web Services
Description XML
Service Service
Language (WSDL) Consumer Provider
Consumer formulates its message to
Simple Object the provider using tag-based
Access Protocol language called XML.
(SOAP)
Types of Web Services
UNIVERSAL DESCRIPTION, DISCOVERY AND INTEGRATION (UDDI)

UDDI provides a world-wide registry of web services for advertisements, discovery, and
Extensible integration purposes.
Markup
Language (XML) UDDI could be dynamic or static; Business Analysts and technologists could use UDDI to
search for available web services.
Universal
Description,
The UDDI Business Registry provides a place for a company to programmatically describe its
Discovery and
services and business processes and its preferred methods for conducting business.
Integration
(UDDI)
Web Services The directory is implicit
Web Services in web services
Description
Language (WSDL)
Simple Object
Access Protocol Any service producer
(SOAP) can also be a service
Service provider. So, the label Service
is changed to “Service”
Types of Web Services
WEB SERVICES DESCRIPTION LANGUAGE (WSDL)

Extensible WSDL describes the interface of the Web Service. It is comparable to the concept of “Remote
Markup Interface” of Java RMI or the “Interface Definition Language File (IDL)” of RPC.
Language (XML)
It standardizes how a web service represents the input and output parameters of an
Universal invocation externally, that is, the function structure, the nature of invocation (in, in/out,etc),
Description, and the service protocol binding.
Discovery and
Integration
(UDDI)
Web Services
Description
Language (WSDL)
Simple Object
Access Protocol
(SOAP)
Types of Web Services
WEB SERVICES WITH WSDL

Extensible
Markup WSDL Directory
Language (XML)
Universal Service
Description, Description
Discovery and
Integration Service description is written in a
(UDDI) special language called web service
Web Services description language (WSDL)
Description
Language (WSDL) Service Service
Simple Object Consumer Provider
Access Protocol
(SOAP)
Types of Web Services
USE OF WSDL

Extensible 2
Markup Directory
Directory
Language (XML)
Service queries
Query
Universal description response
Description, using WSDL
SOAP Messages using
Discovery and
1 WSDL
Integration
3
(UDDI)
4
Web Services XML service request based on WSDL
Description Service Service
Language (WSDL) Provider Consumer
Simple Object XML service response based on WSDL
Access Protocol
(SOAP) 5
Types of Web Services
SIMPLE OBJECT ACCESS PROTOCOL (SOAP)

Extensible SOAP is a simple XML-based protocol to let applications exchange information over HTTP.
Markup
Language (XML) It is a protocol for accessing a Web Service.

Universal
Description,
Discovery and
Integration
(UDDI)
Web Services
Description
Language (WSDL)
Simple Object
Access Protocol
(SOAP)
Types of Web Services
WHY USE SIMPLE OBJECT ACCESS PROTOCOL (SOAP)?

Extensible • It is important to have Internet communication between programs for application


Markup development.
Language (XML)
• Firewalls and proxy servers generally block traffic that creates a compatibility and security
Universal problem, even if they are used for application communication like RPC (Remote Procedure
Description, Call).
Discovery and
Integration • HTTP is supported by all Internet browsers and servers. However, SOAP was created to
(UDDI) accomplish better communication between applications.
Web Services
Description • SOAP supports different technologies and programming languages.
Language (WSDL)
Simple Object
Access Protocol
(SOAP)
Types of Web Services
SOAP ARCHITECTURE

SOAP envelope
Extensible
Markup
Language (XML) Header
Universal
Description,
Discovery and Body
Integration
(UDDI) WSDL
Web Services
Description XML or other format
Language (WSDL)
Simple Object
Access Protocol
(SOAP)
HTTP or other protocol
Types of Web Services
WEB SERVICES WITH SOAP

Extensible
Markup WSDL Directory
Language (XML)
Universal Service
Description, Description Messages are sent
Discovery and and received in a
Integration SOAP SOAP directory through
(UDDI) SOAP language
Web Services
Description
Language (WSDL) Service Service
Simple Object Consumer Provider
Access Protocol
(SOAP)
Types of Web Services
SOAP ELEMENTS

Extensible • Envelope: It identifies the XML document as a SOAP message.


Markup • Header: It is an optional element that contains header information.
Language (XML)
• Body: It contains call and response information.
Universal
Description, • Fault: It provides information about errors that occurred while processing the message.
Discovery and
Integration
(UDDI)
Web Services
Description
Language (WSDL)
Simple Object
Access Protocol
(SOAP)
Types of Web Services
SOAP ELEMENTS: ENVELOPE

Extensible • It is the root element of a SOAP message


Markup
Language (XML) • It defines the XML document as SOAP message

Universal
Description,
Discovery and
Integration
(UDDI)
Web Services
Description
Language (WSDL)
Simple Object
Access Protocol
(SOAP)

Envelope Header Body Fault


Types of Web Services
SOAP ELEMENTS: HEADER

Extensible • The optional SOAP Header element contains application-specific information (like
Markup authentication, payment, etc.) about the SOAP message.
Language (XML)
• If the Header element is present, it must be the first child element of the Envelope
Universal element.
Description,
Discovery and
Integration
(UDDI)
Web Services
Description
Language (WSDL)
Simple Object
Access Protocol All immediate child elements of the Header element must be namespace-
(SOAP) qualified.

Envelope Header Body Fault


Types of Web Services
SOAP ELEMENTS: BODY

Extensible • The required SOAP Body element contains the actual SOAP message intended for the
Markup ultimate endpoint of the message.
Language (XML)
• Immediate child elements of the SOAP Body element may be namespace-qualified.
Universal
Description, • This is the SOAP Fault element used to indicate error messages.
Discovery and
Integration
(UDDI)
Web Services
Description
Language (WSDL)
Simple Object
Access Protocol
(SOAP)

Envelope Header Body Fault


Types of Web Services
SOAP ELEMENTS: FAULT

• The optional SOAP Fault element is used to indicate error messages.


Extensible
Markup • The SOAP Fault element holds errors and status information for a SOAP message.
Language (XML)
Universal • If a Fault element is present, it must appear as a child element of the Body element. A Fault
Description, element can only appear once in a SOAP message.
Discovery and
Integration • The SOAP Fault element has the following sub elements:
(UDDI)
Web Services Sub Element Description
Description <faultcode> A code for identifying the fault
Language (WSDL)
<faultstring> A human readable explanation of the fault
Simple Object
Access Protocol <faultactor> Information about who caused the fault to happen
(SOAP) <detail> Holds application specific error information related to the Body element

Envelope Header Body Fault


SOA and Web Services
DEMO—SOAP Application
Java APIs for Web Service

There are two main APIs defined by Java for developing web service applications (since Java EE 6):

1. JAX-WS: for SOAP web services.


2. JAX-RS: for RESTful web services.
SOA and Web Services
Topic 3—Creating a SOAP based Web Service

• Axis
• Web Service in an Axis Environment
• Creating a SOAP based Web Service
Axis

Axis facilitates easy deployment and undeployment of services using XML-based Web services deployment
descriptors (WSDDs).

• It enables deploying and undeploying services and also Axis-specific resources like handlers and chains
using an administration utility ‘AdminClient’ provided as part of the Axis toolkit.

• It helps deploy a service, ensures that the AXIS CLASSPATH is set, and runs the following command:

java org.apache.axis.client.AdminClient deploy.wsdd

• It helps undeploy a service, ensures that the AXIS CLASSPATH is set, and then runs the following command:

java org.apache.axis.client.AdminClient undeploy.wsdd


Web Service in an Axis Environment

To create a Web service in an Axis environment, the following Models are used:

1. Create the service provider (server application)

2. Create the service requester (client applications)


Creating a SOAP based Web Service

1. Create a new dynamic web project and name it “SimpleSOAPExample”

2. Create a new package named “com.webservice”

3. Create a simple Java class named “HelloWorld.java” which works as Service

4. Right click project  new  web service

5. Click next

In service implementation text box, write the qualified class name of created class (HelloWorld.java),
move both above slider to maximum level (Test service and Test Client level), and click finish. You are
done. A new project named “SimpleSOAPExampleClient” will be created in your work space.

6. Click start server

7. After clicking start server, eclipse will open test web service API. With this test API, you can test your
web service
Creating a SOAP based Web Service
STEP 1: Create a new dynamic web project and name it “SimpleSOAPExample”
Create a new dynamic
web project and name
it
“SimpleSOAPExample”’

Create a new package


named
“com.webservice”

Create a simple Java


class named
“HelloWorld.java”

Right click project 


new  web service

Click next

Click start server

Test your Web service


Creating a SOAP based Web Service
STEP 2: Create a new package named “com.webservice”
Create a new dynamic
web project and name
it
“SimpleSOAPExample”’

Create a new package


named
“com.webservice”

Create a simple Java


class named
“HelloWorld.java”

Right click project 


new  web service

Click next

Click start server

Test your Web service


Creating a SOAP based Web Service
STEP 3: Create a simple Java class named “HelloWorld.java”
Create a new dynamic
web project and name
it The following example is of a simple service that accepts a string parameter, invokes a
“SimpleSOAPExample”’ method justSayHello, and returns a String parameter:
Create a new package
named
“com.webservice” package com.weservice;
Create a simple Java
public class HelloWorld {
class named
“HelloWorld.java”
public String sayHelloWorld(String name)
Right click project  {
new  web service return "Hello world from "+ name;
}
}
Click next

Click start server

Test your Web service


Creating a SOAP based Web Service
STEP 4: Right click project  new  web service
Create a new dynamic
web project and name
it
“SimpleSOAPExample”’

Create a new package


named
“com.webservice”

Create a simple Java


class named
“HelloWorld.java”

Right click project 


new  web service

Click next

Click start server

Test your Web service


Creating a SOAP based Web Service
STEP 5: CLICK NEXT
Create a new dynamic
web project and name
it
“SimpleSOAPExample”’

Create a new package


named
“com.webservice”

Create a simple Java


class named
“HelloWorld.java”

Right click project 


new  web service

Click next

Click start server

Test your Web service


Creating a SOAP based Web Service
STEP 6: CLICK START SERVER
Create a new dynamic
web project and name
it
“SimpleSOAPExample”’

Create a new package


named
“com.webservice”

Create a simple Java


class named After you click start
“HelloWorld.java”
server, you will be re-
directed to this page.
Right click project 
Click Finish.
new  web service

Click next

Click start server

Test your Web service


Creating a SOAP based Web Service
STEP 7: TEST YOUR WEB SERVICE
Create a new dynamic
web project and name
it
“SimpleSOAPExample”’

Create a new package


named
“com.webservice”

Create a simple Java


class named
“HelloWorld.java”

Right click project 


new  web service

Click next

Click start server

Test your Web service


SOA and Web Services
Topic 4—Creating a RESTful Web Service

• Introduction to RESTful Web Services


• RESTful Web Services: Working
• Creating a RESTful Web Service
• SOAP vs. RESTful Web Services
Introduction to RESTful Web Services

RESTful web services are lightweight, highly scalable, and maintainable Web Services. They are basically
based on REST (Representational State Transfer) Architecture.

REST architecture is basically focuses on two things:

1. Resources: Its application functionality, which is represented by a unique URL.


2. Interface: Its HTTP method works as an interface to access the resources.
RESTful Web Services: Working

• A RESTful web service usually defines a URI (Uniform Resource Identifier), which is a service that provides
resource representation such as JSON and a set of HTTP Methods.

• There is no need to use XML data interchange format for request and response.

• The REST web services can be return XML, JSON, or even HTML format response.

Smartphone
Creating a RESTful Web Service
FUNCTIONALITIES

Create a web service called UserLog Management with the following functionalities:

HTTP Method URI Operation Operation Type

GET /UserLogService/users Get list of users Read Only

GET /UserLogService/users/1 Get User with Id 1 Read Only

PUT /UserLogService/users/2 Insert User with Id 2 Idempotent

POST /UserLogService/users/2 Update User with Id 2 N/A

DELETE /UserLogService/users/1 Delete User with Id 1 Idempotent

List the supported


OPTIONS /UserLogService/users Read Only
operations in web service
Creating a RESTful Web Service
ENVIRONMENT SETUP

1. Set up Java Development Kit (JDK)

2. Set up Eclipse IDE

3. Set up Jersey Framework Libraries

4. Download the latest version of Jersey framework binaries from the following link:
https://jersey.java.net/download.html

5. Set up Apache Tomcat


Creating a RESTful Web Service
WRITING RESTful WEB SERVICE WITH JERSEY FRAMEWORK

1. Create a Dynamic Web Project named UserLogManagement using Eclipse IDE.

2. Add Jersey Framework and its dependencies (libraries) in your project.

3. Create UserLogService.java and User.java,UserLogDao.java files under your dynamic project

4. Create a Web XML Configuration file to specify Jersey framework servlet for your application.

5. Export your application as a war file and deploy the same in tomcat.
Creating a RESTful Web Service
Writing User.Java class

Class User has id, name, and designation member variable, and it uses @XmlRootElement and
@XmlElement annotations.

//When a top level class is annotated with the @XmlRootElement annotation,


then its value is //represented as XML element in an XML document.
@XmlRootElement(name = "user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private String profession;
@XmlElement //Maps a JavaBean property to a XML element derived from
property name.
//setter methods
//getter methods
//constructor
}
Creating a RESTful Web Service
Writing UserLogDAO Class

It uses two methods to get user details. First, it checks for the file name User.dat. It it does not exist, it
adds one user data to UserList. It then opens User's file and reads data.

public List<User> getAllUsers(){


List<User> userList = null;
File file = new File("Users.dat"); private void saveUserList(List<User>
if (!file.exists()) { userList){
User user = new User(1, "John", "Worton"); try {
userList = new ArrayList<User>(); File file = new
userList.add(user); File("Users.dat");
saveUserList(userList); FileOutputStream fos;
else{ fos = new
FileInputStream fis = new FileOutputStream(file);
FileInputStream(file); ObjectOutputStream oos = new
ObjectInputStream ois = new ObjectOutputStream(fos);
ObjectInputStream(fis); oos.writeObject(userList);
userList = (List<User>) ois.readObject(); oos.close();
ois.close(); }
return userList;
}
Creating a RESTful Web Service
Writing UserLogservice Class

Path("/UserLogService") //Identifies the URI path that a resource class or class


method will serve //requests for.

public class UserLogService {


UserDao userDao = new UserDao();
@HttpMethod(value="GET") // Indicates that the annotated method responds to
HTTP GET requests
@Path("/users")
@Produces(MediaType.APPLICATION_XML) // is used to specify the MIME
(Multipurpose //Internet Mail Extensions)media types or representations a
resource can produce and send back to the //client.
public List<User> getUsers(){
return userDao.getAllUsers();
}
}
Creating a RESTful Web Service
Writing web.xml File

web-app>
<servlet>
<servlet-name>Jersey RESTful Application</servlet-name>
<servlet-
class>org.glassfish.jersey.servlet.ServletContainer</servletclass>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.tutorialspoint</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Jersey RESTful Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>

URL to run the program:


http://localhost:8080/UserLogManagement/rest/UserLogService/users
SOAP vs. RESTful Web Services

SOAP RESTful
The main advantage of SOAP is that it provides a
In RESTful Web Services, clients have to know what to
mechanism for services to describe themselves to
send and what to expect.
clients and to advertise their existence.
SOAP brings its own protocol and focuses on
REST is focused on accessing named resources
exposing pieces of application logic (not data) as
through a single consistent interface.
services.
REST has better performance and scalability. REST
SOAP-based reads cannot be cached.
reads can be cached,

SOAP only permits XML. REST permits many different data formats
SOA and Web Services
DEMO—RESTful Web Services
Key Takeaways

Software evolution begins with understanding the concept of 1 and 0 (i.e.,bits)


that gives rise to machine language, followed by assembly language, procedure
oriented, object oriented, component oriented, and service oriented.

Service Oriented approach follows an architecture, called SOA (Service Oriented


Architecture), that focuses on building systems through the use of different Web
Services and integrating them to make up the whole system.

Web applications enable interaction between an end user and a website. Web
services are service-oriented and enable application-to-application
communication over the Internet and easy accessibility to heterogeneous
applications and devices.

RESTful web services are lightweight, highly scalable, and maintainable Web
Services. They are basically based on REST (Representational State Transfer)
Architecture.
Quiz
QUIZ
UDDI stands for
1

a. Universal Description Discovery and Integration

b. Unified Description Directory and Integration

c. Uniform Data Dictionary and Identification

d. Uniform Data Dictionary and Integration


QUIZ
UDDI stands for
1

a. Universal Description Discovery and Integration

b. Unified Description Directory and Integration

c. Uniform Data Dictionary and Identification

d. Uniform Data Dictionary and Integration

The correct answer is a.


UDDI stands for Universal Description Discovery and Integration
QUIZ
Which of the following is correct about WSDL?
2

a. WSDL is the standard format for describing a web service.

b. WSDL definition describes how a web service can be accessed and what operations it
can perform

c. WSDL is a language for describing how to interface with XML-based services

d. All of the above


QUIZ
Which of the following is correct about WSDL?
2

a. WSDL is the standard format for describing a web service.

b. WSDL definition describes how a web service can be accessed and what operations it
can perform

c. WSDL is a language for describing how to interface with XML-based services

d. All of the above

The correct answer is d. All of the above


WSDL is the standard format for describing a web service. WSDL definition describes how a web
service can be accessed and what operations it can perform. WSDL is a language for describing how
to interface with XML-based services
Thank You

You might also like