Tyit Sem 5 Advance Java | PDF | Java (Programming Language) | Databases
0% found this document useful (0 votes)
97 views

Tyit Sem 5 Advance Java

The document discusses Java EE (Enterprise Edition), which provides APIs and runtime for large-scale network applications. It describes Java EE technologies like EJBs, JPA, JSF etc. used in different tiers - client, web, business and data tiers. It also summarizes the evolution of Java EE from initial version to current simplified programming model using annotations and dependency injection.

Uploaded by

Sumit Badugu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
97 views

Tyit Sem 5 Advance Java

The document discusses Java EE (Enterprise Edition), which provides APIs and runtime for large-scale network applications. It describes Java EE technologies like EJBs, JPA, JSF etc. used in different tiers - client, web, business and data tiers. It also summarizes the evolution of Java EE from initial version to current simplified programming model using annotations and dependency injection.

Uploaded by

Sumit Badugu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 96

TYBSC-IT SEM 5 (JAVA EE) 2018-19 NOTES

FOR PROGRAMS AND SOLUTION REFER CLASSROOM NOTES

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.

The Client Tier


The client tier consists of application clients that access a Java EE server and that are usually located on a different
machine from the server. The clients make requests to the server. The server processes the requests and returns a
response back to the client. Many different types of applications can be Java EE clients, and they are not always, or
even often Java applications. Clients can be a web browser, a standalone application, or other servers, and they run
on a different machine from the Java EE server.

The Web Tier


The web tier consists of components that handle the interaction between clients and the business tier. Its primary tasks
are the following:

• Dynamically generate content in various formats for the client.


• Collect input from users of the client interface and return appropriate results from the components in the
business tier.
• Control the flow of screens or pages on the client.
• Maintain the state of data for a user's session.
• Perform some basic logic and hold some data temporarily in JavaBeans components.

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

What is java enterprise edition

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

Business Tier Java EE Technologies

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.

Enterprise Information Systems Tier (EIS) Tier Java EE Technologies

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

• 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, Server and Containers:

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.

Infrastructure Service Levels

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.

• The Web Container


o The web container is the interface between web components and the web server. A web component
can be a servlet, a JavaServer Faces Facelets page, or a JSP page. The container manages the
component's lifecycle, dispatches requests to application components, and provides interfaces to
context data, such as information about the current request.

• The Application Client Container


o The application client container is the interface between Java EE application clients, which are
special Java SE applications that use Java EE server components, and the Java EE server. The
application client container runs on the client machine, and is the gateway between the client
application and the Java EE server components that the client uses.

• The EJB Container


o The EJB container is the interface between enterprise beans, which provide the business logic in a
Java EE application, and the Java EE server. The EJB container runs on the Java EE server and
manages the execution of an application's enterprise beans.

Introduction to Java Servlets

The Need for Dynamic Content


• In a web application, clients send request to the servers and servers return a response to the client.
• Once the client receives the response, connection between client and server will get lost.

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.

Java Servlet Technology

• 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.

What can Servlets do?


• servlet can store cookies, maintain session (state), connect to database, call a enterprise bean, call
webservice, can do programmatic redirection.

Servlet API and Lifecycle

Java Servlet API


• The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.
• The javax.servlet package contains many interfaces and classes that are used by the servlet or web container.
These are not specific to any protocol.
• The javax.servlet.http package contains interfaces and classes that are responsible for http requests only.

Interfaces in javax.servlet package

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

Classes in javax.servlet package

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

Interfaces in javax.servlet.http package

1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)

Classes in javax.servlet.http package

1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)

Servlet Types

There are two main servlet types, generic and HTTP:

• 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.

The Servlet Skeleton


Generic Servlet

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
}
}

web.xml (Application Deployment Descriptor)

<?xml version="1.0" encoding="UTF-8"?>


<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>Hrishikesh</servlet-name>
<servlet-class>Hrishikesh</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hrishikesh</servlet-name>
<url-pattern>/xyz</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
The Servlet Life Cycle
The web container maintains the life cycle of a servlet instance

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

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.

1) Servlet class is loaded

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.

2) Servlet instance is created

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.

3) init method is invoked

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:

public void init(ServletConfig config) throws ServletException

4) service method is invoked

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:

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException

5) destroy method is invoked

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:

public void destroy()

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

A Simple Welcome Servlet (Program)

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..");
}
}
}

Working With Servlets

Getting Started
IDE is Integrated Development Environment, and it makes creating applications a lot easier.

Create Servlet Application in Netbeans IDE

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)

Using Annotations Instead of Deployment Descriptor


import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
@WebServlet(

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..");
}
}
}

Working with Databases

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

• Providing Existing Enterprise Data :


o With JDBC businesses can continue to use their installed databases and access
information even if it is stored on different database management systems.
• Easy Enterprise Development :
o With JDBC development of application has become an easier job which is also
cost effective along with JDBC API & Java API. JDBC made the process simple by
hiding details at the time to access different tasks of database. Majority of the
work done internally The JDBC API is very easy to learn, Inexpensive to maintain
& easy to deploy.
• No need of Configurations for Network Computers :
o With JDBC there is no need of configuration on the client side centralizes software
maintenance. Driver of JDBC is written in the Java, so all the information needed
to make a connection is completely defined by the JDBC URL or by a DataSource
object. DataSource object is registered with a Java Naming and Directory Interface
(JNDI) naming service.
• Full Access to Metadata :
o The JDBC API provides metadata access that enables the development of
sophisticated applications.

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.

Two-tier Architecture for Data 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.

Three-tier Architecture for Data Access.

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".

JDBC Driver Types


JDBC drivers are divided into four types or levels. The different types of jdbc drivers are:
Type 1: JDBC-ODBC Bridge driver (Bridge)
Type 2: Native-API/partly Java driver (Native)
Type 3: All Java/Net-protocol driver (Middleware)
Type 4: All Java/Native-protocol driver (Pure)

JDBC classes/interfaces in the java.sql package:


• Driver: Gives JDBC a launching point for database connectivity by responding to
DriverManager connection requests and providing information about the implementation
in question
• DriverManager: Actually keeps a list of classes that implement the Driver interface.When
an application is run, DriverManager loads all the drivers found in the memory, when
opening a connection to a database DriverManager selects the most appropriate driver from
the previously loaded drivers
• Connection: Represents a connection with a data source. This interface can be used to
retrieve information regarding the tables in the database to which connection is opened
• Statement: Represents static SQL statement that can be used to retrieve ResultSet
object(s). The objective of Statement interface is to pass to the database the SQL command
for execution and to retrieve output results from the database in the form of a ResuItSet
• ResultSet: Is a database result set generated from a currently executed SQL statement. The
data from the query is delivered in the form of a table/ The rows of the table are returned
to the program in sequence
• PreparedStatement: Is an SQL statement that is precompiled and stored. This object can
then be executed multiple times much more efficiently than preparing and issuing the same
statement each time it is needed. Therefore, it is a higher performance alternative to
Statement object.
• CallableStatement: Represents a stored procedure. It can be used to execute Stored
procedures in a RDBMS that supports them.

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

Request Dispatcher interface


The RequestDispatcher interface provides the facility of dispatching the request to another resource it may be html,
servlet or jsp. This interface can also be used to include the content of another resource also. It is one of the way of
servlet collaboration.

There are two methods defined in the RequestDispatcher interface.


1. public void forward(ServletRequest request,ServletResponse response)throws
ServletException,java.io.IOException:Forwards a request from a servlet to another resource (servlet, JSP file,
or HTML file) on the server.

2. public void include(ServletRequest request,ServletResponse response)throws


ServletException,java.io.IOException:Includes the content of a resource (servlet, JSP page, or HTML file) in
the response.

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

o WelcomeServlet.java file: a servlet class for displaying the welcome message.


o web.xml file: a deployment descriptor file that contains the information about the
servlet.

index.html

<form action="servlet1" method="post">


Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"/><br/>
<input type="submit" value="login"/>
</form>

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.

Where Cookies Are Used


• Cookies are a convenient way to carry information from one session on a website to another, or between
sessions on related websites, without having to burden a server machine with massive amounts of data
storage.
• Storing the data on the server without using cookies would also be problematic because it would be difficult
to retrieve a particular user's information without requiring a login on each visit to the website.
• If there is a large amount of information to store, then a cookie can simply be used as a means to identify a
given user so that further related information can be looked up on a server-side database.
• For example the first time a user visits a site they may choose a username which is stored in the cookie, and
then provide data such as password, name, address, preferred font size, page layout, etc.
• this information would all be stored on the database using the username as a key. Subsequently when the
site is revisited the server will read the cookie to find the username, and then retrieve all the user's information
from the database without it having to be re-entered.

Methods of Cookie class

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.

public void setValue(String newValue): Assigns a new value to this Cookie.

public String getValue(): Gets the current value of this Cookie.

Creating Cookies Using Servlet


How to send Cookies to the Client

1. Create a Cookie object.


