Advanced Java eBook
Advanced Java eBook
• 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 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
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
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
Complexity
Relating Java EE Architecture Complexity and Robustness
KEY POINTS
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!
• 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.
Server 1 Server 3
Application Application
Server 2 Server 4
Application Application
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).
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
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.
http://localhost:8080/MyApplication
• HTTP (Hypertext Transfer Protocol) is a TCP/IP based communication protocol, which is used to deliver
data over the web.
• 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
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
• Web Server
• Application Server
• Proxy Server
• Virtual ServerBlade Server
• File Server
• Policy Server
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
TRACE
OPTION
HEAD
Client-Server Model
CLIENT REQUEST TYPES: POST
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.
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
• 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
<!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
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
3. Place your HTML page inside project folder with index.html name or any_other_name.html
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
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
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.
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
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.
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.
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.
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
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
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.
init and destroy Used to manage resources that are held for the life of the Servlet
When a request is mapped to a Servlet, the container performs the following steps if an instance of the
Servlet does not exist.
Called once init method (ServletConfig config) Initiates and calls init()
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
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”
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”
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
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)
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
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 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)
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
• 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
• 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
ServletContext:
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
• Servlet Attributes
• Attribute Specific Methods
Servlet Attributes
Attribute Scope
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
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
• RequestDispatcher interface is used to forward request and response objects to another Servlet
2. forward(-,-)
ServletOne ServletSecond
1. request
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
4. Final response
is generated
5. Final response is
client sent back to the client
Response Response
include() method
include() method: Syntax
rd.include(request,response);
RequestDispatcher Interface
Validate Servlet
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.
a. javax.Servlet
b. javax.Servlet.http
d. Both
e. java.Servlet
a. init()
b. service()
c. destroy()
d. getServletInfo()
e. getServlet()
The correct answer is b
Thank You
Advanced Java
Lesson 3—Java Servlet II
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.
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
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
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
Browser Client
Hidden Form
Field Form 1
Request 1
Name Servlet 1
URL Writing
Address
Cookie
Form 2
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
• 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
Hidden Form
Field
Url Writing
Request
Client Server
Response + Cookie
Cookie
Request + Cookie
HttpSession
Constructor and Methods of Cookie Class
Url Writing
• Cookie class has the following methods:
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
• 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
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
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.
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:
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
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
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
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.
<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?
• 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
http request
Filter
request object request object
http response
Filter Types
3. Request-Response Filter: Contains both pre-request processing and post-response generation logic.
Developing and Mapping a Filter Class
<filter>
<filter-name> onelogicalname </filter-name>
<filter-class> filterclassname </filter-class>
</filter>
<filter-mapping>
<filter-name> onelogicalname </filter-name>
<furl-pattern> /urlpatter </url-pattern>
</filter-mapping>
Writing a Filter Program
• Create a Java class to implement Filter interface that has the following three methods:
If multiple filters are configured for servlet, they are executed in the same order in which they are defined in
web.xml
http request
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.
Hidden Form Field, Url Writing, Cookies, and HttpSession are types of session
management.
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
JSP is used to dynamically generate web content on a server and return it to the
client. This can also be done using servlet.
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
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
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
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
1. standard
2. XML
<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.
• 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
• 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.
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.
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:
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.
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.
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
This tag is used to interact with a JavaBean component using the standard tags in a JSP page.
Syntax :
Syntax:
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:
• 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”/>
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.
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.
Syntax:
${expr}
• JSP standard tag library (JSTL) represents a set of tags used to simplify development of JSP
Core JSTL tag is used to write expression and render data to page.
Welcome.html
Process.jsp
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>
</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:
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
Let's start by discussing why we need Hibernate and why it was created?
Think Through!
MySQL
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
• Association: Java can use association by having another class variable as member; in SQL, no standard
concept is available to represent association
BILLING RECORDS
USER
• 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
• 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
• 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
• Surrogate key, Identifier, and other key features can be automated in ORM
ORM Architecture
Java Application
Mapping Information
ORM Engine: facilitates creation of mapping information
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.
• 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 persistence provider can be used in any environment of Java platform, Java SE or Java EE.
Hibernate Programming Model
Transaction Factory
JNDI
Session Factory
Connection Provider
Transaction JTA
Session object is created within the Database Layer in every DAO method. It is known as persistence
object.
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
• 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)
3. Session (org.hibernate.Session)
4. Transaction (org.hibernate.Transaction)
The application programmer may create one's own generator classes by implementing the
IdentifierGenerator interface.
• 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
Oracle9i org.hibernate.dialect.Oracle9iDialect
Oracle10g org.hibernate.dialect.Oracle10gDialect
MySQL org.hibernate.dialect.MySQLDialect
DB2 org.hibernate.dialect.DB2Dialect
Create the
ClassName.hbm.xml file in src
folder (mapping file)
Create the
ClassName.hbm.xml file in src
folder (mapping file)
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>
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
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
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.
Use POJO class student, hibernate.cfg.xml file, and annotations instead of hibernate mapping file.
Creating POJO Class With Annotation
RUNNING THE APPLICATION
}
}
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
NATIVE SQL
Criteria
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).
Create a Student object with existing ID and use sessionobject.update (Object object)
Create a Student object with existing ID and use sessionobject.delete (Object object)
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.
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
Discuss HQL
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 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 SQL Query: Select * from Student, where Student
class name is one table name
Features of HQL
• HQL is object-oriented
• UPDATE
• DELETE
• SELECT
Using HQL, we can move table data to another table. However, we cannot insert
data using HQL.
Creating HQL Query
3. Open Session
Session sn = sf.openSession();
4. Create query
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.
setString: This informs Hibernate that the parameter date type is String
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
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
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.
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.
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
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();
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:
Let’s assume we have one table named student, and one class named Student mapped to student
table, which has following structure:
class Student
{
private int rollno;
private String name;
private int age;
private int marks;
//getter and setter methods
}
Applying Criteria Query
Session s; s.createCriteria(Student.class).list();
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
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?
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
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
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:
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
Columns declared by the subclasses may not have NOT NULL constraints.
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
{
...
}
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.
Component
Mapping Employee Owner
person_id:Integer person_id:Integer
joining_date: Date stocks: Integer
department name: Char department name: Char
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,
}
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
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;
} }
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.
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
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 }
} }
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);
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
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
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
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
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.
Transaction succeeded
commit
rollback
Transaction failed
Transaction Interface
In hibernate framework, we have transaction interface that defines the unit of work.
• void commit() ends the unit of work unless you are in FlushMode.NEVER.
• void setTimeout(int seconds) sets a transaction timeout for any transaction started by a subsequent call to
begin on this instance.
Hibernate provides its own language known as Hibernate Query Language. The
syntax is quite similar to database SQL language.
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
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
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”);
} }
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
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 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.
Specifying
Required
MysqlConnectionProvider
Provider Class
Myproperties.properties
MyContainer
Calling getBean() methods
Why Spring: Example
Myproperties.properties
1.provider=OracleConnectionProvider
Why Spring: Example
Let’s create a MyContainer class to fetch the properties from the Myproperties.properties file.
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 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 :
• 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 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
Transactions
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-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.
• 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.
We have discussed that Spring provides the container and provides spring configuration file (XML file) to
configure our required provider classes instead properties file.
• 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:
Java classes that are handled by this container are called spring beans.
Uses of Spring IOC Container
1. Instantiation of object
2. Dependency injection
3. Initialization to read configuration metadata
Spring Framework's IOC Container Package
• 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 (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 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
• 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.
• 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.
OR
Constructor of XmlBeanFactory class takes Resource object as an argument. This represents spring
configuration file.
Resource
FileSystemResource ClassPathResource
Creating SpringBean Container
Creating Spring Bean Container involves creating an object of any implemented class.
ClassPathXmlApplicationContext .
ClassPathXmlApplicationContext .
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.
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:
SpringBeanName
reference_variable=(SpringBeanName)factory.getBean("reference_id_for_class_objec
t");
• <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
• Setter injection: If dependency is injected to dependent object via setter method, it is known as setter
injection.
<beans…>
<bean id=” “ class=” “ >
<property name=”nameOfClassMemberVariable” value =” “ >
</property>
or
or
<beans…>
<bean id=” “ class=” “ >
<property name=”nameOfClassMemberVariable” ref =”dependency_class_id
“ > </property>
or
or
or
or
<constructor-arg>
<value> </value>
</constructor-arg>
</property>
</bean>
</beans>
Implementing Constructor Injection
IMPLEMENTATION OF CONSTRUCTOR INJECTION WHERE DEPENDENCY IS OBJECT TYPE
or
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
<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>
<beans…>
<bean id=” “ class=” “ >
<property name=”nameOfClassMemberVariable” >
<list>
<ref bean=” reference_id1“ />
<ref bean=” reference_id2“ />
<ref bean=” reference_id3“ />
</list>
</property>
</bean>
</beans>
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
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
3. BeanNameAware: An interface used to override its method setBeanName(String) and get bean name
6. Method Ready State: In this state, object is ready for use and business methods can be called.
Syntax:
@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:
@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:
@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:
@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:
@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:
@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
1. constructor
2. byName
3. byType
4. autodetect
Types of AutoWiring
constructor
constructor Example:
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
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
1) singleton: Create the configured spring bean only once in the container
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 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).
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
a. It is a lightweight framework
b. It is an opensource framework
a. It is a lightweight framework
b. It is an opensource framework
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:
2) “Cross concerns” are functions that are conceptually separate from the application's business logic
but affect the entire service layer.
Aspect-Oriented Programming provides one way to decouple dynamically core concern from
crosscutting concern.
What Is AOP?
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
• 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.
• Proxy design pattern: Actual object (business object) is wrapped into another object knows as proxy and
substitutes that object in place of actual object
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
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
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
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.
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.
Proxy 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.
1. Before advice: It executes before a Joinpoint but does not have the ability to prevent execution flow
proceeding to the Joinpoint
3. Around advice: It surrounds a Joinpoint such as a method invocation. It can perform custom behavior
before and after method invocation.
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.
• 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.
• It is used to intercept after the method execution. For example, a system needs to perform some
delete operations after logging out.
invoke()
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.
• 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. By annotation
2. By XML configuration
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.
@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
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");
}
}
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
@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
<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>
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.
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 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)
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
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.
1. For insert(), update(), and delete() methods of JDBC, Spring JdbcTemplate provides update()
method
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)
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
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.
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 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
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.
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
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
Create UserDao.java
file
Create
applicationContext.x
ml file
Create database
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
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
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 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
Find the class SpringDemo.java. SpringDemo calls the persist method from the PageDao to
Create database save the data in database. Run the command.
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.
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
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:
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.
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
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.
Solution
To solve the above problems, Sun microsystem introduced two design patterns for developing
enterprise applications:
request 1
JSP
response
4
Enterprise
Browser 2 Server/Data
Source
3
JavaBean
Application Server
Model 1: Page Centric Model
WORKFLOW
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
• 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
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>
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
• 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
ModelAndView
Example:
ViewResolver
ModelAndView mv=new ModelAndView(“successView”, “greetingMsg”, “greetingMessage);
Components of Spring MVC
ModelAndView
ModelAndView
ViewResolver
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
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 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
Create web.xml
(Deployment
Descriptor)
Create
HelloWorldControll
er.java (Controller)
Create mvc-
dispatcher-
servlet.xml file.
(Spring
Configuration)
Create web.xml
(Deployment
Descriptor)
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
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
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…
Messages
Management
Security
SOAP Extensions
Reliability, Correlation, Transactions….
SOAP
Communications
HTTP, SMTP, FTP, JMS, IIOP
What Is SOA?
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
SOA
Service Consumer Service Provider
SOA is a solution for making
two software communicate to
each other
Advantages of SOA
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
Directory
Service
Description
Service Service
Consumer Provider
Implementation
Service Consumer Service Provider Web Service
Web Service is an
implementation of
SOA
SOA and Web Services
Topic 2—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.
4. Web services facilitate ease of application integration using a lightweight infrastructure without
affecting scalability.
• 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
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
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
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)?
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
Universal
Description,
Discovery and
Integration
(UDDI)
Web Services
Description
Language (WSDL)
Simple Object
Access Protocol
(SOAP)
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.
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)
There are two main APIs defined by Java for developing web service applications (since Java EE 6):
• 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:
• It helps undeploy a service, ensures that the AXIS CLASSPATH is set, and then runs the following command:
To create a Web service in an Axis environment, the following Models are used:
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.
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”’
Click next
Click next
Click next
Click next
Click next
Click next
RESTful web services are lightweight, highly scalable, and maintainable Web Services. They are basically
based on REST (Representational State Transfer) Architecture.
• 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:
4. Download the latest version of Jersey framework binaries from the following link:
https://jersey.java.net/download.html
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.
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.
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>
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
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
b. WSDL definition describes how a web service can be accessed and what operations it
can perform
b. WSDL definition describes how a web service can be accessed and what operations it
can perform