Download Java Enterprise Edition

Document related concepts
no text concepts found
Transcript
Aside: Java standards process

Sun’s original church and state model (now Oracle!)



Church: Java community process
State: Sun commercial business
Java Community Process


www.jcp.org
Java Service Request (JSR)



Unique id often used to describe pre-standards or recent
standards. e.g. JSR 168 is the Portlet specification
Test suite required for compliance
Reference implementation

Works but not much more
1
2
http://www.jcp.org/en/jsr/detail?id=31
3
EXAMPLE OF A
COMPONENT-BASED
ARCHITECTURE:
JEE OVERVIEW
JEE

Stands for “Java, Enterprise Edition”

It is a collection of standards


It is a component technology


JDBC, JNDI, JMX, JMS
Enterprise JavaBeans`, servlets
It is an “application server”

Following in the footsteps of Component Transaction Monitors
5
The JEE Architecture

Provides the benefits of components based development for
n-tier applications

These components are:


Business logic components:


Enterprise JavaBeans
Presentation logic components



Simpler to develop, portable, reusable
Servlets
JSP
These components are:


Configured via Deployment Descriptors
Deployed into containers
6
JEE Components





Application clients and applets run on the client
Java Servlet and JavaServer Pages (JSP ) are
presentation layer components that run on the
presentation server
Enterprise JavaBeans (EJB ) components represent
business components and run on the business logic
server
JEE components are written in Java in the same way
ordinary Java programs are created
All JEE components are deployed into containers
 Containers provide components with services such
as life cycle management, security, deployment, and
threading
7
Client-tier/web-tier
Components

Client can communicate with the application logic tier either
directly or through servlets or JSP that are located in the
presentation tier.

Servlets are special classes to realise the request-response
model (get, post of HTTP).
 JSP is a developer-friendly html-friendly wrapper over the
servlet classes.

Javascript is a client-side scripting language which runs in the
browser
 Javascript is not part of JEE.
 Javascript could be generated by a servlet or JSP.
8
Application logic tier
Components

This is defined by the logic that pertains to the (business)
application that is being developed.

Enterprise Java Beans (EJB) can be used to implement this
tier.

This tier receives the data from the client-tier and processes
the data and sends it to the RM-tier and takes the data from
the RM and sends it to the client-tier.
9
Resource Management System

In general this corresponds to the database (relational
database) and other information management system.

The other information management systems may include
Enterprise Resource Planning (ERP) and legacy system
connected through open database connectivity.

Or through the Java Connector Architecture (JCA)
10
Servlets and JSP
Static HTML Web Server Architecture

Web servers where designed to provide web browsers with HTML.

The HTML was read from text files by the server and sent to the client
using HTTP. The web server does not modify the HTML. This is now
termed static HTML serving
Server
Client
Web
Browser
HTTP
Get or Post
HTML
Web Server
files on disk
HTTP
12
HyperText Transfer Protocol
(HTTP)
1) Specify Get / Post
2) Request header
Web Client
request
3) Form Data
(Parameters)
Web Server
1) Status code
response
2) Response header
3) Content-Type
4) HTML pages / Other files
13
HTML -- Hyper-Text Markup
Language





A device independent way to represent documents
Specifies the formatting of document
 e.g., titles, paragraphs, fonts, colors, lists, tables
Hyperlinks permit references to other documents
References objects to be inserted into document
 e.g., images, applets, frames
Forms allow user input
 e.g., Text Fields, Buttons, Menus
 Action causes new HTTP request
14
A simple example of HTML
<HTML>
<HEAD>
<TITLE>HTML Reference Library</TITLE>
</HEAD>
<BODY>
<H1>HTML books for everyone</H1
<p>HTML library</p>
<UL>
<LI>HTML for beginners, Do it yourself!
<LI>HTML for experts
</UL>
<H2>Where can i buy it?</H2>
<Menu>
<li>IBM book storage
</Menu>
</body>
</HTML>
15
Requirement for dynamic pages

The Web pages need to be based on data submitted by the user

E.g., results page from search engines and order-confirmation pages at online stores

The Web page need to be built from data that changes frequently
(E.g., a weather report)

The Web page uses information from databases or other server-side
sources


for on-line shopping, employee directories, personalized and
internationalized content
Web browsers are dumb clients

Not designed to modify web pages

Stateless so they process each request in isolation without reference or
memory of what request came before it.
16
Dynamic Web-page Architecture

The web page is accessed an external program is run by the web
server.




The web server must be able to initiate and communicate with this
program
The program generates the HTML and the Web Server passes the
HTML back to the client
This process is transparent to the web browser, it does not know it
has been dynamically generated.
Common implementations: CGI Common Gateway Interface and
Servlets is another way.
Server
Client
HTTP
Get or Post
Web
Browser
Information about the
request
Web Server
HTTP
HTML
External
HTML
generator
17
Servlets

Servlets are programs written in Java which run on the web server
and communicate using with the web browser using HTTP and
HTML

The servlet runs inside a container called a Servlet Engine




Servlets communicate with the browser using only HTML and
HTTP


The communication services, security etc are provided by the container
Container runs within the JVM
Hides coding issues around with Sockets, TCP/IP or Java serialisation.
Compatible with all web browsers
Servlets run only on the server

Servlets do not need any component to be stored or installed on the
client
18
Servlet Lifecycle I:
1.
2.
3.
Web browser sends HTTP Post or Get message to Web Server
Web server redirect the request to the servlet. If the servlet is not
already loaded it loads it and calls the servlet's init method
The web browser passes the HTML request to the servlet's service
method
Server
Client
Servlet Container
HTTP
Get or Post
Web
Browser
Init
Web Server
Service
Servlet
19
Servlet Lifecycle II:
4.
5.
6.
Service method calls the doGet or doPost method of the servlet
Method executes and generates HTML which is passed back to the web
browser.
Threads in Service method exit
Server
Client
Servlet Container
Init
Web
Browser
Web Server
HTTP
Service
Servlet
HTML
HTML
doPost
doGet
Destroy
20
Servlet Lifecycle III:
4.
When the servlet container decides to unload the servlet it calls the
destroy method


At shutdown or if memory is short
Will not happen until all active threads finish (exit or time out)
Server
Client
Servlet Engine
Init
Web
Browser
Web Server
Service
Servlet
doPost
doGet
Destroy
21
Writing a Servlet

All Servlets extend the Servlet class


Normally extends HttpServlet which is derived from Servlet class
HttpServlet class provides default implementations of





Init: Need to override if some additional initialisation required such
as open a database connection.
Destroy: Need to override if some additional cleaning up required
such as closing a database connection.
Service: Not normally be overridden
doGet: Normally over-ridden as HTTP Get is the default web
browser request which causes the doGet method of the servlet to
be invoked.
doPost: Over-ridden if HTTP Post is responded to.
22
Worlds simplest Servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorldExample extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hello World!</title>");
out.println("</head>");
out.println("<body bgcolor=\"white\">");
out.println("<h1>Hello World!</h1>");
out.println("</body>");
out.println("</html>");
}
}
23
Passing a Parameter to Servlets

You can pass parameters to the servlet by creating a link to the servlet
and encoding one or more parameters in the link
The name of the
parameter

<a href="http://www.comp.dit.ie:8186/rbradley/servlet/param?p1=hello">
click here for a parameter example! </a>
The value of the
parameter


The servlet can access the parameter called p1 by using the
getParameter method in request.
The name of the
parameter
String parameter=request.getParameter("p1");
The HttpServletRequest
Object
Get parameter always
returns a String
24
Need for scripting

When the balance of the response document is HTML

Embed simple code in HTML pages rather than write lots of Java
to create HTML

HTML pages are modified by the code which determines
elements and data to display.

Classes and/or subroutines may be called to compute
information for inclusion in the web page. Existing APIs can
be invoked.
25
Some Approaches to Scripting

JavaServer Pages (JSP)

Active Server Pages (ASP)


ASP.NET


uses VBScript, Jscript, COM or ActiveX components, ODBC.
Similar to JSP, using C#
PHP

C-like syntax, many functions available
26
What are JSPs?

JSPs are design time entities which are converted into servlets
when loaded by the web server

JSPs look much more like standard HTML pages


Code is contained within <% %> markers and are referred to a scriptlets
Each JSP page states which programming language is contained
within its scriplets

<%@page language="java" %>

While theoretically it can be any language, in practice the language is
normally Java
27
Simple JSP Example
Specifies which language
the scriptlets are written in
Java import statement
<%@page language="java" import="java.util.Date" %>
<HTML>
<BODY>
<H1>Welcome to JSP</H1>
<B> Current Time is <%= new Date().toString() %> </B>
</BODY>
</HTML>
Java scriptlet embeds
invocation of method to get
the date as a string
Displays
Welcome to JSP
Current Time is Tue April 24 19:00:55 GMT+00:00 2001
28
Servlet with equivalent functionality
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Import java.util.Date;
public class ServWelcome extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
IOException, ServletException
Outputting of HTML with
{
response.setContentType("text/html");
outprintln() statements is
PrintWriter out = response.getWriter();
awkward.
out.println("<HTML>");
out.println("<BODY>");
out.println("<H1>Welcome to Servlets</H1>");
out.println(" <B>Current Time is "+ new Date().toString()+"</B>);
out.println("</BODY>");
out.println("</HTML>");
out.close();
}
}
29
Choosing JSP or Servlets

JSPs require less initialisation




JSP mixes code into the HTML




Simple things are easier to do in JSP than Servlets
Much harder to debug
Typical of scripts!
Best for lots of HTML (avoids the need to write lots of out.println("..")) and less Java
code
Large JSP pages can be difficult to find and read the code
Debugging JSP is difficult because the code is translated into another form (servlet)
before being run
Servlets mix HTML into the code


Large servlets can be difficult to find and read the HTML
Best for little HTML output and lots of Java code
30
JSP Lifecycle I:
1.
2.
Browser sends a HTTP Get or Post including a URL with a ,jsp extension.
Web server detects .jsp extension in the URL, it delegates the request to
JSP engine.
Server
Client
Servlet Engine
Web
Browser
Servlet
Web Server
JSP Engine
JSP Page
31
JSP Lifecycle II:
3.
4.
The JSP page is translated into a Java Servlet
The generated Servlet is loaded by the Servlet engine and handles the
request
Server
Client
Servlet Engine
Servlet
Web
Browser
Web Server
JSP Engine
JSP Page
32
JSP Lifecycle III:
Translation and compilation takes place only when the JSP is called first
time or when it is modified. All subsequent requests are handled by the
Servlet generated
5.


There is a slight delay in response first time due to translation and compilation phase
If there are any changes, Java/HTML page recompiles automatically
Server
Client
Servlet Engine
Servlet
Web
Browser
Web Server
JSP Engine
JSP Page
33
EJB and the EJB
Container
Enterprise Java Bean(EJB)

An enterprise bean is a server-side component that contains
the business logic of an application.

At run-time, an enterprise bean resides in an EJB container.

An EJB container provides the deployment environment and
runtime environment for enterprise beans including services
such as security, transaction, deployment, concurrency etc.

EJB container provides services to bean and manages its life cycle
35
Reminder: components, models
and frameworks
Interface that satisfies contracts
Component-type
Specific interface
EJB
EJB
Independent
deployment
Coordination Services (transactions, persistence..)
Component
implementation
Component
model
Component
Framework
EJB container
36
Session Beans




Created by a client and exist only for the duration of a
single session
Perform operations on behalf of the client inside the
container
Transient state: Do not represent data that is stored in a
database.
A logical extension of the client
37
Session Beans

Simple and easy to program.

For transient functions such as controller





Represents “conversational” state
Typically one per request
Data is non-persistent
Lifetime is limited by the client’s: once the client exits, the session
bean and data are gone.
Light-weight.
38
Entity Bean (up to EJB v3.1)

Entity Beans



Entity beans represent the business objects that need
persistence (need to be stored in a database.)
Represents persistent data in a database, as well as methods
that act on that data
Entity Beans are
 “Transactional” in behavior
 Can be shared among clients
 Persistent: data exists permanently after client quits.
 E.g. Corresponds to a row a relational database.
 The persistence (storing into the database) can be automatically
done by the “container” (CMP) or explicitly by the bean (BMP)
39
Entity Bean(EJB v3.1)

Move away from Entity beans and to use Java
Persistence API to support persistence of data
40
Message-Driven Bean

A message driven bean is an enterprise bean that allows J2EE
applications to process messages asynchronously.


Common mode of communication in enterprise applications
It acts as a listener – for messages sent by any other system or
component via a JMS messaging system
41

Retains no data or conversational state.
Core services: More later

Container managed persistence




Container managed transactions


Container does database operations automatically
Mapping back to the database is defined in the component’s
“deployment description”
Should work with any database.
One transaction per method call to EJB
Container managed security



EJB-container manages roles
Rights are applied per role to EJB
EJB can check permissions by using API provided by container
42
Linking it all together – servlet
and EJB communication
Linking servlets and EJBs
Servlet uses JNDI to find the EJB
Client creates or finds EJB
Client uses EJB business methods from the component interface
JSP example




<%@ page import="javax.naming.*,javax.rmi.PortableRemoteObject,
foo.AccountHome, foo.Account"
Initialise the JSP
%>
<%! AccountHome accHome=null;
Get the reference to the
public void jspInit() {
session bean (EJB)
InitialContext cntxt = new InitialContext( );
Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
accHome =
(AccountHome)PortableRemoteObject.narrow(ref,AccountHome.cl
ass); }
Create an instance of the
%>
session bean
<%
© IBM
Account acct = accHome.create();
acct.doWhatever(...);
%>
Call the method
doWhatever()
44
Enterprise Services & JEE
Enterprise services

To link applications together a number of additional
services are required




Naming
Transactions
Security
Management

Common functional requirements for all distributed
applications

Typically provided by a centralised server
46
JEE Enterprise Services

These are API definitions for these centralised services


Typically allow existing enterprise services to be
accessed easily from Java


The implementation is not specified
Services such as naming, security, messaging etc.
In most cases, these services can be accessed explicitly
or left to the container to interact with.
Enterprise Service 1:
Naming and Directory Services

Naming and Directory Services allow


Allows an application to find the resources its needs
Allows searching for components based on name or attribute

Terminology: A name is
 “Test Topic” (JMS topic)
 “www.ibm.com” (DNS address)
 “/usr/local/java/bin/javac” (File name)

Terminology: Binding is

Associating a name with an object.
48
Java Naming and Directory Interface

JNDI is an interface and can utilise different naming services


Reference


DNS, NIS, LDAP
Compact object representation, with information about how to
access the object
Context


A context is a set of name-to-object bindings, with an associated
naming convention.
E.g. Unix naming convention, “/abc/def”
49
Example of calling an EJB from a JSP
<%@ page import="javax.naming.*,javax.rmi.PortableRemoteObject,
foo.AccountHome, foo.Account"
Initialise the JSP
%>
<%! AccountHome accHome=null;
Get the reference to
public void jspInit() {
the session bean (EJB)
InitialContext cntxt = new InitialContext( );
Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
accHome =
(AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class); }
%>
<%
Account acct = accHome.create();
acct.doWhatever(...);
%>
Create an instance of
the session bean
Call the method
doWhatever()
50
Enterprise Service 2:
JMS - The Java Messaging Service

A Java API that allows applications to create, send, receive,
and read messages




Interface specification only
No vendor interoperability
Vendor-agnostic: the same API to access different MOM
vendors.
Two Domains

Publish/Subscribe


Use pub/sub messaging when each message can be processed
by zero, one, or many consumers.
Point-to-Point

Use when every message must be processed successfully by
one consumer.
51
What is messaging?

“e-mail for applications”

Asynchronous communication
 The sender and receiver do not have to be available at the same time in
order to communicate.

Loosely coupled


The sender does not need to know anything about the receiver, nor does
the receiver need to know anything about the sender; they only need to
know what message format and what destination to use.
Enterprise messaging requires additional Qualities of Service




Guaranteed delivery and fault tolerance
Load balancing
Scalability
Transactional support
52
Point-to-Point Messaging




Asynchronous RPC
Queue - “destination”
Producer is a “sender”
Consumer is a “receiver”
© IBM
53
Publish/Subscribe Messaging

Topic – “destination”





Typically associated with a
set of related messages
E.g. IBM stock prices,
weather reports etc
Producer is a “publisher”
Consumer is a “subscriber”
Publishers and subscribers
are generally anonymous

Unless the message
includes the information
© IBM
54
Enterprise Service 3: JDBC

JDBC is the Java API that provides vendor independent
connectivity to relational databases

JDBC functionality provides basic


connectivity and core database-related classes
The Standard Extension provides additional functionality



JNDI can be used to manage data sources and connections
Connection pooling provided by database vendors to enhance
performance
Support for distributed transactions, including support for the
standard two phase commit protocol used by the Java
Transaction API (JTA).
55
JDBC Code Example
Connect to the DB
Connection con = DriverManager.getConnection(url, "myLogin",
"myPassword");
String createTableCoffees = "CREATE TABLE COFFEES " +
"(COF_NAME VARCHAR(32), SUP_ID INTEGER, PRICE FLOAT, " +
"SALES INTEGER, TOTAL INTEGER)";
Create the query string
Statement stmt = con.createStatement();
stmt.executeUpdate(createTableCoffees);
Execute query
ResultSet rs = stmt.executeQuery( "SELECT COF_NAME, PRICE FROM
COFFEES");
while (rs.next()) {
String s = rs.getString("COF_NAME");
Execute another query
float n = rs.getFloat("PRICE");
and get return set
System.out.println(s + " " + n);
}
Parse return set into
java variables
56
Enterprise Service 4: Transactions

A transaction is a set of operations that moves data from one
consistent state to another

The set of operations is considered indivisible

If one or more operations fail, the entire set is undone


Success: the transaction "commits"
Failure: the transaction "rolls back"

The effects of a committed transaction are persistent

Transactional Client: A program which invokes methods on
transactional objects

Transaction Manager: A program that coordinates transaction
processing
57
Java Transaction API (JTA)

JTA is used by application developers
 Specifies the interface between the transaction manager
and all involved objects
 Main class: the UserTransaction interface.

Java Transaction Service (JTS) is used by developers of
transaction managers
 Developers of application servers, EJB containers, etc.


Very few people in the world!
Not used by application developers
58
Transactions and EJBs

Transactionality can be handled implicitly by the container


Container-managed transaction demarcation (CMT)
The EJB container manages transactions automatically

Interaction with databases




Including two-phase commit (2PC) for databases with JDBC
drivers that support XA
Starting and ending transactions
Creating and propagating the transaction context
However, bean-managed transaction demarcation (BMT) and
client-managed transaction demarcation are also available.
59
Security Basics: Authentication and
Authorization

Proof Of Identity (Authentication)


Verifies the identity of the user, by using
 Shared secret (password)
 Token (Kerberos Ticket or RSA Public Key)
Grant of Access (Authorization)


Identity verified, system has to decide what resources (data,
applications etc) the user should be allowed access, based on
time of day, IP address etc.
Usually defined on the basis of roles



Each user may have many roles
Each role has predefined access attributes
E.g. a user may have two roles of system admin and pay-roll
admin. In the second role, the user can execute the pay-roll
software.
60
Security Basics: Terminology

A principal is something that can be authenticated


Each principal has an associated set of security attributes



For example, a user or a server
Used to identify which resources the principal can access
Also used for auditing
A principal is identified using credentials



A credential contains or references security attributes
Credentials are acquired via authentication
Credentials can also be acquired through delegation from
another principal
61
Challenges of distributed security

Perimeter security is only the start



Primarily focused on external attack
Internal security focuses on auditing and policing good
behaviour.
Need to ensure authentication can be achieved securely

Single sign-on or passing around of authentication data.

Each task must be associated with a principal with valid
credentials and authorisations.

Across multiple domains, systems and applications.
62
J2EE Container-Based Security

Security for components is provided by the container in which they
run

When an EJB method is invoked, it is always with a given security
identity


Supports declarative security: defined using deployment descriptors



A principal and one or more roles
Includes definition of security roles, access control rules and
authentication requirements
Mapped by the application deployer to the specific runtime environment
Supports programmatic security: explicit use of security APIs by
application code

Provides increased flexibility
 e.g., the same method can function differently for different pricipals
63
Enterprise Service 5: Java
Authentication and Authorization
Service (JAAS)

JAAS has two purposes:



JAAS authentication is pluggable



Authentication of users, to reliably and securely determine who is
currently executing Java code, regardless of how the code is
running
Authorization of users to ensure they have the permissions
required to do the actions performed
Different underlying authentication technologies can be used
transparently to the client.
Usually implemented on Identity Servers.
JAAS authorization extends the existing Java security
architecture

Role based access control - based not just on what code is
running, but also on who is running it
64
Enterprise Service 6: Java Connector
Architecture

JCA allows resource adapters that support access to
Enterprise Information Systems (EIS) to be plugged into J2EE
products



Defines a connection management contract between a J2EE
server and a resource adapter to allow connection pooling to EIS
systems
A transaction management contract between the transaction
manager and an EIS that supports transactional access
 Also supports transactions that are managed entirely by an
EIS.
A security contract that enables secure access to an EIS
65