2. Set the maximum Age.
3. Place the Cookie in HTTP response header.

Create a Cookie object:

• Cookie c = new Cookie("userName","weit");

set the maximum Age:

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);

Place the Cookie in HTTP response header:

We can send the cookie to the client browser through response.addCookie() method.

• response.addCookie(c);

How to read cookies

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());
}

Dynamically Changing The Colors Of A Page

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.

How to get the HttpSession object

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.

Commonly used methods of HttpSession interface


1. public String getId():Returns a string containing the unique identifier value.
2. public long getCreationTime():Returns the time when this session was created, measured in milliseconds
since midnight January 1, 1970 GMT.
3. public long getLastAccessedTime():Returns the last time the client sent a request associated with this
session, as the number of milliseconds since midnight January 1, 1970 GMT.
4. public void invalidate():Invalidates this session then unbinds any objects bound to it.

Lifecycle Of Http Session


• Every request is associated with an HttpSession object. It can be retrieved using getSession(boolean create)
available in HttpServletRequest. It returns the current HttpSession associated with this request or, if there is
no current session and create is true, and then returns a new session. A session can be uniquely identified
using a unique identifier assigned to this session, which is called session id. getId() gives you the session id
as String.

• 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.

o public boolean HttpSession.isNew()

▪ 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.

o public void HttpSession.invalidate()

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.

o public long HttpSession.getCreationTime()

▪ 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).

o public long HttpSession.getLastAccessedTime()

▪ 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.

Session Tracking with the Servlet API

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)

A Servlet Session Example


(refer classroom notes for example)

Working With Files


1. http://commons.apache.org/proper/commons-io/download_io.cgi (commons-io-x.x.jar )
2. http://commons.apache.org/proper/commons-fileupload/download_fileupload.cgi (commons-
fileupload.x.x.jar)

• 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

public class DiskFileItemFactory extends java.lang.Object implements FileItemFactory


• The default FileItemFactory implementation. This implementation creates FileItem instances
which keep their content either in memory, for smaller items, or in a temporary file on disk, for larger items.
The size threshold, above which content will be stored on disk, is configurable, as is the directory in which
temporary files will be created.

public class ServletFileUpload extends FileUpload

• High level API for processing file uploads.

• 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

o public static final boolean isMultipartContent(HttpServletRequest request)

▪ Utility method that determines whether the request contains multipart content.

o public List<FileItem> parseRequest(HttpServletRequest request) throws FileUploadException

▪ Processes an RFC 1867 compliant multipart/form-data stream.

Creating an Upload File Application


1. Html file(fileupload.html)
2. servletfile (fileupload.java)

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

• A servlet can be annotated with ©MultipartConfig in order to handle multipart/form-data


requests which contain file upload data.
• Servlets annotated with @MultipartConfig may retrieve the Part components of a given
multipart/form-data request by calling getPart() or getParts()
• @MultipartConfig annotation supports the following optional attributes:

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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">


</head>
<body>
<form method="POST" action="upload" enctype="multipart/form-data" >
File:
<input type="file" name="file" id="file" /> <br/>
Destination:
<input type="text" value="/tmp" name="destination"/>
</br>
<input type="submit" value="Upload" name="upload" id="upload" />
</form>
</body>
</html>

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");

// Create path components to save the file


final String path = request.getParameter("destination");
final Part filePart = request.getPart("file"); //represents a part or form item that was received within
a multipart/form-data POST request.
final String fileName = getFileName(filePart);

OutputStream out = null;


InputStream filecontent = null;
final PrintWriter writer = response.getWriter();

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

final byte[] bytes = new byte[1024];

while ((read = filecontent.read(bytes)) != -1) {


out.write(bytes, 0, read);
}
writer.println("New file " + fileName + " created at " + path);
LOGGER.log(Level.INFO, "File{0}being uploaded to {1}",
new Object[]{fileName, path});
} catch (FileNotFoundException fne) {
writer.println("You either did not specify a file to upload or are "
+ "trying to upload a file to a protected or nonexistent "
+ "location.");
writer.println("<br/> ERROR: " + fne.getMessage());

LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}",


new Object[]{fne.getMessage()});
} finally {
if (out != null) {
out.close();
}
if (filecontent != null) {
filecontent.close();
}
if (writer != null) {
writer.close();
}
}
}

private String getFileName(final Part part) {


final String partHeader = part.getHeader("content-disposition");
LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(
content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
}
• getFileName method to retrieve the file name from the file part.

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 .

Creating a Download File Application

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);
}
}

Working With Non-Blocking I/O


Whats non-blocking i/o

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.

1. Put the request in asynchronous mode as described in Asynchronous Processing.


2. Obtain an input stream and/or an output stream from the request and response objects in the service method.
3. Assign a read listener to the input stream and/or a write listener to the output stream.
4. Process the request and the response inside the listener's callback 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

Nonblocking I/O Support in javax.servlet.ServletInputStream


Method Description
void setReadListener(ReadListener rl) Associates this input stream with a listener object that contains callback
methods to read data asynchronously. You provide the listener object as
an anonymous class or use another mechanism to pass the input stream
to the read listener object.
boolean isReady() Returns true if data can be read without blocking.
boolean isFinished() Returns true when all the data has been read.

Nonblocking I/O Support in javax.servlet.ServletOutputStream

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.

Listener Interfaces for Nonblocking I/O Support

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

Interface Methods Description


ReadListener void onDataAvailable() A ServletInputStream instance calls these methods on its
listener when there is data available to read, when all the
void onAllDataRead() data has been read, or when there is an error.

void onError(Throwable t)

WriteListener void onWritePossible() A ServletOutputStream instance calls these methods on its


listener when it is possible to write data without blocking or
void onError(Throwable t) when there is an error.

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

Why use Java Server Pages?


• JavaServer Pages (JSP) is a technology for developing Webpages that supports dynamic
content. This helps developers insert java code in HTML pages by making use of special
JSP tags, most of which start with <% and end with %>
• A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role
of a user interface for a Java web application. Web developers write JSPs as text files that
combine HTML or XHTML code, XML elements, and embedded JSP actions and
commands.
• Using JSP, you can collect input from users through Webpage forms, present records from
a database or another source, and create Webpages dynamically.
• JSP tags can be used for a variety of purposes, such as retrieving information from a
database or registering user preferences, accessing JavaBeans components, passing control
between pages, and sharing information between requests, pages etc.

Why Use JSP?


• JavaServer Pages often serve the same purpose as programs implemented using
the Common Gateway Interface (CGI). But JSP offers several advantages in comparison
with the CGI.
• Performance is significantly better because JSP allows embedding Dynamic Elements in
HTML Pages itself instead of having separate CGI files.
• JSP are always compiled before they are processed by the server unlike CGI/Perl which
requires the server to load an interpreter and the target script each time the page is
requested.
• JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has
access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP, etc.
• JSP pages can be used in combination with servlets that handle the business logic, the
model supported by Java servlet template engines.
• No body can borrow the code (code remains on web server)
• Faster loading of web pages
• No browser compatibility issue

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 v\s Servlets


JSP Servlets

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.

Life cycle of JSP


A Java Server Page life cycle is defined as the process started with its creation which later
translated to a servlet and afterward servlet lifecycle comes into play. This is how the process goes
on until its destruction.

Following steps are involved in JSP life cycle:


• Translation of JSP page to Servlet
• Compilation of JSP page(Compilation of JSP into test.java)
• Classloading (test.java to test.class)
• Instantiation(Object of the generated Servlet is created)
• Initialization(jspInit() method is invoked by the container)
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

• Request processing(_jspService()is invoked by the container)


• JSP Cleanup (jspDestroy() method is invoked by the container)

• Translation of JSP page to Servlet :


o This is the first step of JSP life cycle. This translation phase deals with Syntactic
correctness of JSP. Here test.jsp file is transllated to test.java.
• Compilation of JSP page :
o Here the generated java servlet file (test.java) is compiled to a class file (test.class).
• Classloading :
o Servlet class which has been loaded from JSP source is now loaded into container.
• Instantiation :
o Here instance of the class is generated. The container manages one or more instance
by providing response to requests.
• Initialization :
o jspInit() method is called only once during the life cycle immediately after the
generation of Servlet instance from JSP.
• Request processing :
o _jspService() method is used to serve the raised requests by JSP.It takes request
and response object as parameters.This method cannot be overridden.
• JSP Cleanup :
o In order to remove the JSP from use by the container or to destroy method for
servlets jspDestroy()method is used. This method is called once, if you need to
perform any cleanup task like closing open files, releasing database connections
jspDestroy() can be overridden.

How does a JSP function


