Tyit Sem 5 Advance Java
Tyit Sem 5 Advance Java
UNIT 1
Understanding JAVA EE
what is Enterprise Applications
Java EE platform is designed to help developers create large-scale, multi-tiered, scalable, reliable, and secure network
applications
A shorthand name for such applications is “enterprise applications,” so called because these applications are designed
to solve the problems encountered by large enterprises.
Enterprise applications are not only useful for large corporations, agencies, and governments, however. The benefits
of an enterprise application are helpful, even essential, for individual developers and small organizations in an
increasingly networked world.
The features that make enterprise applications powerful, like security and reliability, often make these applications
complex.
The Java EE platform is designed to reduce the complexity of enterprise application development by providing a
development model, API, and runtime environment that allows developers to concentrate on functionality.
Tiered Applications
In a multi-tiered application, the functionality of the application is separated into isolated functional areas, called tiers.
Typically, multi-tiered applications have a client tier, a middle tier, and a data tier (often called the enterprise information
systems tier). The client tier consists of a client program that makes requests to the middle tier. The middle tier's
business functions handle client requests and process application data, storing it in a permanent datastore in the data
tier.
Java EE application development concentrates on the middle tier to make enterprise application management easier,
more robust, and more secure.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
1
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
The Java EE platform is built on top of the Java SE platform. The Java EE platform provides an API and runtime
environment for developing and running large-scale, multi-tiered, scalable, reliable, and secure network applications.
The Java EE APIs include several technologies that extend the functionality of the base Java SE APIs, such
as Enterprise JavaBeans, connectors, servlets, JavaServer Pages and several web service technologies.
• Contexts and Dependency Injection is a specification to provide a depencency injection container, as in Spring;
• Enterprise JavaBean (EJB) specification defines a set of lightweight APIs that an object container (the EJB
container) will support in order to provide transactions (using JTA), remote procedure
calls (using RMI or RMI-IIOP), concurrency control, dependency injection and access control for business
objects. This package contains the Enterprise JavaBeans classes and interfaces that define the contracts
between the enterprise bean and its clients and between the enterprise bean and the ejb container.
• Java Persistence API are specifications about object-relational mapping between relation database tables and
Java classes.
• Java Transaction API contains the interfaces and annotations to interact with the transaction support offered
by Java EE. Even though this API abstracts from the really low-level details, the interfaces are also considered
somewhat low-level and the average application developer in Java EE is either assumed to be relying on
transparent handling of transactions by the higher level EJB abstractions, or using the annotations provided
by this API in combination with CDI managed beans.
• Java Message Service provides a common way for Java programs to create, send, receive and read an
enterprise messaging system's messages.
Java EE technologies
Java EE Technologies Used in the Web Tier
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
2
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
Technology Purpose
Servlets Java programming language classes that dynamically process requests and construct
responses, usually for HTML pages
JavaServer Faces A user-interface component framework for web applications that allows you to include UI
technology components (such as fields and buttons) on a page, convert and validate UI component
data, save UI component data to server-side data stores, and maintain component state.
JavaServer Faces Facelets applications are a type of JavaServer Faces applications that use XHTML pages
Facelets technology rather than JSP pages.
Expression A set of standard tags used in JSP and Facelets pages to refer to Java EE components.
Language
JavaServer Pages Text-based documents that are compiled into servlets and define how dynamic content can
(JSP) be added to static pages, such as HTML pages.
JavaServer Pages A tag library that encapsulates core functionality common to JSP pages
Standard Tag Library
JavaBeans Objects that act as temporary data stores for the pages of an application
Components
Technology Description
Enterprise JavaBeans Enterprise beans are managed components that encapsulate the core functionality of an
(enterprise bean) application.
components
JAX-RS RESTful web An API for creating web services that respond to HTTP methods (for
services example GET or POST methods). JAX-RS web services are developed according to the
principles of REST, or representational state transfer.
JAX-WS web service An API for creating and consuming SOAP web services.
endpoints
Java Persistence API An API for accessing data in underlying data stores and mapping that data to Java
entities programming language objects.
Java EE managed beans Managed components that may provide the business logic of an application, but do not
require the transactional or security features of enterprise beans.
Technology Description
The Java Database A low-level API for accessing and retrieving data from underlying data stores. A common
Connectivity API use of JDBC is to make SQL queries on a particular database.
(JDBC)
The Java Persistence An API for accessing data in underlying data stores and mapping that data to Java
API programming language objects. The Java Persistence API is a much higher-level API
than JDBC, and hides the complexity of JDBC from the user.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
3
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
The Java EE Connector An API for connecting to other enterprise resources, like enterprise resource planning or
Architecture customer management system software.
The Java Transaction An API for defining and managing transactions, including distributed transactions or
API (JTA) transactions that cross multiple underlying data sources.
Java EE evolution
• 1998 saw the release of the first incarnation of Enterprise Java, but soon after, important technologies soon
joined the mix, such as Servlets, Messaging, and Enterprise Java Beans.
• These technologies still exist in the Enterprise platform today but in a much more advanced and
comprehensive form.
• Over the following years, it developed a programming model that was difficult to use and very cumbersome.
This all changed in the fifth edition, which saw a radical shift away from XML configuration towards
annotations and convention over configuration.
• The new programming model had simplified substantially. Annotations replace XML description files,
convention over configuration replaces the tedious manual configuration and dependency injection hides the
creation and lookup of resources. Resources are created and injected at injection points marked by
annotations such as @Inject. So all you need is a POJO that meets the conditions of the managed beans
specification, JSR 299, and depending on the annotation used it will become an EJB, Servlet, Singleton or
a RESTful web service.
• The platform continued to grow, but at a much slower rate. With each new release, it becomes more
programmer friendly and the number of APIs blossomed to reach 28+, up from just a handful of five APIs
in 1999.
• Java EE 7 Once a JSR is approved and its development finalized, it forms part for the next release of the
platform.
• The Java EE 7 release added four new APIs.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
4
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
• They were JSON-Processing, WebSocket API, Batch Processing and Concurrency. All these APIs
started life as a JSR on which the community and JCP members commented, deliberated and discussed until
a final specification request was devised and the development could begin.
• Oracle GlassFish Server is the world's first implementation of the Java Platform, Enterprise Edition (Java EE)
6 specification. Built using the GlassFish Server Open Source Edition, Oracle GlassFish Server delivers a
flexible, lightweight, and production-ready Java EE 6 application server.
• GlassFish is an open-source application server project started by Sun Microsystems for the Java EE platform
and now sponsored by Oracle Corporation. The supported version is called Oracle GlassFish Server.
GlassFish is free software, dual-licensed under two free software licences: the Common Development and
Distribution License (CDDL) and the GNU General Public License (GPL) with the classpath exception.
• GlassFish is the reference implementation of Java EE and as such supports Enterprise
JavaBeans, JPA, JavaServer Faces, JMS, RMI, JavaServer Pages, servlets, etc. This allows developers to
create enterprise applications that are portable and scalable, and that integrate with legacy technologies.
Optional components can also be installed for additional services.
• GlassFish is based on source code released by Sun and Oracle Corporation's TopLink persistence system. It
uses a derivative of Apache Tomcat as the servlet container for serving Web content, with an added
component called Grizzly which uses Java New I/O (NIO) for scalability and speed.
Java EE Architecture
Normally, thin-client multitiered applications are hard to write because they involve many lines of intricate code to handle
transaction and state management, multithreading, resource pooling, and other complex low-level details.
The component-based and platform-independent Java EE architecture makes Java EE applications easy to write
because business logic is organized into reusable components and the Java EE server provides underlying services in
the form of a container for every component type.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
5
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
Because you do not have to develop these services yourself, you are free to concentrate on solving the business
problem at hand.
Java Enterprise System deployment architectures is analyzed along three dimensions: logical tiers, infrastructure
service levels, and quality of service.
Logical Tiers
The standard architecture for distributed applications separates application logic into a number of tiers. These tiers
signify a logical and physical organization of components into an ordered chain of service providers and consumers.
Components within a tier typically consume the services provided by components in an adjacent provider tier and
provide services to one or more components in an adjacent consumer tier.
The interacting software components of distributed enterprise applications require an underlying set of infrastructure
services that allows the distributed components to communicate with each other, coordinate their work, implement
secure access, and so forth. This set of distributed services constitutes an infrastructure upon which distributed
components can be built.
Quality of Service
The previous two architectural dimensions (logical tiers and infrastructure service levels) largely define the logical
aspects of architecture, namely which components are needed to interact in what way to deliver services to end users.
However, an equally important dimension of any deployed solution is the ability of the solution to meet quality of service
requirements.
As internet and E-commerce services have become more critical to business operations, the performance, availability,
security, scalability, and serviceability of these services has become a key requirement of large-scale, high-
performance deployment architectures.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
6
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
Java EE Server
A Java EE server is a server application that the implements the Java EE platform APIs and provides the standard
Java EE services. Java EE servers are sometimes called application servers, because they allow you to serve
application data to clients, much like web servers serve web pages to web browsers.
Java EE servers host several application component types that correspond to the tiers in a multi-tiered application. The
Java EE server provides services to these components in the form of a container.
Java EE Containers
Java EE containers are the interface between the component and the lower-level functionality provided by the platform
to support that component. The functionality of the container is defined by the platform, and is different for each
component type. Nonetheless, the server allows the different component types to work together to provide functionality
in an enterprise application.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
7
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
• So even if the same client makes another request, server receives it as a new request from a new user, in
other words server does not remember the client or the history of transactions with that client.
• If the request is for a static content like an HTML file or media file, server is much happy with that request and
return the file as the response.
• If the request is for a dynamic content like a web page which contains weather details on that day, or current
time (Notice that these details cannot be hard coded in a static HTML file it has to be generated on runtime)
a web server cannot handle that request.
• It has to be handled by any other helper applications (here dynamic content maker is needed)
A Java servlet is a Java program that extends the capabilities of a server. Such Web servlets are the Java counterpart
to other dynamic Web content technologies such as PHP and ASP.NET. Compared to CGIs, Servlets provide high
performance, easy exception management and portability.
• Servlet technology is used to create web application (resides at server side and generates dynamic web page).
• Servlet technology is robust and scalable because of java language. Before Servlet, CGI (Common Gateway
Interface) scripting language was popular as a server-side programming language.
• Servlet can be described in many ways, depending on the context.
o Servlet is a technology i.e. used to create web application.
o Servlet is an API that provides many interfaces and classes including documentations.
o Servlet is an interface that must be implemented for creating any servlet.
o Servlet is a class that extends the capabilities of the servers and responds to the incoming requests.
It can respond to any type of requests.
o Servlet is a web component that is deployed on the server to create dynamic web page.
Why Servlets?
Several advantages of servlet
Platform independence
• Servlets run on top of Java Virtual Machine (JVM) so they are platform independent components. On the other
hand CGIs run on the operating system itself so they are platform dependent.
Performance
• CGIs run on separate processes, so it takes more time to start a new process for each and every requests.
Servlets are accessed through threads and those threads also being kept in a thread pool. It increases the
performance.
Security
• Servlets are running inside the sand box of JVM, so it is hard to damage the server side modules by
malfunctioning the Servlets. Since CGIs are native applications, using CGIs a hacker can damage the server
side components easily compared to Servlets.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
8
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
Error Handling
•
Servlets provides easiest error handling mechanism jointly with web container. CGIs do not have such a
powerful error handling support.
Extensibility
• Servlets are just Java classes so it is easy maintain and extend their functionality. All the object oriented
concepts can be directly applied to Servlets as well. CGIs are mostly written in scripting languages like Perl
so the extensibility is very poor in case of CGIs.
1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener
1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
9
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)
1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)
Servlet Types
• Generic servlets
o Extend javax.servlet.GenericServlet.
o Are protocol independent. They contain no inherent HTTP support or any other transport protocol.
• HTTP servlets
o Extend javax.servlet.HttpServlet.
o Have built-in HTTP protocol support and are more useful in a Sun Java System Web Server
environment.
• For both servlet types, you implement the constructor method init() and the destructor method destroy() to
initialize or deallocate resources.
• All servlets must implement a service() method, which is responsible for handling servlet requests. For
generic servlets, simply override the service method to provide routines for handling requests.
• HTTP servlets provide a service method that automatically routes the request to another method in the servlet
based on which HTTP transfer method is used. So, for HTTP servlets, override doPost()to process POST
requests, doGet() to process GET requests, and so on.
import javax.servlet.GenericServlet;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class Hrishikesh extends GenericServlet
{
public void service(ServletRequest req, ServletResponse res)
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
10
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
{
// some code
}
}
HttpServlet
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Hrishikesh1 extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
{
//some code
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
{
//some code
}
}
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
11
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
As displayed in the above diagram, there are three states of a servlet: new, ready and end. The servlet is in new state
if servlet instance is created. After invoking the init() method, Servlet comes in the ready state. In the ready state, servlet
performs all the tasks. When the web container invokes the destroy() method, it shifts to the end state.
The classloader is responsible to load the servlet class. The servlet class is loaded when the first request for the servlet
is received by the web container.
The web container creates the instance of a servlet after loading the servlet class. The servlet instance is created only
once in the servlet life cycle.
The web container calls the init method only once after creating the servlet instance. The init method is used to initialize
the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the init method is given below:
The web container calls the service method each time when request for the servlet is received. If servlet is not initialized,
it follows the first three steps as described above then calls the service method. If servlet is initialized, it calls the service
method. Notice that servlet is initialized only once. The syntax of the service method of the Servlet interface is given
below:
The web container calls the destroy method before removing the servlet instance from the service. It gives the servlet
an opportunity to clean up any resource for example memory, thread etc. The syntax of the destroy method of the
Servlet interface is given below:
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
12
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class Hrishikesh extends GenericServlet
{
public void service(ServletRequest req, ServletResponse res)
{
try
{
PrintWriter pw = res.getWriter();
pw.print("Hello world"); // print in s
}
catch (Exception e)
{
System.out.println(e+" exception in hrishikesh servlet..");
}
}
}
Getting Started
IDE is Integrated Development Environment, and it makes creating applications a lot easier.
1. To create a servlet application in Netbeans IDE, you will need to follow the following (simple) steps :
2. Open Netbeans IDE, Select File -> New Project
3. Select Java Web -> Web Application, then click on Next,
4. Give a name to your project and click on Next,
5. and then, Click Finish (select glassfish server)
6. The complete directory structure required for the Servlet Application will be created automatically by the IDE.
7. To create a Servlet, open Source Package, right click on default packages -> New -> Servlet.
8. Give a Name to your Servlet class file
9. If you want you can click the checkbox if you want to use web.xml file
10. Now, your Servlet class is ready, and you just need to change the method definitions and you will good to go.
(use classroom examples for examples)
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
13
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
name = "AnnotatedServlet",
description = "A sample annotated servlet",
urlPatterns = {"/Annotation"} // now we dont need web.xml
)
public class Hrishikesh extends GenericServlet
{
public void service(ServletRequest req, ServletResponse res)
{
try
{
PrintWriter pw = res.getWriter();
pw.print("Hello world"); // print in s
}
catch (Exception e)
{
System.out.println(e+" exception in hrishikesh servlet..");
}
}
}
What is JDBC
Design of JDBC:
The JDBC™ API was designed to keep simple things simple. This means that the JDBC makes everyday
database tasks easy.
ADVANTAGES OF JDBC
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
14
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access.
In the two-tier model, a Java application talks directly to the data source. This requires a JDBC driver that can
communicate with the particular data source being accessed. A user's commands are delivered to the database or
other data source, and the results of those statements are sent back to the user. The data source may be located on
another machine to which the user is connected via a network. This is referred to as a client/server configuration, with
the user's machine as the client, and the machine housing the data source as the server. The network can be an
intranet, which, for example, connects employees within a corporation, or it can be the Internet.
In the three-tier model, commands are sent to a "middle tier" of services, which then sends the commands to the data
source. The data source processes the commands and sends the results back to the middle tier, which then sends
them to the user. MIS directors find the three-tier model very attractive because the middle tier makes it possible to
maintain control over access and the kinds of updates that can be made to corporate data. Another advantage is that
it simplifies the deployment of applications. Finally, in many cases, the three-tier architecture can provide performance
advantages.
Until recently, the middle tier has often been written in languages such as C or C++, which offer fast performance.
However, with the introduction of optimizing compilers that translate Java bytecode into efficient machine-specific code
and technologies such as Enterprise JavaBeans™, the Java platform is fast becoming the standard platform for middle-
tier development. This is a big plus, making it possible to take advantage of Java's robustness, multithreading, and
security features.
With enterprises increasingly using the Java programming language for writing server code, the JDBC API is being
used more and more in the middle tier of a three-tier architecture. Some of the features that make JDBC a server
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
15
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
technology are its support for connection pooling, distributed transactions, and disconnected rowsets. The JDBC API
is also what allows access to a data source from a Java middle tier.
JDBC driver
The JDBC API defines the Java interfaces and classes that programmers use to connect to
databases and send queries. A JDBC driver implements these interfaces and classes for a
particular DBMS vendor. The JDBC driver converts JDBC calls into a network or database
protocol or into a database library API call that makes communication with the database.
This translation layer provides JDBC applications with database autonomy. In the case of
any back-end database change, only we need to just replace the JDBC driver & some code
modifications are required. "The Java program that uses the JDBC API loads the specified
driver for a particular DBMS before it actually connects to a database. After that the JDBC
DriverManager class then sends all JDBC API calls to the loaded driver".
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
16
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
Accessing Database
To access and work with a database using JDBC, the following are the steps involved:
• Configuring JDBC Driver
• Creating A Database Connection
• Executing Queries
• Processing The Results
• Closing The Database Connection
Configuring JDBC Driver
The first step In establish a database connection using a JDBC driver involves loading the specific
driver class into the application's JVM. This makes the driver available later required for opening
the connection.
• Class.forName(String).newInstance() is used to load the JDBC driver class:
• Class.forName("com.mysql.jdbc.Driver").newInstance();
• The above code spec indicates that the JDBC driver from some JDBC vendor has to be
loaded into the application.
• Class.forName() is a static method. This instructs the JVM to dynamically locate, load and
link the class specified to it as a parameter. newlnstance() indicates that a new instance of
the current class should be created.
• When the driver class is loaded into memory, it creates an instance of itself and registers
with java.sql.DriverManager as an available database driver.
Creating A Database Connection
Once the driver is loaded, a database connection needs to be established. A database URL identifies
a database connection and notifies the driver manager about which driver and data source is used.
Syntax: [For Database URL]
jdbc:<SubProtocol>:<SubName>
jdbc indicates that JDBC is being used to establish the database connection
SubProtocol is the name of the database the developer wants to connect to. Example mysql, oracle,
odbc and so on.
SubName is typically a logical name or alias, which provides additional information on how and
where to connect.
The following list represents the syntax for three common JDBC database URLs. Each type of
database driver requires different information within its URL:
MySQL jdbc:mysql://Server[:Port]/Database_Name MySQL Connector/JDBC Driver
To create a database connection, the JDBC connection method getConnection() of DriverManager
is used as follows:
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/tyit ", "root", "root");
The method is passed a specially formatted URL that specifies the database. The URL used is
dependent upon the JDBC driver implemented. It always begins with jdbc: protocol, but the rest
depends upon the particular vendor. It returns a class that implements java.sql .Connection.
Within getConnection(), DriverManager queries each registered driver until it locates one that
recognizes the specified database URL. Once the correct driver is located,DriverManager uses it
to create Connection object. While using JDBC, it is required to import java.sql package as the
driver manager, the connection objects and the other JDBC objects are contained in this package.
Executing Queries
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
17
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
After establishing database connection there should be some way to execute queries. There are
three ways of executing a query:
• Standard Statement
o The simplest way to execute a query is to use java.sql.Statement. To obtain a new
Statement object createStatement() of Connection object is used which is written
as follows:
o Statement stmt = con.createStatement();
o Statement objects are never instantiated directly.
o A query that returns data can be executed using executeQuery() of statement. this
method executes the statement and returns java.sql.ResultSet() that encapsulate the
retrived data.
o The following code spec defines RcsultSet object that encapsulates the retrived
data:
o ResultSet rs = stmt.executeQuery('SELECT * FROM Books');
The Servlet GUI and Database Example
(refer classroom notes for example, for CRUD operation using mysql database)
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
18
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
UNIT 2
Resquestdispatcher
Requestdispatcher Application
o index.html file: for getting input from the user.
o Login.java file: a servlet class for processing the response. If password is servet, it
will forward the request to the welcome servlet.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
1
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
index.html
Login.java (servlet)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Login extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
if(p.equals("servlet"){
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response);
}
else{
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
2
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);
}
}
WelcomeServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class WelcomeServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
}
}
COOKIES
Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client requests.
A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum
age, and a version number.
How Cookie works By default, each request is considered as a new request. In cookies technique, we add cookie with
response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent by the user,
cookie is added with request by default. Thus, we recognize the user as the old user.
Kinds/Types Of Cookies
The two types of cookies follow:
• Session cookies – Session cookies are stored in memory and are accessible as long as the user is using
the web application. Session cookies are lost when the user exits the web application. Such cookies are
identified by a session ID and are most commonly used to store details of a shopping cart.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
3
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
• Permanent cookies – Permanent cookies are used to store long-term information such as user preferences
and user identification information. Permanent cookies are stored in persistent storage and are not lost when
the user exits the application. Permanent cookies are lost when they expire.
public void setComment(String purpose): This method is used for setting up comments in the cookie. This is
basically used for describing the purpose of the cookie.
public String getComment(): Returns the comment describing the purpose of this cookie, or null if the cookie has no
comment.
public void setMaxAge(int expiry): Sets the maximum age of the cookie in seconds.
public int getMaxAge(): Gets the maximum age in seconds of this Cookie.
By default, -1 is returned, which indicates that the cookie will persist until browser shutdown.
public String getName(): Returns the name of the cookie. The name cannot be changed after creation.
By using setMaxAge () method we can set the maximum age for the particular cookie in seconds.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
4
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
• c.setMaxAge(1800);
We can send the cookie to the client browser through response.addCookie() method.
• response.addCookie(c);
Cookie c[]=request.getCookies();
//c.length gives the cookie count
for(int i=0;i<c.length;i++)
{
out.print("Name: "+c[i].getName()+" & Value: "+c[i].getValue());
}
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class setcookieservlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter())
{
Cookie[] allcookies = request.getCookies();
boolean cookiepresent = false;
int cookieindex = 0;
if(allcookies != null)
{
for (int i = 0; i < allcookies.length; i++)
{
if(allcookies[i].getName().equals("colour"))
{
cookiepresent = true;
cookieindex = i;
break;
}
}
}
if(cookiepresent==true)
{
out.print("<html><body bgcolor="+ allcookies[cookieindex].getValue() +"></body></html>");
}
else
{
System.out.println("cook not pre");
if(request.getParameter("color")!= null)
{
Cookie setcolour = new Cookie("colour", request.getParameter("color"));
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
5
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
setcolour.setMaxAge(60*60); // 1 hour
response.addCookie(setcolour);
}
else
{
out.print("<html><body><form method='post' action='setcookieservlet'>"
+ "<input type='text' name='color'><input type='submit'>"
+ "</form></body></html>");
}
}
}
catch(Exception x)
{
System.out.println(x.getMessage());
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
SESSION
What Are Sessions?
Session simply means a particular interval of time.
Session Tracking is a way to maintain state (data) of an user. It is also known as session management in servlet.
Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time user requests
to the server, server treats the request as the new request. So we need to maintain the state of an user to recognize to
particular user.
HTTP is stateless that means each request is considered as the new request. It is shown in the figure given below:
HttpSession interface
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
6
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
container creates a session id for each user.The container uses this id to identify the particular user.An object of
HttpSession can be used to perform two tasks:
1. bind objects
2. view and manipulate information about a session, such as the session identifier, creation time, and last
accessed time.
The HttpServletRequest interface provides two methods to get the object of HttpSession:
1. public HttpSession getSession():Returns the current session associated with this request, or if the request
does not have a session, creates one.
2. public HttpSession getSession(boolean create):Returns the current HttpSession associated with this request
or, if there is no current session and create is true, returns a new session.
• isNew() will be handy in quite a lot of situations. It returns true if the client does not know about the session
or if the client chooses not to join the session. getCreationTime() returns the time when this session was
created. getLastAccessedTime() returns the last time the client sent a request associated with this session.
▪ This method returns whether the session is new. A session is considered new if it has been
created by the server but the client has not yet acknowledged joining the session. For
example, if a server supports only cookie-based sessions and a client has completely
disabled the use of cookies, calls to the getSession() method ofHttpServletRequest always
return new sessions.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
7
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
▪ This method causes the session to be immediately invalidated. All objects stored in the
session are unbound.
▪ This method returns the time at which the session was created, as a long value that
represents the number of milliseconds since the epoch (midnight, January 1, 1970, GMT).
▪ This method returns the time at which the client last sent a request associated with
this session, as a long value that represents the number of milliseconds since the epoch.
The Servlet API has its own built-in support for session tracking. The HttpSession object provides this functionality. In
this section, I focus on four of the HttpSession's session tracking methods.
• The setAttribute() method binds a name/value pair to store in the current session. If the name already exists
in the session, it is replaced. The method signature for setAttribute() is listed as follows:
• public void setAttribute(String name, Object value)
• The getAttribute() method, which is used to get an object that is stored in the session. The getAttribute()
method takes a string representing the name that the desired object is bound to. Its signature is listed as
follows:
• public Object getAttribute(String name)
• The getAttributeNames() method returns an array of the current bound names stored in the session.
• public String[ ] getAttributeNames()
• removeAttribute() method. As its name suggests, it removes a binding from the current session. It takes a
string parameter representing the name associated with the binding. Its method signature is listed as follows:
• public void removeAttribute(String name)
• The form method attribute should be set to POST method and GET method can not be used
• The form enctype attribute should be set to multipart/form-data.
• The form action attribute should be set to a servlet file which would handle file uploading at backend server.
Following example is using UploadServlet servlet to upload file.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
8
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
• To upload a single file you should use a single <input .../> tag with attribute type="file". To allow multiple files
uploading, include more than one input tags with different values for the name attribute. The browser
associates a Browse button with each of them.
1. Following example depends on FileUpload, so make sure you have the latest version of commons-
fileupload.x.x.jar file in your classpath. You can download it from https://commons.apache.org/fileupload/.
2. FileUpload depends on Commons IO, so make sure you have the latest version of commons-io-x.x.jar file in
your classpath. You can download it from https://commons.apache.org/io/.
Uploading Files
• This class handles multiple files per single HTML widget, sent using multipart/mixed encoding type, as
specified by RFC 1867. Use parseRequest(HttpServletRequest) to acquire a list of FileItems
associated with a given HTML widget.
• How the data for individual parts is stored is determined by the factory used to create them; a given part may
be in memory, on disk, or somewhere else.
• methods of ServletFileUpload
▪ Utility method that determines whether the request contains multipart content.
note : add jar files as explained in classroom / or configure maven and web.xml
fileupload.html
<html>
<body>
<form action="fileupload" method="post" enctype = "multipart/form-data">
<input type="file" name="fiup">
<input type="submit">
</form>
</body>
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
9
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
</html>
fileupload.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class fileupload extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// refer https://commons.apache.org/proper/commons-fileupload/using.html
DiskFileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try
{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
File f1 = new File("f:\\testupload\\"+fi.getName());
fi.write(f1);
}
}
(response.getWriter()).print("Done");
}
catch(Exception ex)
{
System.out.println("oops check log for exception "+ex);
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
10
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
another way
javax.servlet.annotation.MultipartConfig is used to indicate that the servlet on which it is declared
expects requests to made using the multipart/form-data MIME type
@MultipartConfig
fileSizeThreshold
• The fileSizeThreshold attribute holds the file size in bytes after which the file will be
temporarily stored on disk.
• The default size is 0 bytes.
location
• The location attribute holds an absolute path to a directory on the file system.
• The location attribute does not support a path relative to the application context. this
location is used to store file temporarily while the parts are processed on when the size of
the file exceeds the specified fileSizeThreshold.
• The default location is ""
maxFileSize
• the maxFileSize attribute holds the maximum size allowed for multipart/form-data request,
in bytes
• The default size is unlimited.
maxRequestSize
• the maxRequestSize attribute holds the maximum size allowed for a multipart/form-data
request, in bytes.
• default size is unlimited
Html file
<!DOCTYPE html>
<html lang="en">
<head>
<title>File Upload</title>
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
11
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
Servlet file
@WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"})
@MultipartConfig //
public class FileUploadServlet extends HttpServlet
{
private final static Logger LOGGER =
Logger.getLogger(FileUploadServlet.class.getCanonicalName());
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try {
out = new FileOutputStream(new File(path + File.separator
+ fileName));
filecontent = filePart.getInputStream();
int read = 0;
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
12
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
13
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
• The method then creates a FileOutputStream and copies the file to the specified destination.
• The error-handling section of the method catches and handles some of the most common
reasons why a file would not be found.
Downloading Files
servlet file that reads the content of the file and writes it into the stream to send as a response. For this purpose, we
need to inform the server, so we are setting the content type as APPLICATION/OCTET-STREAM .
filedownload.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class filedownload extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// refer https://www.javatpoint.com/example-of-downloading-file-from-the-server-in-servlet
String downloadas = "mybook.pdf";
String absfilepath = "F:\\testupload\\iot1.pdf";
response.setContentType("APPLICATION/OCTET-STREAM"); // set the MIME type to be binary type
response.setHeader("Content-Disposition","attachment; filename=\"" + downloadas + "\""); // handles
the response based on the content type set in HTTP headers
FileInputStream fileInputStream = new FileInputStream(absfilepath); // Read the file on the server
PrintWriter out = response.getWriter();
int i;
while ((i=fileInputStream.read()) != -1)
{
out.write(i);
}
fileInputStream.close();
out.close();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
14
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
Web containers in application servers normally use a server thread per client request. To develop scalable web
applications, you must ensure that threads associated with client requests are never sitting idle waiting for a blocking
operation to complete.
Asynchronous Processing provides a mechanism to execute application-specific blocking operations in a new thread,
returning the thread associated with the request immediately to the container.
Even if you use asynchronous processing for all the application-specific blocking operations inside your service
methods, threads associated with client requests can be momentarily sitting idle because of input/output
considerations.
For example, if a client is submitting a large HTTP POST request over a slow network connection, the server can read
the request faster than the client can provide it. Using traditional I/O, the container thread associated with this request
would be sometimes sitting idle waiting for the rest of the request.
Java EE provides nonblocking I/O support for servlets and filters when processing requests in asynchronous mode.
The following steps summarize how to use nonblocking I/O to process requests and write responses inside service
methods.
refer : https://docs.oracle.com/javaee/7/tutorial/servlets013.htm
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HTML5andServlet31/HTML5andServlet%
203.1.html#section6
Method Description
void setWriteListener(WriteListener Associates this output stream with a listener object that contains callback
wl) methods to write data asynchronously. You provide the write listener object as
an anonymous class or use another mechanism to pass the output stream to the
write listener object.
boolean isReady() Returns true if data can be written without blocking.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
15
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
void onError(Throwable t)
NIO allows you to manage multiple channels (network connections or files) using only a single
(or few) threads, but the cost is that parsing the data might be somewhat more complicated than
when reading data from a blocking stream.
If you need to manage thousands of open connections simultanously, which each only send a little
data, for instance a chat server, implementing the server in NIO is probably an advantage.
Similarly, if you need to keep a lot of open connections to other computers, e.g. in a P2P network,
using a single thread to manage all of your outbound connections might be an advantage. This one
thread, multiple connections design is illustrated in this diagram:
Example:
add <async-supported>true</async-supported> in web.xml servlet block
<servlet>
<servlet-name>nonbio</servlet-name>
<servlet-class>nonbio</servlet-class>
<async-supported>true</async-supported>
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
16
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
</servlet>
nonbio.java (servlet)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class nonbio extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException
{
doPost(req, res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException
{
final AsyncContext context = req.startAsync(); // set async
final ServletInputStream sis = req.getInputStream();
sis.setReadListener(new ReadListener() {
byte buffer[] = new byte[4*1024];
StringBuilder sbuilder = new StringBuilder(); // mutable string
public void onDataAvailable() throws IOException
{
System.out.println(".onDataAvailable()");
do {
int length = sis.read(buffer);
sbuilder.append(new String(buffer, 0, length));
} while(sis.isReady());
System.out.println(sbuilder);
}
public void onAllDataRead() throws IOException
{
System.out.println(".onAllDataRead()");
context.complete(); // it will stop async content and process will stop listening;
}
public void onError(Throwable t)
{
System.out.println(".onError()");
}
});
}
}
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
17
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
UNIT 3
Introduction To Java Server Pages
Disadvantages of JSP
• As JSP pages are translated to servlets and compiled, it is difficult to trace errors occurred
in JSP pages.
• JSP pages require double the disk space to hold the JSP page. (Because JSP pages are
translated into class files, the server has to store the resultant class files with the JSP pages)
• JSP pages require more time when accessed for the first time as they are to be
compiled on the server.
• Simple task are hard to code.
• Difficult in looping in tags many times nesting of brackets make things complex.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
1
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
JSP is a webpage scripting language that can Servlets are Java programs that are already
generate dynamic content. compiled which also creates dynamic web
content.
JSP run slower compared to Servlet as it takes Servlets run faster compared to JSP.
compilation time to convert into Java Servlets.
It’s easier to code in JSP than in Java Servlets. Its little much code to write here.
In MVC, jsp act as a view. In MVC, servlet act as a controller.
JSP are generally preferred when there is not servlets are best for use when there is more
much processing of data required. processing and manipulation involved.
The advantage of JSP programming over There is no such custom tag facility in
servlets is that we can build custom tags which servlets.
can directly call Java beans.
We can achieve functionality of JSP at client There are no such methods for servlets.
side by running JavaScript at client side.
• New jsp is translated into java class by the jsp engine, which is child of the web server, by
having its embeded java code compiled into a servlet.
• When servlet is run by the jvm its init() is called first.
• Then individual request are sent to the servlet service() where their response is assembled.
• After that servlet uses response object and send the output to the client in html form.
• A JSP page is very similar to an HTML or a XML page. Every JSP page holds text marked
with a variety of tags. A standard JSP page is not a valid XML page however there is a
separate JSP tag syntax, which allows using JSP tags within XML documents.
• In jsp, [when compared to regular HTML] the special JSP tags are not processed by the
browser instead they are processed by the Web server, allowing the page content to change
dynamically, JSP thus functions in the same manner in which other dynamic page
generation systems such as ASP or PhP functions.
Comments
This JSP comment tag tells the JSP container to ignore the comment part from compilation. That
is, the commented part of source code is not considered for the content parsed for ‘response’.
1. One-liner Comment: <% //This is the one line comment. %>
2. Using /* */ comment tags inside the <% %> tags: <% /* %> This is also considered as
comment <% */ %>
JSP Document
A JSP document is an XML document and therefore must comply with the XML standard.
Fundamentally, this means that a JSP document must be well formed, meaning that each start tag
must have a corresponding end tag and that the document must have only one root element. In
addition, JSP elements included in the JSP document must comply with the XML syntax.
For detail study (visit : http://www.huihoo.org/code/jsp/)
Much of the standard JSP syntax is already XML-compliant, including all the standard actions.
Syntax Standard Syntax XML Syntax
Elements
Comments <%--.. --%> <!-- .. -->
Declarations <%! ..%> <jsp:declaration> .. </jsp:declaration>
Directives <%@ include .. %> <jsp:directive.include .. />
<%@ page .. %> <jsp:directive.page .. />
<%@ taglib .. %> xmlns:prefix="tag library URL"
Expressions <%= ..%> <jsp:expression> .. </jsp:expression>
Scriptlets <% ..%> <jsp:scriptlet> .. </jsp:scriptlet>
Session Attribute
Syntax: [In a regular JSP page]
• <%@ page session="true" %>
Syntax: [In an XML based JSP page]
• <jsp:directive.page session=”true" />
Taglib directive
Syntax: [In a regular JSP page]
• <%@ taglib uri='<TaglibraryURI>" prefix="<TagPrefix>" %>
Syntax: [In an XML based JSP page]
• <jsp:directive.taglib uri="<TaglibraryURI>" prefix="<TagPrefix>" />
JSP Elements
Declaration
• A declaration tag is a piece of Java code for declaring variables, methods and classes. If we
declare a variable or method inside declaration tag it means that the declaration is made
inside the servlet class but outside the service method.
• We can declare a static member, an instance variable (can declare a number or string) and
methods inside the declaration tag.
<%! int count =10; %>
<% out.println("The Number is " +count); %>
Scriptlet
• Scriptlet tag allows to write Java code into JSP file.
• JSP container moves statements in _jspservice() method while generating servlet from jsp.
• For each request of the client, service method of the JSP gets invoked hence the code inside
the Scriptlet executes for every request.
• A Scriptlet contains java code that is executed every time JSP is invoked.
<% int num1=10;
int num2=40;
int num3 = num1+num2;
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
5
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
Expression
• Expression tag evaluates the expression placed in it.
• It accesses the data stored in stored application.
• It allows create expressions like arithmetic and logical.
• It produces scriptless JSP page.
<% out.println("The expression number is "); %>
<% int num1=10; int num2=10; int num3 = 20; %>
<%= num1*num2+num3 %>
Action Elements
• These actions use constructs in XML syntax to control the behavior of the servlet engine.
You can dynamically insert a file, reuse JavaBeans components, forward the user to another
page, or generate HTML for the Java plugin.
• There is only one syntax for the Action element, as it conforms to the XML standard –
• <jsp:action_name attribute = "value" />
Common Attributes
There are two attributes that are common to all Action elements: the idattribute and
the scope attribute.
• Id attribute
o The id attribute uniquely identifies the Action element, and allows the action to be
referenced inside the JSP page. If the Action creates an instance of an object, the id
value can be used to reference it through the implicit object PageContext.
• Scope attribute
o This attribute identifies the lifecycle of the Action element. The id attribute and the
scope attribute are directly related, as the scope attribute determines the lifespan of
the object associated with the id. The scope attribute has four possible values: (a)
page, (b)request, (c)session, and (d) application.
Forwarding JSP Page to Another Page, Passing Parameters for other Actions
The <jsp:forward> Action
The forward action terminates the action of the current page and forwards the request to another
resource such as a static page, another JSP page, or a Java Servlet.
Following is the syntax of the forward action −
<jsp:forward page = "Relative URL" />
Following table lists out the required attributes associated with the forward action −
S.No. Attribute & Description
1 page
Should consist of a relative URL of another resource such as a static page, another
JSP page, or a Java Servlet.
Example
Let us reuse the following two files (a) hello.jsp and (b) main.jsp as follows –
<center>
<h2>The include action Example</h2>
<jsp:forward page = "date.jsp" >
<jsp:param name=”username” value=”siddhesh”/>
</jsp:forward>
</center>
</body>
</html>
Loading a Javabean
The <jsp:useBean> Action
The useBean action is quite versatile. It first searches for an existing object utilizing the id and
scope variables. If an object is not found, it then tries to create the specified object.
The simplest way to load a bean is as follows −
<jsp:useBean id = "name" class = "package.class" />
Once a bean class is loaded, you can use jsp:setProperty and jsp:getProperty actions to modify
and retrieve the bean properties.
Following table lists out the attributes associated with the useBean action −
S.No. Attribute & Description
1 class
Designates the full package name of the bean.
2 type
Specifies the type of the variable that will refer to the object.
3 beanName
Gives the name of the bean as specified by the instantiate () method of the
java.beans.Beans class.
Let us now discuss the jsp:setProperty and the jsp:getProperty actions before giving a valid
example related to these actions.
In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated or
an existing bean was found.
A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean element,
as given below −
The getProperty action is used to retrieve the value of a given property and converts it to a string,
and finally inserts it into the output.
The getProperty action has only two attributes, both of which are required. The syntax of the
getProperty action is as follows –
Following table lists out the required attributes associated with the getProperty action –
S.No. Attribute & Description
1 Name
The name of the Bean that has a property to be retrieved. The Bean must have been
previously defined.
2 Property
The property attribute is the name of the Bean property to be retrieved.
• Delivering dynamic website content to a client browser requires interacting with Java
objects on the Web server. Java scripting elements provide a great deal of power and
flexibility to the developer to achieve this. In addition to permitting such
intercommunication the JSP engine exposes a number of internal Java objects to the
developer. These objects do not need to be declared or instantiated by the developer, but
are provided by the JSP engine in its implementation and execution.
• Scripting elements can access predefined variables assigned by the JSP engine and using
their content reference implicit objects to access request and application data. These objects
are instances of classes defined by the Servlet and JSP specifications.
• All such implicit objects are available only to scriptlets or expressions. They are not
available in declarations. Declarations translate into class variables or method declarations.
Implicit Ejects are only available in _jspService() of the generated Servlet.
Following table lists out the nine Implicit Objects that JSP supports −
S.No. Object & Description
1 request
This is the HttpServletRequest object associated with the request.
2 response
This is the HttpServletResponse object associated with the response to the client.
3 out
This is the PrintWriter object used to send output to the client.
4 session
This is the HttpSession object associated with the request.
5 application
This is the ServletContext object associated with the application context.
6 config
This is the ServletConfig object associated with the page.
7 pageContext
This encapsulates use of server-specific features like higher performance JspWriters.
8 page
This is simply a synonym for this, and is used to call the methods defined by the
translated servlet class.
9 Exception
The Exception object allows the exception data to be accessed by designated JSP.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
10
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
11
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
12
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
following conditional tag is supplied with an EL expression that compares the number of items in
the session-scoped bean named cart with 0.
Immediate evaluation
• Immediate evaluation means that the JSP engine evaluates the expression and returns the
result immediately when the page is first rendered.
• Those expressions that are evaluated immediately use the ${} syntax
• ${9+10}
Deferred evaluation
• Deferred evaluation means that the technology using the expression language can employ
its own machinery to evaluate the expression sometime later during the page’s life cycle,
whenever it is appropriate to do so.
• Expressions whose evaluation is deferred use the #{}
• <h:inputText id="name" value="#{customer.name}" />
Example Expressions
EL Expression Result
${1 > (4/2)} false
${4.0 >= 3} true
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
13
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
Referencing Objects
• A top-level identifier (such as customer in the expression customer.name) can refer to the
following objects:
o Lambda parameters
o EL variables
o Managed beans
o Implicit objects
o Classes of static fields and methods
An enum constant is a special case of a static field, and you can reference such a constant
directly. For example, consider this enum class:
public enum Suit {hearts, spades, diamonds, clubs}
In the following expression, in which mySuit is an instance of Suit, you can compare
suit.hearts to the instance:
${mySuit == suit.hearts}
o ${customer.address["street"]}
Referencing Literals
o The EL defines the following literals:
o Boolean: true and false
o Integer: As in Java
o Floating-point: As in Java
o String: With single and double quotes; " is escaped as \", ' is escaped as \', and \is escaped
as \\
o Null: null
Lambda Expressions
o A lambda expression is a value expression with parameters. The syntax is similar to that
of the lambda expression in the Java programming language, except that in the EL, the
body of the lambda expression is an EL expression.
o A lambda expression uses the arrow token (->) operator. The identifiers to the left of the
operator are called lambda parameters. The body, to the right of the operator, must be an
EL expression. The lambda parameters are enclosed in parentheses; the parentheses can be
omitted if there is only one parameter. Here are some examples:
o (p1, p2) -> System.out.println("Multiple parameters: " + p1 + ", " + p2);
• You operate on collection objects using method calls to the stream of elements derived
from the collection. Some operations return another stream, which allows additional
operations. Therefore, you can chain these operations together in a pipeline.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
15
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
JSTL allows programming JSP pages using tags, rather than the scriptlets that most JSP
developers are already comfortable with. JSTL does nearly everything that the regular
scriptlet does. JSTL was introduced to allow the JSP developers to create Web applications
Using tags rather than the Java code.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
16
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
• jstl tags are XML based tags, they cleanly and consistently blend into a pages HTML
markup tags
• Easy to call getter and setter
• No type casting require in request and response object
• JSTL tags are easier to use effectively as they do not require any knowledge of
programming or Java. This is very useful for the non programming or the Inexperience
Disadvantages Of JSTL
• JSTL puts die processing burden to the server. Java Scriptlet and the tag libraries both are
compiled into a Servlet, which is then executed by the Servlet engine. Java code
embedded inScriptlets is pretty much just copied into the Servlet. But, on the other hand,
JSTL tags causes much more code to be added to the Servlet. In some cases this is not
measurable, but it should be considered
• Scriptlets are more powerful than the JSTL tags. If anything has to be done in the JSP
pages, then the developer might want to stick to the embedded Java code. JSTL provides
a powerful set of reusable libraries to application developers. However, JSTL cannot do
everything that the Java code spec can do
Tag libraries
• JSTL includes a wide variety of tags that fit into discrete functional areas. To reflect this,
as well as to give each area its own namespace, JSTL is exposed as multiple tag libraries.
The URIs for the libraries are as follows:
o Core: http://java.sun.com/jsp/jstl/core
o XML: http://java.sun.com/jsp/jstl/xml
o Internationalization: http://java.sun.com/jsp/jstl/fmt
o SQL: http://java.sun.com/jsp/jstl/sql
o Functions: http://java.sun.com/jsp/jstl/functions
JSTL Tags
Area Subfunction Prefix
Flow control
URL management
Miscellaneous
XML Core x
Flow control
Transformation
Message formatting
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
17
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
Number and date formatting
String manipulation
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
18
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
19
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
fmt:formatNum It is used to format the numerical value with specific format or precision.
ber <c:set var="Amount" value="9850.14115" />
<fmt:formatNumber type="number" groupingUsed="true" value="${Amou
nt}" /></p>
fmt:parseDate It parses the string representation of a time and date.
<c:set var="date" value="12-08-2016" />
<fmt:parseDate value="${date}" var="parsedDate" pattern="dd-MM-
yyyy" />
<p><c:out value="${parsedDate}" /></p>
sql:setDataSource It is used for creating a simple data source suitable only for prototyping.
<sql:setDataSource var="db" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/test"
user="root" password="1234"/>
sql:query It is used for executing the SQL query defined in its sql attribute or the
body.
<sql:setDataSource var="db" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/test"
user="root" password="1234"/>
sql:update It is used for executing the SQL update defined in its sql attribute or in the
tag body.
<sql:update dataSource="${db}" var="count">
INSERT INTO Students VALUES (154,'Nasreen', 'jaha', 25);
</sql:update>
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
21
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
UNIT 4
Introduction To Enterprise Javabeans
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
1
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
2
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
3
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
4
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
o JAR files that contain enterprise bean classes packaged within a WAR module are
not considered EJB JAR files, even if the bundled JAR file conforms to the format
of an EJB JAR file. The enterprise beans contained within the JAR file are
semantically equivalent to enterprise beans located in the WAR module's WEB-
INF/classesdirectory, and the environment namespace of all the enterprise beans
are scoped to the WAR module.
o A stateless session bean does not maintain a conversational state with the client.
When a client invokes the methods of a stateless bean, the instance of bean variables
may contain a state specific to that client only for the duration of a method
invocation.
o Once the method is finished, the client-specific state should not be retained i.e. the
EJB container destroys a stateless session bean.
o Stateless session beans can support multiple clients, they provide the better
scalability for applications that require large numbers of clients.
o Life Cycle of a Stateless Session Bean:
o Since the Stateless session bean does not passivates across method calls therefore a
stateless session bean includes only two stages. Whether it does not exist or ready for
method invocation. A stateless session bean starts its life cycle when the client first
obtains the reference of the session bean. For this, the container performs the
dependency injection before invoking the annotated @PreConstruct method if any
exists. After invoking the annotated @PreConstruct method the bean will be ready to
invoke its method by the client
o The container calls the annotated @PreDestroy method while ending the life
cycle of the session bean. After this, the bean is ready for garbage collection.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
6
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
o For example, consider a customer using a debit card at an ATM machine. The
ATM could perform various operations like checking an account balance,
transferring funds, or making a withdrawal. These operations could be
performed one by one, by the same customer. So the bean needs to keep track
its state for each of these operations to the same client. Thus Stateful session
beans has the extra overhead for the server to maintain the state than the
stateless session bean.
o Life Cycle of a Stateful Session Bean:
o A Stateful session bean starts its life cycle when the client first gets the
reference of a stateful session bean. Before invoking the method annotated
@PostConstruct the container performs any dependency injection after this the
bean is ready.
o The container may deactivate a bean while in ready state (Generally the
container uses the least recently use algorithm to passivates a bean). In the
passivate mechanism the bean moves from memory to secondary memory.
o The container invokes the annotated @PrePassivate method before passivating
the bean.
o If a client invokes a business method on the passivated bean then the container
invokes the annotated @PostActivate method to let come the bean in the ready
state.
3) Singleton Session Bean: One instance per application, it is shared between clients and
supports concurrent access.
o A Singleton Session Bean maintains the state of the bean for the complete
lifecycle of the application.
o Singleton Session Beans are similar to Stateless Session Beans but only one
instance of the Singleton Session Bean is created in the whole application and
does not terminates until the application is shut down.
o The single instance of the bean is shared between multiple clients and can be
concurrently accessed.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
7
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
Accessing Interfaces
o Accessing Local Enterprise Beans Using the No-Interface View
o Client access to an enterprise bean that exposes a local, no-interface view is
accomplished through either dependency injection or JNDI lookup. To obtain a
reference to the no-interface view of an enterprise bean through dependency
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
8
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
injection, use the javax.ejb.EJB annotation and specify the enterprise bean’s
implementation class:
▪ @EJB
▪ ExampleBean exampleBean;
▪ To obtain a reference to the no-interface view of an enterprise bean through
JNDI lookup, use
the javax.naming.InitialContext interface’s lookupmethod:
▪ ExampleBean exampleBean = (ExampleBean)
▪ InitialContext.lookup("java:module/ExampleBean");
▪ Clients do not use the new operator to obtain a new instance of an enterprise
bean that uses a no-interface view.
o Accessing Local Enterprise Beans That Implement Business Interfaces
o Client access to enterprise beans that implement local business interfaces is
accomplished through either dependency injection or JNDI lookup.
o To obtain a reference to the local business interface of an enterprise bean through
dependency injection, use the javax.ejb.EJB annotation and specify the enterprise
bean’s local business interface name:
▪ @EJB
▪ Example example;
▪ To obtain a reference to a local business interface of an enterprise bean
through JNDI lookup, use
the javax.naming.InitialContext interface’s lookupmethod:
▪ ExampleLocal example = (ExampleLocal)
▪ InitialContext.lookup("java:module/ExampleLocal");
Lifecycle of Enterprise Beans((refer previous topics in Types of Session Bean ), Packaging Enterprise
Beans(refer previous topics Packaging Enterprise Beans)
Example of Stateful Session Bean, Example of Stateless Session Bean, Example of Singleton
Session Beans. (refer classroom notes)
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
9
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
o Like a stateless session bean, a message-driven bean is never passivated, and it has only
two states: nonexistent and ready to receive messages.
o At the end of the life cycle, the container calls the ejbRemove method. The bean's instance
is then ready for garbage collection.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
10
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
Interceptors
Adding An Interceptor To An Enterprise Bean EJB 3.0 provides specification to intercept business
methods calls using methods annotated with @AroundInvoke annotation. An interceptor method
is called by ejbContainer before business method call it is intercepting. Following is the example
signature of an interceptor method.
Defining An Interceptor
• Interceptors can be defined in Java as an method interceptor or a class interceptor. The
preferred way to define in Java code is by using meta-data annotations. They can be defined
in the application descriptor as well, but, in that case they are not portable across Java EE
servers. Some of the meta-data annotations found in the javax.interceptor package
are: @AroundInvoke, @AroundTimeout, @PostConstruct, and @PreDestroy.
AroundInvoke Method
@AroundInvoke
public Object methodInterceptor(InvocationContext ctx) throws Exception {
System.out.println("*** Intercepting call to LibraryBean method: "
+ ctx.getMethod().getName());
return ctx.proceed();
}
• Defines an interceptor method that interposes on business methods. May be applied to any
non-final, non-static method with a single parameter of type InvocationContext and return
type Object of the target class (or superclass) or of any interceptor class.
• An AroundInvoke method can invoke any component or resource that the method it is
intercepting can invoke.
• AroundInvoke method invocations occur within the same transaction and security context
as the method on which they are interposing.
• AroundInvoke methods may throw any exceptions that are allowed by the throws clause
of the method on which they are interposing. They may catch and suppress exceptions and
recover by calling InvocationContext.proceed().
• public interface InvocationContext
• Exposes context information about the intercepted invocation and operations that enable
interceptor methods to control the behavior of the invocation chain.
Applying Interceptor
Intercepted Stateless EJB
@Interceptors ({BusinessInterceptor.class})
@Stateless
public class LibraryBean implements LibraryBeanRemote {
//implement business method
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
11
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
Types of interceptors
• Default − Default interceptor is invoked for every bean within deployment.Default
interceptor can be applied only via xml (ejb-jar.xml).
• Class − Class level interceptor is invoked for every method of the bean. Class level
interceptor can be applied both by annotation of via xml(ejb-jar.xml).
• Method− Method level interceptor is invoked for a particular method of the bean.
Method level interceptor can be applied both by annotation of via xml(ejb-jar.xml).
Build and Run the Web Application (REFER CLASSROOM NOTES AND VIDEO TUTORIAL)
Naming services
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
12
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
naming service maintains a set of bindings. Bindings relate names to objects. All objects
in a naming system are named in the same way (that is, they subscribe to the same naming
convention). Clients use the naming service to locate objects by name.
There are a number of existing naming services
• COS (Common Object Services) Naming: The naming service for CORBA
applications; allows applications to store and access references to CORBA objects.
• DNS (Domain Name System): The Internet's naming service; maps people-friendly
names (such as www.etcee.com) into computer-friendly IP (Internet Protocol)
addresses in dotted-quad notation (207.69.175.36). Interestingly, DNS is
a distributed naming service, meaning that the service and its underlying database is
spread across many hosts on the Internet.
• LDAP (Lightweight Directory Access Protocol): Developed by the University of
Michigan; as its name implies, it is a lightweight version of DAP (Directory Access
Protocol), which in turn is part of X.500, a standard for network directory services.
Currently, over 40 companies endorse LDAP.
• NIS (Network Information System) and NIS+: Network naming services developed by
Sun Microsystems. Both allow users to access files and applications on any host with
a single ID and password.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
13
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
Java Naming and Directory Interface [JNDI] is a part of the Java platform. It is a Java API for a
directory service that allows Java software clients to discover and look up data and objects via a
name.
The API provides:
• A mechanism to bind an object to a name
• A directory lookup interface that allows general queries
• An event interface that allows clients to determine when directory entries have been
modified
• LDAP extensions to support the additional capabilities of an LDAP service
Basic Lookup
• JNDI organizes its names into a hierarchy.
• A name can be any string such as org.ejb.ConverterBean or can also be an object that
supports the Name interface. A string is the most common way to name an object.
• A name is bound to an object in the directory by storing either the object or a reference to
the object in the directory service identified by the name.
• The user of the JNDI client API will first be required to create an initial context to the
naming or directory service to connect to.
• This initial context establishes a connection with the naming or directory service when it
is constructed with a set of properties that describes:
o The specific naming or directory service provider library to use
o The URL of the naming or directory service process
o A user name and credentials
• JNDI API defines a context that specifies where to look for an object. The initial context
is typically used as a starting point for all naming and directory operations.
• An initial context must be created using the specific implementation and extra parameters
required by the implementation. The initial context will be used to look up a name.
• After an initial context to a naming or directory service is established, the root context or
sub-context reference is used, which performs various operations on the context depending
on the type of context.
• Naming contexts can be used for binding and unbinding names and objects, list names and
name bindings and lookup object references of named objects.
• Using the lookup() method of the InitialContext object the named object of the
ShoppingCartRemote class is retrieved.
• The named object that is returned by the lookup() method is type casted to
ShoppingCartRemote and then assigned to the ShoppingCartRemote class object created
earlier named cart.
• The java:module namespace is used to lookup local enterprise beans within the
same module.
• Syntax:
• java:module/<Enterprise Bean Name>/[<Interface Name>]
• Resource Injection
o The javax.annotation.Resource annotation is used to declare a reference to a
resource. @Resource can be used in a class, a field or a method.
o The container injects the resource referred to by @Resource into the component
either at runtime or when the component is initialized, depending on whether
field/method injection or class injection is used.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
15
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
o With field and method-based injection, the container injects the resource when the
application is initialized. For class-based injection, the resource is looked up by the
application at runtime.
@Resource
private MessageDrivenContext mdc;
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
16
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
UNIT 5
Persistence, Object/Relational Mapping And JPA
• Data is an important asset to any computer application. All computer applications require
that a person or another computer access their data. This data is used in different ways.
• Data can be
o Read-only
o Read-write
o Read for update over multiple requests
o Modified through batch updates
o Used in bulk data retrieval
• If the application does not preserve data when it was powered off, the application is of little
or rather no practical use.
• Hence, it is required to make the precious data live longer than the application. This is
where Persistence comes in.
What Is Persistence?
• Most business applications require that data must be persistent. Data can be labeled as
persistent only when it manages to survive day to day problems such as system crashes and
network failures.
• In enterprise application architecture, data persistence is implemented as:
o Having data stored outside an application's active memory, known as persistent data
store, typically a relational database or an object database or a flat file system
Having a rollback system, where, in case of system failure, the state of the data is
rolled back to its last known valid data state.
o Large amounts of data should not be stored in an HTTP session, instead a database
should be considered.
o The type of database that is chosen also plays an important influence on the
architecture and design.
Persistence In Java
• Persistence in Java usually means storing data in a relational database using SQL.
• In Java, persistence is accomplished by storing data in a Relational Database Management
• System [RDBMS]. SQL is used to get data in and out of the relational database.
• Java DataBase Connectivity [JDBC] - The Java API is used to connect to the RDBMS and
fire SQL statements.
• Object Oriented Programming is based on OBJECTS that represent the business model
[the real world]. Objects are easily traversed through relationship graphs using inheritance,
associations.
• Object Persistence deals with persistence in object oriented programs such as Java. It
means determining how objects and their relationships are persisted in a relational
database.
• Object persistence is about
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
1
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
Architecture of JPA
• Persistence
o The javax.persistence.Persistence class contains static helper methods to obtain
EntityManagerFactory instances in a vendor-neutral fashion.
• EntityManagerFactory
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
5
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
o The EntityManagerFactory is created with the help of a Persistence Unit during the
application start up. It serves as a factory for spawning EntityManager objects when
required.
o Typically, it is created once [one EntityManagerFactory object per database] and
kept alive for later use.
• EntityManager
o The EntityManager object [javax.persistence.EntityManager] is lightweight and
inexpensive to create. It provides the main interface to perform actual database
operations.
o All the POJOs i.e. persistent objects are saved and retrieved with the help of an
EntityManager object.
o Typically, EntityManager objects are created as needed and destroyed when not
required.
o Each EntityManager manages a set of persistent objects and has APIs to insert new
objects and delete existing ones.
• Entity
o Entites are persistent objects that represent datastore records.
• EntityTransaction
o A Transaction represents a unit of work with the database.
o Any kind of modifications initiated via the EntityManager object are placed within
a transaction. An EntityManager object helps creating an EntityTransaction object.
o Transaction objects are typically used for a short time and are closed by either
committing or rejecting.
• Query
o Persistent objects are retrieved using a Query object.
o Query objects [javax.persistence.Query] allows using SQL or Java Persistence
Query Language [JPQL] queries to retrieve the actual data from the database and
create objects.
• Criteria
o Criteria API is a non-string-based API for the dynamic construction of object-based
queries [javax.persistence.criteria].
o Just like JPQL static and dynamic queries, criteria query objects are passed to the
EntityManager's createQuery() method to create Query objects and then executed
using the methods of the Query API.
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
6
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
7
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
Software Requirements
• Java Development Kit
• NetBeans IDE [The development IDE]
• MySQL Community Server [The database server]
• JDBC Driver for MySQL
• Sun Glassfish Enterprise Server v3 EclipseLink [Default ORM that comes bundled]
public Emp(){}
public Integer getEmpid() {
return empid;
}
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
9
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
• A Persistence Unit [PU] allows logically grouping a set of related entity beans. Each
persistence unit is configured with a provider along with its data source and some set of
entities.
• The Persistence unit is defined using the persistence.xml file.
• JPA uses the persistence.xml file to create the connection and setup the required
environment. This file is used to provide the information which is necessary for making
database connections. In this file the JNDI data source that indicates the database driver,
the database location, the user and the password is specified.
2. Hover new
3. Click others
4. Click persistence category
5. Click file type persistence unit
6. Uncheck (use java transaction api) and select (none)
7. Select (new data source) from data source
8. Give jndi a name (empjndi)
9. Select (new database connection) from database connection
10. Select mysql connector from driver
11. Click next
12. Write (jpatest) in database textbox
13. Username : root
14. Password: leave it blank
15. Check remember password
16. The jdbc url should look like
(jdbc:mysql://localhost:3306/jpatest?zeroDateTimeBehavior=convertToNull)
Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="JPATESTPU" transaction-type="RESOURCE_LOCAL">
<non-jta-data-source>java:app/empjndi</non-jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>
• RESOURCE_LOCAL as the transaction type of the unit This transaction type will be used
when using JPA outside a Java EE container.
• A non-JTA data source [Local] only supports local transactions that are limited to the
process/server where they begin.
• <exclude-unlisted-classes> If this attribute is set to true, the main jar file will not be
scanned for annotated classes. Only explicit classes will be part of the persistence unit.
Glassfish-resources.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//GlassFish.org//DTD GlassFish Application Server
3.1 Resource Definitions//EN" "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
<jdbc-connection-pool allow-non-component-callers="false" associate-with-
thread="false" connection-creation-retry-attempts="0" connection-creation-retry-interval-
in-seconds="10" connection-leak-reclaim="false" connection-leak-timeout-in-
seconds="0" connection-validation-method="auto-commit" datasource-
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
11
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" fail-all-
connections="false" idle-timeout-in-seconds="300" is-connection-validation-
required="false" is-isolation-level-guaranteed="true" lazy-connection-association="false"
lazy-connection-enlistment="false" match-connections="false" max-connection-usage-
count="0" max-pool-size="32" max-wait-time-in-millis="60000"
name="mysql_jpatest_rootPool" non-transactional-connections="false" pool-resize-
quantity="2" res-type="javax.sql.DataSource" statement-timeout-in-seconds="-1" steady-
pool-size="8" validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
<property name="serverName" value="localhost"/>
<property name="portNumber" value="3306"/>
<property name="databaseName" value="jpatest"/>
<property name="User" value="root"/>
<property name="Password" value=""/>
<property name="URL"
value="jdbc:mysql://localhost:3306/jpatest?zeroDateTimeBehavior=convertToNull"/>
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
</jdbc-connection-pool>
<jdbc-resource enabled="true" jndi-name="java:app/empjndi" object-type="user" pool-
name="mysql_jpatest_rootPool"/>
</resources>
Creating JSPS
Cud.jsp
<%@page import="pojo.Emp"%>
<%@page import="javax.persistence.Persistence"%>
<%@page import="javax.persistence.EntityTransaction"%>
<%@page import="javax.persistence.EntityManager"%>
<%@page import="javax.persistence.EntityManagerFactory"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<body>
<%!
private EntityManagerFactory emf;
private EntityManager em;
private EntityTransaction tx;
%>
<%
emf = Persistence.createEntityManagerFactory("JPATESTPU"); // read xml for
configuration
em = emf.createEntityManager();
// access pojo
Emp emp = new Emp();
emp.setEmpname("siddhesh");
emp.setEmpsname("zele");
// INSERT DATA
tx = em.getTransaction();
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
12
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
tx.begin();
em.persist(emp);
tx.commit();
em.close();
%>
</body>
</html>
• The EntityManagerFactory is an in-memory representation of a Persistence Unit. The
EntityManagerFactory finds and processes the persistence meta information
• This entity manager can then be used to work with persistent entities. An EntityManager
provides methods for persisting, merging, removing, retrieving and querying objects
• EntityTransaction is used as the transaction service.
• Using the Persistence object's createEntityManagerFactory() method, the
EntityManagerFactory is built. This references the Persistence Unit [persistence.xml].
• The createEntityManager() method of the EntityManagaerFactory interface creates an
instance of EntityManager. This instance represents the primary interface to the ORM
framework.
• Beginning A Transaction
• The begin() method of EntityTransaction starts a new resource transaction and returns
void.
• The persist() method allows saving the information to the database table. When an object
is passed to the persist() method, JPA reads the state of the variables of that object and
executes the required SQL query.
• tx.commit(); Finally, the transaction is committed. This method flushes the associated
Entity Manager and ends the unit of work [ends a transaction].
read.jsp
<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>
<%@page import="pojo.Emp"%>
<%@page import="javax.persistence.Persistence"%>
<%@page import="javax.persistence.EntityManager"%>
<%@page import="javax.persistence.EntityManagerFactory"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<body>
<%!
private EntityManagerFactory emf;
private EntityManager em;
private List<Emp> emps; // for storing employees
%>
<%
emf = Persistence.createEntityManagerFactory("JPATESTPU"); // read xml for
configuration
em = emf.createEntityManager();
Emp emp;
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
13
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
• java.util.List: Is an ordered collection. The user of this interface has precise control over
where in the list each element is inserted. The user can access elements by their integer
index [position in the list] and search for elements in the list
• java.util.Iterator: Is used to sequence over a collection of objects. Iterator allows the caller
to remove elements from the underlying collection during the iteration with well-defined
semantics
Introduction To Hibernate
What Is Hibernate?
• Hibernate is the latest Open Source persistence technology
• free open source [distributed under the GNU Lesser General Public License]
Object/Relational Mapping [ORM] library for the Java programming language
• It provides a framework for mapping an object oriented DOMAIN model to a traditional
Relational Database.
• Its primary feature is mapping from:
o Java Classes -> Database Tables
o Java Data Types -> SQL Data Types
• Hibernate also allows querying and retrieving data. It generates all the necessary SQL calls
to achieve this and thereby, relieves the developers from manual result set handling and
object conversion.
Why Hibernate?
• It eliminates the need for repetitive SQL
• It allows working with classes and objects instead of queries and result sets which makes
the approach more Object Oriented and less Procedural
• Handles all Create, Read, Update, Delete [CRUD] operations
• Brings in portability across databases
• Reduces the development time by supporting inheritance, polymorphism, composition and
the Java Collection framework
• Hibernate's Dual Layer Cache Architecture [HDCLCA] delivers thread safeness, non-
blocking data access, session level cache, optional second-level cache and optional query
cache.
• Supports connection pooling
• Supports wide range of database
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
15
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
• Hibernate uses the database and configuration data to provide persistence services
Persistent Objects] to the application.
• Hibernate then allows performing the SELECT, INSERT, UPDATE and DELETE
operations on the database tables by automatically creating the required SQL queries and
firing them using the JDBC APIs.
Components Of Hibernate
• Connection Management
o Hibernate's Connection management service provides efficient management of the
database connections.
• Transaction Management
o Transaction management service provides the ability to execute more than one.
database statements at a time.
• Object Relational Mapping
o Object relational mapping is a technique of mapping the data representation from
an object model to a relational data model. This part of Hibernate is used to
SELECT, INSERT, UPDATE and DELETE records from the underlying database
tables.
o Usually a populated object of a POJO is passed to Session.save() method. Hibernate
reads the state of the variables of that object and executes the necessary SQL query.
Architecture of hibernate
o Hibernate makes use of persistent objects commonly called as POJO (POJO =
"Plain Old Java Object".) along with XML mapping documents for persisting
objects to the database layer. The term POJO refers to a normal Java objects that
does not serve any other special role or implement any special interfaces of any of
the Java frameworks (EJB, JDBC, DAO, JDO, etc...).
o SessionFactory (org.hibernate.SessionFactory)
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
16
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
o Session (org.hibernate.Session)
o A single-threaded, short-lived object representing a conversation between
the application and the persistent store. Wraps a JDBC connection. Factory
for Transaction. Holds a mandatory (first-level) cache of persistent objects,
used when navigating the object graph or looking up objects by identifier.
o Persistent objects and collections
o Short-lived, single threaded objects containing persistent state and business
function. These might be ordinary JavaBeans/POJOs, the only special thing
about them is that they are currently associated with (exactly one) Session.
As soon as the Session is closed, they will be detached and free to use in
any application layer (e.g. directly as data transfer objects to and from
presentation).
o Transient and detached objects and collections
o Instances of persistent classes that are not currently associated with a
Session. They may have been instantiated by the application and not (yet)
persisted or they may have been instantiated by a closed Session.
o Transaction (org.hibernate.Transaction)
o (Optional) A single-threaded, short-lived object used by the application to
specify atomic units of work. Abstracts application from underlying JDBC,
JTA or CORBA transaction. A Session might span several Transactions in
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
17
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
▪ A Servlet
▪ A JSP
Software Requirements
o Java Development Kit
o NetBeans IDE [The development IDE]
o MySQL database server
o Hibernate 3 [The ORM tool]
7. click next
8. select glassfish server
9. click next
10. select hibernate 4.3.1 framework
11. select jpatest database connection we created in previous session
12. click finish
hibernate.reveng
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse
Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-
engineering-3.0.dtd">
<hibernate-reverse-engineering>
<schema-selection match-catalog="jpatest"/>
<table-filter match-name="emp"/>
</hibernate-reverse-engineering>
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
20
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
</property>
</class>
</hibernate-mapping>
Even in hibernate.cfg.xml
<mapping resource="weit/Emp.hbm.xml"/> is added in config automatically
Creating JSP’s
Read.jsp
<%@page import="java.util.Iterator"%>
<%@page import="org.hibernate.Transaction"%>
<%@page import="org.hibernate.cfg.Configuration"%>
<%@page import="weit.Emp"%>
<%@page import="java.util.List"%>
<%@page import="org.hibernate.Session"%>
<%@page import="org.hibernate.SessionFactory"%>
<html>
<body>
<%!
SessionFactory sessionFactory;
Session hibSession;
List<Emp> emp;
%>
<%
sessionFactory =new Configuration().configure().buildSessionFactory();
hibSession = sessionFactory .openSession();
hibSession.beginTransaction();
emp = hibSession.createQuery("from Emp").list();
hibSession.close();
Iterator it = emp.iterator();
while (it.hasNext()) {
Emp em =(Emp)it.next();
out.println(em.getEmpid() +" " +em.getEmpname() +" "+
em.getEmpsname()+"<br>");
}
%>
</body>
</html>
Write.jsp
<%@page import="java.util.Iterator"%>
<%@page import="org.hibernate.Transaction"%>
<%@page import="org.hibernate.cfg.Configuration"%>
<%@page import="weit.Emp"%>
<%@page import="java.util.List"%>
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
22
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
<%@page import="org.hibernate.Session"%>
<%@page import="org.hibernate.SessionFactory"%>
<html>
<body>
<%!
SessionFactory sessionFactory;
Session hibSession;
List<Emp> emp;
%>
<%
sessionFactory =new Configuration().configure().buildSessionFactory();
hibSession = sessionFactory .openSession();
Transaction tx = hibSession.beginTransaction();
Emp employee = new Emp("sarvesh", "belose");
hibSession.save(employee);
tx.commit();
hibSession.close();
%>
</body>
</html>
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
23
TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES
FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES
o session factory is built. This step indicates Hibernate to load the hibernate.cfg.xml
file.
o The configure() method returns an instance of Configuration, which can be used to
obtain a Hibernate SessionFactory instance by calling the buildSessionFactory()
method.
o The buildSessionFactory() method decides about various SQL statements that must
be used to access the data and creates the SessionFactory object
Instantiating A Transaction
o Transaction tx = null;
o An empty instance of Transaction is created.
o tx = hibSession.beginTransaction( );
o An instance of the Transaction class is created by invoking the beginTransaction()
method of the Session interface
o hibSession.save(employee));
o The session interface then saves the Guestbook list by invoking the save() method.
The save() method of the session object allows saving the information to the
database table. When an object is passed to the save() method, Hibernate reads the
state of the variables of that object and executes the required SQL query
o tx.commit();
o Finally, the transaction is committed
WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
24