Jsp code spec can be broken into two categories:
• Elements that are processed by the JSP engine on the Web server
• Template data or everything other than such elements, that the JSP engine ignores
• JSP rage is executed by a Web server that either has a built in JSP engine or accesses a
third party JSP engine, which it is configured to use. When a client asks for a JSP resource
the
web server fields that request and delivers it to the JSP engine along with a RESPONSE
object.
• Jsp engine uses the jsp code spec referenced by the client to process the client response
obtain whatever is required from associated resources.
• Jsp uses HttpServletRequest and HttpServletResonse for the http protocol similar to that
of servlet.
• Most jsp is pain html, interspersed with special JSP tags.
• The scriplet tag encloses java code, which accept and processes the parameters from html
form using request object and send response to client using response object.

How does a JSP Execute?


• first browser send request to server via http get or post method.
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

• 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.

Getting started with javaserver pages

• 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>

Advantages of JSP document


• JSP documents can be easily verified as well-formed XML/HTML
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

• JSP documents can be validated against an XML Schema


• JSP documents can be readily written and parsed using standard XML tools
• JSP documents can be readily written and presented in alternate forms using XSLT
[extensible Stylesheet Language Transformations]
• JSP uses XML-compliant include and forward actions as well as custom tags. This makes
the entire document XML-compliant, which in turn leads to increased code consistency
• JSP documents require slightly more developer discipline than JSP pages. This makes the
code spec more readable and maintainable, especially for those to whom JSP is new
Page Directive
Syntax: [In a regular JSP page]
• <%@ page attributes=”<Value>” %>
Syntax: [In an XML based JSP page]
• <jsp:directive.page attributes="<Value>" />

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

out.println("Scriplet Number is " +num3);


%>

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 %>

JSP GUI Example(refer classroom notes)

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.

Including other Files


The <jsp:include> Action
• This action lets you insert files into the page being generated. The syntax looks like this −
• <jsp:include page = "relative URL" flush = "true" />
• Unlike the include directive, which inserts the file at the time the JSP page is translated
into a servlet, this action inserts the file at the time the page is requested.
Following table lists out the attributes associated with the include action −
S.No. Attribute & Description
1 page
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

The relative URL of the page to be included.


2 flush
The boolean attribute determines whether the included resource has its buffer
flushed before it is included.
Example
Let us define the following two files (a)date.jsp and (b) main.jsp as follows −

Following is the content of the date.jsp file −


<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>

Following is the content of the main.jsp file −


<html>
<head>
<title>The include Action Example</title>
</head>
<body>
<center>
<h2>The include action Example</h2>
<jsp:include page = "date.jsp" flush = "true" />
</center>
</body>
</html>

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 –

Following is the content of the hello.jsp file −


<p>Today's date: <%= request.getParameter(“username”) %></p>

Following is the content of the main.jsp file −


<html>
<head>
<title>The include Action Example</title>
</head>
<body>
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

<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.

The <jsp:setProperty> Action


The setProperty action sets the properties of a Bean. The Bean must have been previously defined
before this action. There are two basic ways to use the setProperty action −
You can use jsp:setProperty after, but outside of a jsp:useBean element, as given below −

<jsp:useBean id = "myName" ... />


...
<jsp:setProperty name = "myName" property = "someProperty" .../>

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 −

<jsp:useBean id = "myName" ... >


...
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

<jsp:setProperty name = "myName" property = "someProperty"


.../>
</jsp:useBean>
Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing one
was found.
Following table lists out the attributes associated with the setProperty action −
S.No. Attribute & Description
1 name
Designates the bean the property of which will be set. The Bean must have been
previously defined.
2 property
Indicates the property you want to set. A value of "*" means that all request
parameters whose names match bean property names will be passed to the
appropriate setter methods.
3 value
The value that is to be assigned to the given property. The the parameter's value is
null, or the parameter does not exist, the setProperty action is ignored.
4 param
The param attribute is the name of the request parameter whose value the property
is to receive. You can't use both value and param, but it is permissible to use
neither.

The <jsp:getProperty> Action

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 –

<jsp:useBean id = "myName" ... />


...
<jsp:getProperty name = "myName" property = "someProperty" .../>

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.

Implicit Objects, Scope And EL Expressions


Implicit Objects
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

• 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.

The request Object


• The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each
time a client requests a page the JSP engine creates a new object to represent that request.
• The request object provides methods to get the HTTP header information including form
data, cookies, HTTP methods etc

The response Object


The response object is an instance of a javax.servlet.http.HttpServletResponse object. Just as the
server creates the request object, it also creates an object to represent the response to the client.
The response object also defines the interfaces that deal with creating new HTTP headers. Through
this object the JSP programmer can add new cookies or date stamps, HTTP status codes, etc.

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

The out Object


• The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to
send content in a response.
• The initial JspWriter object is instantiated differently depending on whether the page is
buffered or not. Buffering can be easily turned off by using the buffered = 'false' attribute
of the page directive.
• The JspWriter object contains most of the same methods as the java.io.PrintWriter class.
However, JspWriter has some additional methods designed to deal with buffering. Unlike
the PrintWriter object, JspWriter throws IOExceptions.
Following table lists out the important methods that we will use to write boolean char, int, double,
object, String, etc.
S.No. Method & Description
1 out.print(dataType dt)
Print a data type value
2 out.println(dataType dt)
Print a data type value then terminate the line with new line character.
3 out.flush()
Flush the stream.

The session Object


• The session object is an instance of javax.servlet.http.HttpSession and behaves exactly the
same way that session objects behave under Java Servlets.
• The session object is used to track client session between client requests.
• The application Object
• The application object is direct wrapper around the ServletContext object for the generated
Servlet and in reality an instance of a javax.servlet.ServletContext object.
• This object is a representation of the JSP page through its entire lifecycle. This object is
created when the JSP page is initialized and will be removed when the JSP page is removed
by the jspDestroy() method.
• By adding an attribute to application, you can ensure that all JSP files that make up your
web application have access to it.

The config Object


• The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper
around the ServletConfig object for the generated servlet.
• This object allows the JSP programmer access to the Servlet or JSP engine initialization
parameters such as the paths or file locations etc.
• The following config method is the only one you might ever use, and its usage is trivial −
• config.getServletName();
• This returns the servlet name, which is the string contained in the <servlet-name> element
defined in the WEB-INF\web.xml file.

The pageContext Object

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

• The pageContext object is an instance of a javax.servlet.jsp.PageContextobject. The


pageContext object is used to represent the entire JSP page.
• This object is intended as a means to access information about the page while avoiding
most of the implementation details.
• This object stores references to the request and response objects for each request.
The application, config, session, and out objects are derived by accessing attributes of this
object.
• The pageContext object also contains information about the directives issued to the JSP
page, including the buffering information, the errorPageURL, and page scope.
• The PageContext class defines several fields, including PAGE_SCOPE,
REQUEST_SCOPE, SESSION_SCOPE, and APPLICATION_SCOPE, which identify
the four scopes. It also supports more than 40 methods, about half of which are inherited
from the javax.servlet.jsp.JspContext class.
• One of the important methods is removeAttribute. This method accepts either one or two
arguments. For example, pageContext.removeAttribute ("attrName") removes the attribute
from all scopes, while the following code only removes it from the page scope −
• pageContext.removeAttribute("attrName", PAGE_SCOPE);

The page Object


• This object is an actual reference to the instance of the page. It can be thought of as an
object that represents the entire JSP page.
• The page object is really a direct synonym for the this object.
• The exception Object
• The exception object is a wrapper containing the exception thrown from the previous page.
It is typically used to generate an appropriate response to the error condition.

Character Quoting Conventions


There are a small number of special constructs you can use in various cases to insert comments or
characters that would otherwise be treated specially. Here's a summary:
Syntax Purpose
<\% Used in template text (static HTML) where you really want "<%".
%\> Used in scripting elements where you really want "%>".
\' A single quote in an attribute that uses single quotes. Remember, however, that you
can use either single or double quotes, and the other type of quote will then be a regular
character.
\" A double quote in an attribute that uses double quotes. Remember, however, that you
can use either single or double quotes, and the other type of quote will then be a regular
character.
%\> %> in an attribute.
<\% <% in an attribute.

Unified Expression Language


The expression language introduced in JSP 2.0 allows page authors to use simple expressions to
dynamically read data from JavaBeans components. For example, the test attribute of the

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.

<c:if test="${sessionScope.cart.numberOfItems > 0}">


...
</c:if>
unified expression language allows page authors to use simple expressions to perform the
following tasks:
• Dynamically read application data stored in JavaBeans components, various data
structures, and implicit objects
• Dynamically write data, such as user input into forms, to JavaBeans components
• Invoke arbitrary static and public methods
• Dynamically perform arithmetic operations

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}" />

Value and Method Expressions


• The unified EL defines two kinds of expressions: value expressions and method
expressions. Value expressions can either yield a value or set a value. Method expressions
reference methods that can be invoked and can return a value.
• Value Expressions
o Value expressions can be further categorized into rvalue and lvalue
expressions. Rvalue expressions are those that can read data, but cannot write
it. Lvalue expressions can both read and write data.
o All expressions that are evaluated immediately use the ${} delimiters and are
always rvalue expressions. Expressions whose evaluation can be deferred use
the #{}delimiters and can act as both rvalue and lvalue expressions. Consider these
two value expressions:
o <taglib:tag value="${customer.name}" />
o <taglib:tag 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

${100.0 == 100} true


${(10*10) ne 100} false
${'a' < 'b'} true
${'hip' gt 'hit'} false
${4 > 3} true
${1.2E4 + 1.4} 12001.4
${3 div 4} 0.75
${10 mod 4} 2
${!empty param.Add} False if the request parameter named Add is
null or an empty string.
${pageContext.request.contextPath} The context path.
${sessionScope.cart.numberOfItems} The value of the numberOfItems property of
the session-scoped attribute named cart.
${param['mycom.productId']} The value of the request parameter
named mycom.productId.
${header["host"]} The host.
${departments[deptName]} The value of the entry named deptName in
the departments map.
${requestScope[’javax.servlet.forward.servlet_path’]} The value of the request-scoped attribute
named javax.servlet.forward.servlet_path.
#{customer.lName} Gets the value of the property lName from
the customer bean during an initial request.
Sets the value of lName during a postback.
#{customer.calcTotal} The return value of the method calcTotal of
the customer bean.

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}

Referencing Object Properties or Collection Elements


o To refer to properties of a bean, static fields or methods of a class, or items of a collection,
you use the. or [] notation. The same syntax can be used for attributes of an implicit object,
because attributes are placed in a map.
o To reference the name property of the customer bean, use either the expression
o ${customer.name} or the expression ${customer["name"]}.
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

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

Parameterized Method Calls


The EL offers support for parameterized method calls.
Both the . and [] operators can be used for invoking method calls with parameters, as
shown in the following expression syntax:
o expr-a[expr-b](parameters)
o expr-a.identifier-b(parameters)
<h:inputText value="#{userNumberBean.userNumber('5')}">

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);

Operations on Collection Objects


• The EL supports operations on collection objects: sets, lists, and maps. It allows the
dynamic creation of collection objects, which can then be operated on using streams and
pipelines.
• For example, you can construct a set as follows:
o {1,2,3}
• You can construct a list as follows; a list can contain various types of items:
o [1,2,3]
o [1, "two", [three,four]]
• You can construct a map by using a colon to define the entries, as follows:
o {"one":1, "two":2, "three":3}

• 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

• A stream pipeline consists of the following:


o A source (the Stream object)
o Any number of intermediate operations that return a stream (for example, filter and
map)
o A terminal operation that does not return a stream (for example, toList())
• The stream method obtains a Stream from a java.util.Collection or a Java array. The stream
operations do not modify the original collection object. For example, you might generate a
list of titles of history books as follows:
o books.stream().filter(b->b.category == 'history')
o .map(b->b.title)
o .toList()
• The following simpler example returns a sorted version of the original list:
o [1,3,5,2].stream().sorted().toList()

• The following subset of operations is supported by the EL:


allMatch findFirst min distinct sorted limit
anyMatch flatMap noneMatch filter substream map
average forEach peek toArray sum max
count iterator reduce toList

JavaServer Pages Standard Tag Libraries


JSP tags were logical evolutionary steps towards creating fast, maintainable, Java based, Internet
delivered, applications. In mid 2002 the release of the JSP Standard Tag Library [JSTL]
represented a really huge step that speeded up yet simplified the Java based application
development process.

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.

What Is Wrong In Using JSP Scriptlet Tags.


• The java code embedded within the scriptlet looks ugly and obtrusive
• The developer who does not know Java actually modify the embedded java code Thus, this
disadvantage nullifies the major benefit of JSP, which is designers and business people to
update page content.
• The Java code embedded within the Scriptlets cannot be re-used by another jsp pages. So
the common logic code spec ends up being re-implemented in multiple jsp pages
• Retrieving objects out of the HTTP request and sessions is not manageable. they have to
be specifically typecast to the object's class. This requires that the object class be known to
the JSP by importing or fully qualifying the class name

How jstl fixes jsp scriptlets shortcommings.

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

Core Variable support c

Flow control

URL management

Miscellaneous

XML Core x

Flow control

Transformation

I18N Locale fmt

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

Database SQL sql

Functions Collection length fn

String manipulation

JSTL Core Tags


The JSTL core tag provides variable support, URL management, flow control etc. The syntax
used for including JSTL core library in your JSP is:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
c:out It display the result of an expression, similar to the way <%=...%> tag work.
<c:out value="${'testing'}"/>
c:import It Retrives relative or an absolute URL and display the contents to either a String in
'var',a Reader in 'varReader' or the page.
<c:import var="data" url="http://www.weit.in"/>
<c:out value="${data}"/>

c:set It sets the result of an expression under evaluation in a 'scope' variable.

<c:set var="Income" scope="session" value="${4000*4}"/>


<c:out value="${Income}"/>
c:remove It is used for removing the specified scoped variable from a particular scope.

<c:set var="income" scope="session" value="${4000*4}"/>


<p>Before Remove Value is: <c:out value="${income}"/></p>
<c:remove var="income"/>
<p>After Remove Value is: <c:out value="${income}"/></p>
c:catch It is used for Catches any Throwable exceptions that occurs in the body.

<c:catch var ="catchtheException">


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

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


<p>The type of exception is : ${catchtheException} <br />
There is an exception: ${catchtheException.message}</p>
</c:if>
c:if It is conditional tag used for testing the condition and display the body content only
if the expression evaluates is true.

<c:set var="income" scope="session" value="${4000*4}"/>


<c:if test="${income > 8000}">
<p>My income is: <c:out value="${income}"/><p>
</c:if>

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

JSTL XML tags List


XML Tags Descriptions
x:out Similar to <%= ... > tag, but for XPath expressions.
<x:parse xml="${vegetable}" var="output"/> GET XML DATA VEGETABLES
<b>Name of the vegetable is</b>:
<x:out select="$output/vegetables/vegetable[1]/name" /><br> PRINT
FIRST VEG NAME
<b>Price of the Potato is</b>:
<x:out select="$output/vegetables/vegetable[1]/price" /> PRINT FIRST
VEG PRICE
x:parse It is used for parse the XML data specified either in the tag body or an
attribute.
<x:parse xml="${vegetable}" var="output"/> GET XML DATA VEGETABLES
x:set It is used to sets a variable to the value of an XPath expression.
<x:set var="fragment" select="$output/books/book[2]/price"/>
<b>The price of the Tomorrow land book</b>:
<x:out select="$fragment" />
x:choose It is a conditional tag that establish a context for mutually exclusive
conditional operations.
<x:parse xml="${xmltext}" var="output"/>
<x:choose>
<x:when select="$output//book/author = 'Chetan bhagat'">
Book is written by Chetan bhagat
</x:when>
</x:choose>
x:when It is a subtag of that will include its body if the condition evaluated be 'true'.
<x:when select="$output//book/author = 'Chetan bhagat'">
Book is written by Chetan bhagat
</x:when>
x:if It is used for evaluating the test XPath expression and if it is true, it will
processes its body content.
<x:parse xml="${vegetables}" var="output"/>
<x:if select="$output/vegetables/vegetable/price < 100">
Vegetables prices are very low.
</x:if>
x:transform It is used in a XML document for providing the XSL(Extensible Stylesheet
Language) transformation.
<c:import var="xml" url="transfer.xml" />
<c:import var="xsl" url="transfer.xsl" />
<x:transform xml="${xml}" xslt="${xsl}" />

JSTL Formatting tags


Formatting Descriptions
Tags
fmt:parseNumb It is used to Parses the string representation of a currency, percentage or
er number.
<c:set var="Amount" value="786.970" />
<fmt:parseNumber var="j" type="number" value="${Amount}" />
<p><i>Amount is:</i> <c:out value="${j}" /></p>

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>

JSTL SQL Tags List


SQL Tags Descriptions

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>

JSTL Function Tags List


JSTL Functions Description
fn:contains() It is used to test if an input string containing the specified substring
in a program.
<c:set var="String" value="Welcome to JAVA"/>

<c:if test="${fn:contains(String, 'JAVA')}">


<p>Found javatpoint string<p>
</c:if>
fn:containsIgnoreCase() It is used to test if an input string contains the specified substring as
a case insensitive way.
<c:set var="String" value="Welcome to java"/>

<c:if test="${fn:containsIgnoreCase(String, 'java')}">


<p>Found javatpoint string<p>
</c:if>
fn:endsWith() It is used to test if an input string ends with the specified suffix.
<c:set var="String" value="Welcome to JSP programming"/>
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

<c:if test="${fn:endsWith(String, 'programming')}">


<p>String ends with programming<p>
</c:if>

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

Enterprise Bean Architecture


• Enterprise applications are complex, used by many users, developed by multiple teams,
and deployed on heterogeneous systems that might span multiple environments. In
addition, enterprise applications have to be distributed, secure, transactional, reliable,
scalable, flexible, expandable, reusable, and manageable. Moreover, enterprise
applications must be integrated with existing systems, and leveraged against the existing
infrastructure.
• Enterprise JavaBeans (EJB) is a component-based architecture for developing, deploying,
and managing reliable enterprise applications in production environments. EJB
architecture is at the heart of the Java 2 platform, Enterprise Edition (J2EE). With the
growth of the Web and the Internet, more and more enterprise applications are now Web
based, including both intranet and extranet applications. Together, the J2EE and EJB
architectures provide superior support for Web-based enterprise applications.
• Enterprise Bean architecture defines a model for the development and deployment of
reusable Java sever components. EJB component architecture is the backbone of the java
EE platform
o ETB Architecture is composed of
▪ An Enterprise Bean Server
• EJB SERVER
• The EJB server (also known as the J2EE application server) is the
outermost container of the various elements that make up an EJB
environment. The EJB server manages one or more EJB containers
and provides required support services, such as transaction
management, persistence, and client access. A JNDI-accessible
naming space can be used by clients to locate the EJB.
• 3 tire architecture : ui, business rules, database
• Features : security, threading, connection polling
▪ Enterprise Bean Containers that runs on these servers
• Manage enterprise bean inside it.
• It provides registration of objects, remote interface, security,
transaction
▪ Enterprise Beans that run in these containers
• Its reusable classes (add to cart) logic or emi calculator
▪ Enterprise Bean Clients
• Its standalone application for user interaction (atm machine)
▪ Other systems such as Java Naming and Director Interface [JNDI] and
Java Transaction Service [JTS]
o An EJB component can have remote and local interfaces. Clients not located in
the same application server instance as the bean (remote clients) use the remote
interface to access the bean. Calls to the remote interface require marshalling

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

arguments, transportation of the marshalled data over the network, un-marshaling


the arguments, and dispatch at the receiving end.
o If an EJB component has a local interface, then local clients in the same application
server instance can use it instead of the remote interface. Using the local interface
is more efficient, since it does not require argument marshalling, transportation, and
un-marshalling.
o list of these common services:
▪ Life cycle management: The container creates and destroys enterprise
bean instances based on client demand.
▪ Security: The security services are designed to ensure that only authorized
users access resources.
▪ Remote method invocation: The container transparently manages the
communication between enterprise beans and other components.
▪ Transaction management: The transaction services relieve the enterprise
bean developer from dealing with the complex issues of managing
distributed transactions
▪ Transaction management: The transaction services relieve the enterprise
bean developer from dealing with the complex issues of managing
distributed transactions
▪ Passivation/activation: The mechanism that is used by the container to
store an inactive enterprise bean to disk, and restore its state when the bean
is invoked.
▪ Clustering: Supports replication of EJBs and services across multiple
application server instances installed on the same machine or in different
environments.
▪ Concurrency: Supports multithreading management.
▪ Resource pooling: Supports the allocation of a pool of instances, and then
assigns them to the requesting clients.

Types of Enterprise Beans


o Session Beans
o associated with one EJB Client
o created and destroyed by the particular EJB Client
o nonpersistant, do not survive a server shutdown/crash.
o obviously used to model some service
o Two types of session beans exist: stateful and stateless
▪ Stateless Session Beans
• have no internal state
• since they do not have any states, they need not be passivated
• instances can be pooled to service multiple clients
▪ Stateful Session Beans
• have internal state
• need to handle activation and passivation
• an instance of stateful bean is dedicated to the client that created it
(i.e. not shared with other clients)

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

• may survive client session - a persistent handle to the bean may be


obtained, saved at the client side and later (possibly when a client is
started next time) converted back to the reference to the original
session bean
▪ Singleton Session Beans
• A Singleton Session Bean maintains the state of the bean for the
complete lifecycle of the application.
• 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.
• The single instance of the bean is shared between multiple clients
and can be concurrently accessed.
o Entity Beans
o always have states
o may be shared by multiple EJB Clients
o their states can be persisted and stored across multiple invocations
o survive server shutdown/crash
o encapsulate in their object reference a unique ID that points to their state
o Message Driven Beans
o Message driven beans are the light weight components used for communication. In
message driven beans the messaging service is in asynchronous mode because the
user is not intended to get the instant result.
▪ Message driven beans are the special type of components that can receive the
JMS as well as other type of messages.
▪ Message driven bean can also be used to receive the messages other than JMS.
▪ When a message is reached at the destination then the EJB container invokes
the message driven bean. A message driven bean is decoupled with the client
that sends the message. A client is not allowed to access the message driven
bean through a business interface. The client can interact with the message
driven bean only through the messaging system.
▪ To interact with the message driven bean use the message provider specific
API such as JMS.

Accessing Enterprise Beans


o Clients access enterprise beans either through a no-interface view or through a business
interface.
o A no-interface view of an enterprise bean exposes the public methods of the
enterprise bean implementation class to clients. Clients using the no-interface view
of an enterprise bean may invoke any public methods in the enterprise bean
implementation class or any superclasses of the implementation class.
▪ To obtain a reference to the no-interface view of an enterprise bean through
dependency injection, use the javax.ejb.EJB annotation and specify the
enterprise bean’s implementation class.
o A business interface is a standard Java programming language interface that
contains the business methods of the enterprise bean.

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

▪ 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.

Enterprise Bean Application


o To develop an enterprise bean, the following are the files usually created.
o Enterprise Bean Class
o The class that implements the business methods of the enterprise bean and any life
cycle callback methods.
o Business Interfaces
o Business interface defines the business methods implemented by the enterprise
bean class.
o Helper class
o Exception class or utility class

Packaging Enterprise Beans


o An EJB JAR file is portable and can be used for various applications.
o To assemble a Java EE application, package one or more modules, such as EJB JAR files,
into an EAR file, the archive file that holds the application. When deploying the EAR file
that contains the enterprise bean's EJB JAR file, you also deploy the enterprise bean to
GlassFish Server. You can also deploy an EJB JAR that is not contained in an EAR file

o Packaging Enterprise Beans in WAR Modules


o Enterprise beans often provide the business logic of a web application. In these
cases, packaging the enterprise bean within the web application's WAR module
simplifies deployment and application organization. Enterprise beans may be
packaged within a WAR module as Java programming language class files or
within a JAR file that is bundled within the WAR module.
o To include enterprise bean class files in a WAR module, the class files should be
in the WEB-INF/classes directory.
o To include a JAR file that contains enterprise beans in a WAR module, add the JAR
to the WEB-INF/lib directory of the WAR module.
o WAR modules that contain enterprise beans do not require an ejb-
jar.xml deployment descriptor. If the application uses ejb-jar.xml, it must be
located in the WAR module's WEB-INF directory.

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.

Working With Session Beans


What is a Session bean
o A session bean is the enterprise bean that directly interacts with the user and contains the
business logic of the enterprise application.
o A session bean represents a single client accessing the enterprise application deployed on
the server by invoking its method. An application may contain multiple sessions depending
upon the number of users accessing to the application.
o A session bean makes an interactive session only for a single client and shields that client
from complexities just by executing the business task on server side.
o For example, whenever a client wants to perform any of these actions such as making a
reservation or validating a credit card, a session bean should be used. The session bean
decides what data is to be modified.
o Typically, the session bean uses an entity bean to access or modify data. They implement
business logic, business rules, algorithms, and work flows.
o Session beans are relatively short-lived components. The EJB container may destroy a
session bean if its client times out.

When to use Session Beans


o At any given time, only one client has access to the bean instance.
o The state of the bean is not persistent, existing only for a short period (perhaps a few hours).
o The bean implements a web service.
o Stateful session beans are useful in the following circumstances:
o What the bean wants to holds information about the client across method
invocation.
o When the bean works as the mediator between the client and the other component
of the application.
o When the bean have to manage the work flow of several other enterprise beans.
o Stateless session beans are appropriate in the circumstances illustrated below:
o If the bean does not contain the data for a specific client.
o If there is only one method invocation among all the clients to perform the generic
task.

Types of Session Bean


There are 3 types of session bean.
1) Stateless Session Bean: It doesn't maintain state of a client between multiple method
calls.
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 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.

2) Stateful Session Bean: It maintains state of a client across multiple requests.


o These types of beans use the instance variables that allows the data persistent
across method invocation because the instance variables allow persistence of
data across method invocation.
o The client sets the data to these variables which he wants to persist.
o A stateful session bean retains its state across multiple method invocations
made by the same client. If the stateful session bean's state is changed during a
method invocation, then that state will be available to the same client on the
following invocation. The state of a client bean is retained for the duration of
the client-bean session. Once the client removes the bean or terminates, the
session ends and the state disappears.
o Because the client interacts with its bean, this state is often called the
conversational state.

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

Remote and Local Interfaces


o Remote
o A remote client or remote access of an enterprise bean has the following traits
(characteristics)- It can run on a different machine and a different Java Virtual
Machine (JVM) than the enterprise bean it accesses. (it is not required to run on a
different JVM) It can be a web component, an application client, or another
enterprise bean. To a remote client, the location of the enterprise bean is
transparent. To create an enterprise bean that allows remote access, you must do
one of the following:-
o Decorate the business interface of the enterprise bean with the @Remote
annotation:
o @Remote
o Public interface InterfaceName{…….}
o Decorate the bean class with @Remote, specifying the business interface or
interfaces:
o @Remote(InterfaceName.class)
o Public class BeanName implements InterfaceName{……..}
o The remote interface defines the business and lifecycle methods that are specific to
the bean. For example- the remote interface of a bean named BankAccountBean
might have business methods named deposit and credit.
o Local
o A local client or local access has following characteristics:- It must run in the same
JVM as the enterprise bean it accesses. It can be a web component or another enterprise
bean. To the local client, the location of the enterprise bean it accesses is not
transparent.
o The local business interface defines the bean’s business and lifecycle methods. If the
bean’s business interface is not decorated with @Local or @Remote , and the bean
class does not specify the interface using @Local or @Remote, the business interface
is by default a local interface. To build an enterprise bean that allows only local access,
you may, but are not required to do the following:-
o Annotate the business interface of the enterprise bean as a @Local interface. For
example:
o @Local
o public Interface InterfaceName{……..}
o Specify the interface by decorating the bean class with @Local and specify the
interface name. for example:-
o @Local(InterfaceName.class)
o Public class BeanName implements InterfaceName{……..}

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)

Working with Message Driven Beans

Message Driven Beans


o Message driven beans are the light weight components used for communication. In message
driven beans the messaging service is in asynchronous mode because the user is not intended
to get the instant result.
o Message driven beans are the special type of components that can receive the JMS as well as
other type of messages.
o Message driven bean can also be used to receive the messages other than JMS.
o When a message is reached at the destination then the EJB container invokes the message
driven bean. A message driven bean is decoupled with the client that sends the message. A
client is not allowed to access the message driven bean through a business interface. The client
can interact with the message driven bean only through the messaging system.
o To interact with the message driven bean use the message provider specific API such as JMS.

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

The Life Cycle of a Message-Driven Bean


o The EJB container usually creates a pool of message-driven bean instances. For each
instance, the EJB container instantiates the bean and performs these tasks:
• It calls the setMessageDrivenContext method to pass the context object to the
instance.
• It calls the instance's ejbCreate method.

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.

Java Message Services (JMS):


• JMS API is an enterprise tool developed by Sun Microsystems used to develop the
enterprise applications.
• JMS API supports to a framework that allows the development of portable and message
based applications.
• JMS communicates in synchronous or in asynchronous mode by using point-to-point and
the publish-subscribe models respectively.
• JMS has become vendor specific and many vendors such as IBM, Oracle, Hewlett-Packard,
BEA Systems and Macromedia are providing the JMS implementation.

When to Use Message-Driven Beans


• Session beans allow you to send JMS messages and to receive them synchronously but not
asynchronously.
• To avoid tying up server resources, do not to use blocking synchronous receives in a server-
side component; in general, JMS messages should not be sent or received synchronously.
• To receive messages asynchronously, use a message-driven bean.

The Message Driven Beans Example.(refer classroom notes)

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.

Request And Interceptor


• Interceptor can validate request before processing

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

Declares an ordered list of interceptors for a target class, a method or a constructor of a


target class.
@Interceptors(ValidationInterceptor.class)
public class Order { ... }

Interceptor Metadata Annotations


Interceptor Metadata Annotation Description
javax.interceptor.AroundInvoke Designates the method as an interceptor method.
javax.interceptor.AroundTimeout Designates the method as a timeout interceptor, for
interposing on timeout methods for enterprise bean
timers.
javax.annotation.PostConstruct Designates the method as an interceptor method for
post-construct lifecycle events.
javax.annotation.PreDestroy Designates the method as an interceptor method for
pre-destroy lifecycle events.

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)

Java Naming and Directory Interface

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.

What Is Directory Service?


• A Directory Service [DS] is a software application [or a set of applications working
together in harmony], which stores and organizes information about computer
network's users and network resources.
• This allows network administrators to manage users' access to network resources.
Directory Services act as an abstraction layer between users and shared resources on a
network.
• A directory service, called a naming service, binds names of network resources to their
respective network addresses. With the name / service type of directory, a user does
not have to remember the physical address of a network resource.
• Simply providing a name will locate the resource using the directory service. Each
resource on the network is considered an object by the directory server. Information
about a particular object is stored as attributes of that object. Information within objects
can be made secure so that only users with the available permissions are able to access
it
• A directory service defines a namespace for a network. A namespace being a term that
is used to indicate a place that holds one or more objects as named entries.
• The directory design process normally has a set of rules that determine how network
resources are named and identified such as network resource names must be unique
and unambiguous.
• A directory service behaves quite like a database. It is completely optimized for reads.
It provides advanced search possibilities bound to multiple [and different] object
attributes held within the directory.

What Is Java Naming And Directory Interface?

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.

InitialContext ic = new InitialContext();


cart = (ShoppingCartRemote)ic.lookup(“java:global/ShoppingCart/ShoppingCart”);

• 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.

JNDI Namespace In Java EE


There are three JNDI namespaces used for JNDI lookups:
The java:module JNDI Namespace
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

• The java:module namespace is used to lookup local enterprise beans within the
same module.
• Syntax:
• java:module/<Enterprise Bean Name>/[<Interface Name>]

The java:app JNDI Namespace


• The java:app namespace is used to lookup local enterprise beans packaged within
the same Application i.e. the enterprise bean is packaged within an EAR file
containing multiple Java EE modules.
• Syntax:
• Java:app[/< Module Name>]/<Enterprise Bean Name>[/<Interface Name>]

The java:global JNDI Namespace


• The java:global namespace [available since EJB 3.1] is the portable way of finding
remote
• enterprise beans using JNDI lookups.
• Syntax:
• java:global[/<ApplicationName>]/<ModuleName>/<EnterpriseBeanName>[/<Int
erfaceName>]

Resources And JNDI


• JNDI naming service enables components to locate other components and resources.
• A resource is a program object that provides connections to systems such as database
servers and messaging systems.
• Each resource object is identified by a unique, people-friendly name called the JNDI name.
• For example: The JNDI name of the JDBC resource for the JavaDB database that is shipped
with the Sun GlassFish Enterprise Server is jdbc/_default.
• An administrator creates resources in a JNDI namespace.
• In the Sun GlassFish Enterprise Server, the Admin Console or the asadmin command can
be used to create resources.
• Applications then use annotations to inject the resources. If an application uses resource
injection, the Sun GlassFish Enterprise Server invokes the JNDI API and the application
is not required to do so. However, it is also possible for an application to locate resources
by making direct calls to the JNDI API.
• A resource object and its JNDI name are bound together by the naming and directory
service. To create a new resource, a new name-object binding is entered into the JNDI
namespace. Inject resources by using the @Resource annotation in an application.

• 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;

A Message-Driven Bean is injected by a MessageDrivenContext resource. This resource is


commonly used to call the setRollbackOnly() method to handle exceptions for a bean that
uses container-managed transactions.

DataSource Resource Definition In Java EE


• Java EE applications use DataSource objects when they access relational databases through
the JDBC API.
• A DataSource has a set of properties that identify the data source that it represents. These
properties include information such as:
o The location of the database server
o The name of the database
o The network protocol to use to communicate with the server.
• A DataSource object also works with a JNDI naming service. After a DataSource object is
registered with a JNDI naming service, an application can use the JNDI API to access that
DataSource object, which can then be used to connect to the datasource it represents.

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

o Mapping object state


o Determining how an object's state [data stored in member variables of an object] is
stored in database table columns
o Dealing with the fact that object state types may not align with relational database
types
o Mapping object relationships
o Determining how associations between objects are stored as relational database
keys or in relational database intersection tables

Why Object Oriented Models?


• Business logic can be implemented in Java as opposed to stored procedures
• Design patterns and sophisticated object oriented concepts such as inheritance and
• polymorphism can be used
• Provides code reusability and maintainability.
In most of the applications, storing and retrieving information usually involves some kind of
interaction with a relational database

Why Relational Database?


• A relational database is a choice because of the following:
o It is a proven data persistence technology
o Provides flexible and robust approach to data management
o It is the De-facto standard in software development

Current Persistence Standards In Java


• The Java platform was always supported for managing persistence to relational databases.
It provides programming interfaces that in turn provide gateway to the relational databases.
• There already exist the following options that allow the Java developers to store and
retrieve persistent data:
• Serialization
o Serialization allows transforming an object graph into a series of bytes, which can
then be sent over the network or stored in a file.
o Serialization seems to be quite simple, but it has a few limitations:
▪ Unsuitable For Large Amount Of Data
▪ Lacks strict data integrity
▪ No Concurrent Access To Information
▪ No Querying Capability
• JDBC
o JDBC was not designed for storing objects. JDBC allows the Java programs to fully
interact with the database. However, this interaction is heavily reliant on SQL. It
requires a considerable amount of code spec that deals with taking tabular row and
column data and converting it back and forth into objects.
▪ JDBC overcomes a lot of limitations that serialization has such as:
• It can handle large amounts of data
• Ensures data integrity
• Supports concurrent access to information
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

• Provides a sophisticated query language in SQL


o Unfortunately, JDBC does not provide ease of use.
• EJB 2 Entity Beans
o Provide an object-oriented view of persistent data
o Use a strict standard, making them portable across vendors
• Java Data Objects
o Java Data Objects [JDO] was initiated to provide another persistence specification
effort due to the failures of the EJB persistence model.
o Provides an object-oriented query language, which was not well accepted by the
o relational database users
o Supports non-relational databases. In fact, it was driven by members of the object
oriented database community and is now being adopted by object-oriented database
products as the primary API

Why Another Persistence Standards


o The object oriented [domain] model use classes whereas the relational databases use tables.
This creates a gap [The Impedance Mismatch].
o Getting the data and associations from objects into relational table structure and vice versa
requires a lot of tedious programming due to the difference between the two.
o This difference is called The Impedance Mismatch.
o Developers need something simple to convert from one to the other automatically.
o Bridging the gap between the object model and the relational model is known as Object-
Relational Mapping [O-R mapping or ORM].
o The Impedance Mismatch
▪ Relational databases are structured in a tabular manner and the object
oriented instances are structured in a hierarchical manner.
o How To Map One To The Other?
▪ The most native approach that is usually taken is a simple mapping between
each class and the database table. This approach requires writing a lot of
code spec that maps one to the other. This code spec is often complex,
tedious and costly to develop.
o The Solution To The Impedance Mismatch
▪ This impedance mismatch has led to the development of several different
object persistence technologies attempting to bridge the gap between the
relational world and the object oriented world.
▪ Hence the solution is:
• Use an Object Relational Mapping Tool.
• An Object Relational Mapping Tool provides a simple API for
storing and retrieving Java objects directly to and from the relational
database
• Object/Relational Mapping [ORM] is a technique that allows an
application written in an object oriented language to deal with the
information [it manipulates] as objects, rather than using database
specific concepts such as ROWS, COLUMNS and TABLES which
is facilitated by a software called Object/Relational Mapper.
• Object/Relational Mapper also offers persistence services [CRUD]
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

• O/R mapping is performed by a persistence framework.


• This framework knows how to:
o Query the database to retrieve objects
o Persist those objects back to their representation in the
database's tables and columns
▪ ORM has several benefits.
• Eliminates writing SQL to load and persist object state, leaving the
developer free to concentrate on the business logic
• Enables creating an appropriate DOMAIN model, after which, the
developer only needs to think in terms of OBJECTS, rather than
TABLES, ROWS and COLUMNS
• Reduces dependence on database specific SQL and thus provides
Portability across databases
• Reduces more than 30% of the amount of Java code spec that needs
to be written by adopting an ORM

Why Object Relational Mapping?


• An ORM provides the following advantages:
• Better System Architecture
o If the application functionality [business logic] and the database access code spec
[persistence
o mechanism] are separated, applying changes become very easy.
• Reduce Coding Time
o Most of the time the database access code spec is simple inserts, updates or deletes.
These are SQL statements which sometimes are quite tedious to code.
o ORM tool helps here, by generating them on the fly and thereby saves a lot of time.
• Caching And Transactions
o Most ORM tools such as Hibernate come with features such as Caching and
Transactions.
introduction to Java Persistence API

• In spite of having so many Object/Relational mapping tools, there is no single persistence


standard for the Java platform that can be used in both the Java EE and Java SE environments.
• This is where Java Persistence API comes in!
o JPA helps standardize the persistence API for the Java platform.
o A lot of these Object/Relational tool vendors [such as TopLink and Hibernate, as
well as other leading application server vendors and JDO vendors] have widely
accepted the JSR-220 specification and most of them have also released their
implementation of JPA.

The Java Persistence API


• The Java Persistence API is a standard API that allows accessing, persisting and managing
data between Java objects / classes and the relational database in Java EE 5 platform.
• JPA provides standard mechanisms to using Object Relational Mapping tools.
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

• Java Persistence consists of three areas:


o The Java Persistence API
o Object/Relational mapping metadata
o The Query language
• Object-relational mapping with the Java Persistence API is entirely metadata driven.
• It can be done by:
o Adding annotations to the code spec OR
o Using externally defined XML OR
o Using annotations as well as externally defined XML

JPA, ORM, Database And The Application

• JPA is made up of a few classes and interfaces.


• The application communicates with the configured JPA provider [in this case EclipseLink]
to access the underlying data.
• Typically, applications invoke the appropriate methods of the Java Persistence API, These
methods are passed the persistence objects and instructed to operate upon them.
• The information about the mapping [metadata] between the instance variables of classes
and the columns of the tables in the database is available either in XML and/or POJOs with
the help of Annotations.
• POJOs are Java classes that represent the tables in the database. Data Access Object [DAO]
is the design pattern that can be used [if required] to deal with database operations.

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

• WHERE clause predicates


• SELECT clauses, which comprise one or more select item objects
• ORDER-BY and GROUP-BY items
• Subqueries

How JPA Works?


• An XML is created or annotations are added to POJOs, which inform the JPA provider
[such as EclipseLink] about:
o The classes needed to store the data
o How the classes are related to the tables and columns in the database
• This way all the necessary information is provided to the JPA provider.
• During the runtime, the JPA provider reads the XML and/or annotations and dynamically
builds Java classes to manage the translation between the database and the Java objects.
• An EntityManagerFactory is created from the compiled collection of mapping metadata.
The EntityManagerFactory provides the mechanism for managing persistent classes and
the EntityManager interface.
• The EntityManager class provides the interface between the persistent data store and the
application. The EntityManager interface wraps a JDBC connection, which can be user
managed or controlled by the JPA provider and is only intended to be used by a single
application thread, then dosed and discarded.
• All the database interaction is done via a simple, intuitive API that JPA provides. This API
allows performing queries against the objects represented by the database. This API
informs the JPA provider:
o To save the changes whenever the objects are changed
o To store the objects in the database whenever new objects are created

JPA 2.0 specification


o ORM mapping enhancements
o Ability to map unidirectional one-to-many relationships as JPA 1.0 only allowed
bidirectional one-to-many relationships
o Ability to model collections, maps and lists using @ElementCollection annotation
o EntityManager and the Query APIs now support:
o Retrieving the first result
o Accessing the underlying vendor-specific entity manager/query objects
o Pessimistic locking
o JPQL has been enhanced with SQL-like CASE, NULLIF, COALESCE and like
capabilities
o Criteria API similar to the one that Hibernate provides Standardization of:
o Second level caching
o Hints for Query configuration and for EntityManager configuration o Metadata to
support DDL generation and Java2DB mapping
o Support for validation

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

Writing JPA Application


Application Requirement Specifications
• JSP/servlet for user interface to CRUD operations

Where Does ORM/JPA Fit?


• An ORM tool can be invoked from a Java application either directly or by using another
framework such as Struts, Spring and so on.
• Java Persistence API makes it easy for these frameworks to support in one way or another.
o An ORM tool along with the JPA can be used in:
o A Swing application
o A Servlet
o A JSP
o An Enterprise application
• Any other kind of Java application that has access to a database
• Typically, an ORM tool is used to create a Data Access Layer for an application.
o The most typical workflow would be:
▪ Define the configuration details using a Persistence Unit
▪ Create an EntityManagerFactory object by referencing the Persistence Unit
▪ Instantiate the EntityManager object through which the application accesses
ORM tool's representation of the database

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]

The Application Development Approach


1. Create the database schema
2. Create the Web Application
3. Add the Java libraries [JDBC driver] to the application
4. Create a POJO to represent the table in the database schema
5. Create a Persistence unit that points to the database server [MySQL] using JNDI
6. Annotate the POJO to indicate the mapping between the JavaBean properties and the
columns in the table
7. Create JSPs with code spec:
a. To build an EntityManagerFactory object by referencing the Persistence Unit
b. To obtain an EntityManager object from the EntityManagerFactory
c. To perform the required database operations

1. Creating Database And Tables In MySQL


CREATE TABLE `emp` (
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

`empid` int(10) NOT NULL,


`empname` varchar(20) NOT NULL,
`empsname` varchar(20) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
ALTER TABLE `emp` ADD PRIMARY KEY (`empid`);
ALTER TABLE `emp`
MODIFY `empid` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
2. Create web application in netbeans 8.2
3. Adding The Required Library Files
• Right-click the Libraries directory of the webapplication project and select Add
JAR/Folder....
• The Add JAR/Folder dialog box to choose the JAR files appears.
• Select mysql-connector-java-5.1.10-bin.jar file [from the directory, that holds the
extracted contents of the MySQL Connector/J driver] to add it to the project
4. Create a javaBean class
• The primary purpose of having such a class is to hold individual emp table entry as and
when they are captured.
• This class must be annotated with javax.persistence.Entity. Entity classes become a
table in a relational database. Instances of this class becomes rows in the table.
• All entities must have a primary key. Keys can be a single field or a combination of
fields* JPA also allows to auto generate the primary key in the database using the
@GeneratedValue annotation.
package pojo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "emp")
public class Emp
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="empid", unique=true, updatable=false)
private Integer empid;
@Column(name = "empname")
private String empname;
@Column(name = "empsname")
private String empsname;

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

public void setEmpid(Integer empid) {


this.empid = empid;
}
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
public String getEmpsname() {
return empsname;
}
public void setEmpsname(String empsname) {
this.empsname = empsname;
}
}

The following interfaces/ classes are imported:


• javax.persistence.Column: Is used to specify a mapped column for a persistent
property / field. If no @Column annotation is specified, the default values are
applied
• javax.persistence.Entity: Specifies that the class is an entity. This annotation is
applied to the entity class
• javax.persistence.GeneratedValue: Provides for the specification of generation
strategies for the values of primary keys. @GeneratedValue annotation may be
applied to a primary key property / field of an entity or mapped superclass in
conjunction with @Id annotation
• javax.persistence.GenerationType: Defines the types of primary key generation
• javax.persistence.Id: Specifies the primary key property / field of an entity
• javax.persistence.Table: This annotation specifies the primary table for the
annotated entity. If no @Table annotation is specified for an entity class, the
default values apply

Creating Persistence Unit [persistence.xml]

• 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.

1. Right click on project


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

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

emps= em.createQuery("SELECT e from Emp e").getResultList();


Iterator it = emps.iterator();
while (it.hasNext()) {
emp = (Emp)it.next();
out.print(emp.getEmpid() + " -- "+ emp.getEmpname() +" -- "+
emp.getEmpsname()+"<br>");
}
em.close();
%>
</body>
</html>

• 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

The JPA Application Structure, Running The JPA Application.

• Rights click on cud.jsp or read.jsp and click run

Introduction To Hibernate

• Hibernate provides a solution to map database tables to a Java class.


• It does this by:
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

o Copying the data available in the database tables to a Java class


o Saving OBJECTS to the database tables
• In this process the object is transformed to one or more tables.
• Saving data to a storage medium is called persistence.
• Copying of tables to objects and vice versa is called Object/Relational Mapping.

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

Hibernate, Database And The Application


• POJOs are Java classes that represent the tables in the database. Data Access Object [DAO]
is the design pattern that can be used [if required] to deal with database operations.

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 A threadsafe (immutable) cache of compiled mappings for a single


database. A factory for Session and a client of ConnectionProvider. Might
hold an optional (second-level) cache of data that is reusable between
transactions, at a process- or cluster-level.

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

some cases. However, transaction demarcation, either using the underlying


API or Transaction, is never optional!
o ConnectionProvider (org.hibernate.connection.ConnectionProvider)
o (Optional) A factory for (and pool of) JDBC connections. Abstracts
application from underlying Datasource or DriverManager. Not exposed to
application, but can be extended/implemented by the developer.
o TransactionFactory (org.hibernate.TransactionFactory)
o (Optional) A factory for Transaction instances. Not exposed to the
application, but can be extended/implemented by the developer.

How Hibernate Works?


An XML mapping document is created, which informs Hibernate about:
• The classes needed to store the data
• How the classes are related to the tables and columns in the database
• The mapping document is compiled, when the application starts up. It provides the
Hibernate framework with all the necessary information.
• During the runtime, Hibernate reads the XML mapping document and dynamically builds
Java classes to manage the translation between the database and the Java objects.
• A SessionFactory is created from the compiled collection of mapping documents. The
SessionFactory provides the mechanism for managing persistent classes and the Session
interface.
• A SessionFactory is created from the compiled collection of mapping documents. The
SessionFactory provides the mechanism for managing persistent classes and the Session
interface.
• The Session class provides the interface between the persistent data store and the
application. The Session interface wraps a JDBC connection, which can be user managed
or controlled by Hibernate and is only intended to be used by a single application thread,
then closed and discarded.
• All the database interaction is done via a simple, intuitive API that Hibernate provides.
This API allows performing queries against the objects represented by the database. This
API informs Hibernate:
o To save the changes whenever the objects are changed
o To store the objects in the database whenever new objects are created

Writing Hibernate Application

Application Requirement Specifications


o Read write data in mysql using hibernate

Where Does Hibernate Fit?


o Hibernate can be invoked from a Java application either directly or by using another
framework such as Struts or Spring and so on.
o Hibernate can also be invoked from
▪ A Swing application
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

▪ 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]

The Application Development Approach


1. Create the database schema
2. Create the Web Application using the NetBeans IDE
3. Add the Java libraries [Hibernate and JDBC driver] to the application
4. Create a POJO to represent the table in the database schema
5. Create a Hibernate [XML] configuration file that points to the database server [MySQL]
6. Create a Hibernate [XML] mapping files for the POJO that maps the JavaBean properties
to the columns in the table
7. Add the Hibernate mapping file as a reference to the Hibernate configuration file
8. Create JSPs
a. Create a Hibernate Configuration object that references the XML configuration file
b. Build a Hibernate SessionFactory object from the Configuration object
c. Finally, retrieve Hibernate Session objects from the SessionFactory and write the
data access logic for the application to allow the operations CREATE and
RETRIEVE

Creating Database and Tables in Mysql


Creating Database And Tables In MySQL
CREATE TABLE `emp` (
`empid` int(10) NOT NULL,
`empname` varchar(20) NOT NULL,
`empsname` varchar(20) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
ALTER TABLE `emp` ADD PRIMARY KEY (`empid`);
ALTER TABLE `emp`
MODIFY `empid` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;

Creating a Web Application, Adding The Required Library Files

1. open netbeans 8.2


2. click new project
3. click java web category
4. click web application project
5. click next
6. give project name : hibertest
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

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

Creating a Javabean Class, Creating Hibernate Configuration File, Adding a


Mapping Class

1. right click on project


2. hover new --> others
3. select hibernate category
4. select hibernate reverse engineering wizard
5. give file name : hibernate.reveng
6. select folder projectxx\src\java
7. click next
8. click add all button
9. 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>

10. right click on project


11. hover new --> others
12. select hibernate category
13. select hibernate mapping files and POJO from Database
14. in package write weit
15. click finish

Emp.java (pojo file)


package weit;
// Generated Sep 16, 2018 3:15:00 AM by Hibernate Tools 4.3.1
/**
* Emp generated by hbm2java
*/
public class Emp implements java.io.Serializable {

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

private Integer empid;


private String empname;
private String empsname;
public Emp() {
}
public Emp(String empname, String empsname) {
this.empname = empname;
this.empsname = empsname;
}
public Integer getEmpid() {
return this.empid;
}
public void setEmpid(Integer empid) {
this.empid = empid;
}
public String getEmpname() {
return this.empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
public String getEmpsname() {
return this.empsname;
}
public void setEmpsname(String empsname) {
this.empsname = empsname;
}
}

Emp.hbm.xml (mapping file)


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD
3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Sep 16, 2018 3:15:00 AM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="weit.Emp" table="emp" catalog="jpatest" optimistic-lock="version">
<id name="empid" type="java.lang.Integer">
<column name="empid" />
<generator class="identity" />
</id>
<property name="empname" type="string">
<column name="empname" length="20" not-null="true" />
</property>
<property name="empsname" type="string">
<column name="empsname" length="20" not-null="true" />
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

</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>

o org.hibernate.SessionFactory: Allows creating sessions. The SessionFactory caches


generate SQL statements and other mapping metadata that Hibernate uses at runtime
o org.hibernate.cfg.Configuration: Is used to configure and bootstrap Hibernate. It is
meant only as a initialization-time object. The application uses a Configuration instance to
specify the location of mapping documents and Hibernate-specific properties and then
create the SessionFactory
o org.hibernate.Session: Is the main runtime interface between a Java application and
Hibernate. This is the central API class abstracting the notion of a persistence service. The
main function of the Session is to offer create, read and delete operations for instances of
mapped entity classes
o org.hibernate.Transaction: Is a package, which abstracts the underlying transaction
mechanism [JTA or JDBC] and provides strategies for obtaining application server
TransactionManagers
o 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
o 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

Creating A Configuration Instance And Building A SessionFactory


o session Factory = new Configuration().configure().build SessionFactory();
o An instance of the Configuration interface is created. Using it's configure() method,
the

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

Obtaining A Session Object


o After obtaining the SessionFactory, Hibernate org.hibernate.Session objects can be
retrieved.
o hibSession = sessionFactory.openSession();
o The openSession() method of the SessionFactory interface creates an instance of
Session. This instance represents the primary interface to the Hibernate framework.

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

Running The Hibernate Application.


o Right click on write.jsp or read.jsp and run

WE-IT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS (THANE) 8097071144/55, WEB www.weit.in
24

You might also like