Moving to WebSphere Application Server V6 and Beyond By by pyw18970


									 Moving to WebSphere
Application Server V6 and
        By Colin Renouf
          Version 1.0
    Agenda: What will we cover?
   WebSphere Application Server v6 Changes
    • What are they? Why should we use them?
          i.e. Java Server Faces, SDO, EJB Dynamic Query

   J2EE 1.4 Changes
    • What are they? Why would we use them? What would we do
          i.e. JSP 2.0, EJB 2.1, JMS 1.1, etc

   The Future and Preparing for it Now…
    • What is coming along? What should we do differently?
          i.e. Java 5 “Tiger”, J2EE 1.5 and EJB 3.0
                      WAS 6 - Changes
   We will cover these in more detail later….

     • J2EE 1.4 support
            Enterprise Java Beans (EJB) 2.1
            Java Messaging Service (JMS) 1.1
            J2EE Connector Architecture (JCA) 1.5
            Servlet 2.4
            Java Server Pages (JSP) 2.0.
             All on a JDK 1.4.2 base.

     • Web Services Standards Support Enhancements
            Java API for XML-based RPC (JAX-RPC) 1.1
            Web Services for J2EE JSR109
            Soap with Attachments API for Java (SAAJ) 1.2
            Web Services Security (WS-Security)
            Web Services-Interoperability (WS-I) Basic Profile 1.1
            Java API for XML Registries (JAXR) 1.0
            Universal Description, Discovery and Integration (UDDI) v3

     • Service Data Objects (SDO) / JSR 235
             WAS 6 - Changes (2)
• JavaServer Faces (JSF) 1.0

• Programming Model Extensions (PME)

• Service Integration
      Integrated Web Services Infrastructure
                 WAS 6 - Changes (3)
   We will look at J2EE 1.4 support later….

   In this section we will cover

    • Java Server Faces (JSF)

    • Service Data Objects

    • Programming Model Extensions (PME)

    • Service Integration
           Web Services Standards Enhancements
               Java Server Faces (JSF)
   Java Server Faces (JSF) is a web application framework
    • Concentrates on page architecture and rich UI
    • Components can be extended, rendered, validated and built upon.
   Codebehind model like ASP.NET
    • Events being passed back to event listeners for handling.
   Uses a Front Controller servlet called the FacesServlet
   FacesContext used by developer for sharing information.
   UI components can target other technologies than HTML.
   For HTML JSF tags map back to JSF components.
   Developer creates event listeners and Java bean components
    to receive the data from the form.
   JSF-Expression language is similar in syntax to JSP-EL in JSP
    • Note that it uses “#” rather than the “$” of JSP-EL from JSP 2.0
   XML file (faces config) relates the bean to the page
            Java Server Faces (JSF) (2)
<HEAD>                                                                  JSF tag libraries for HTML
<%@ taglib uri="" prefix="f" %>             and core functionality.
<%@ taglib uri="" prefix="h" %>
<%@ page language="java“ ContentType="text/html; charset=ISO-8859-1“ pageEncoding="ISO-8859-1“ %>
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<TITLE>Test Faces</TITLE>
<%-- jsf:codeBehind language="java" location="/JavaSource/codebehind/" --%>
<%-- /jsf:codeBehind --%>
<f:use_faces>                                                                   Setup link to codebehind
<BODY>                                                                          module for event handling
     <h:form formName="setName" id="setName">
                        User Name: <h:input_text id=“setNameText“ value=“#{}” />
                        <h:commandButton type="submit" label="Submit" id="setNameCmd“
            action=“#{}” />
                        <h:output_label id=“getname“ value=“#{}” />
     </h:form>           Use JSF tag names
</BODY>                                                     Use JSF expression names to get and set
                         for the form and its
                         contents, and also                 the variables in the “model” Java bean
                       mark the HTML                      components, using names configured in the
                       body as belonging                  faces config file. A JSF expression uses the
                       to JSF.                            “#{xxx}” format.
                Service Data Objects
   Formerly WebSphere Data Objects, now SDOs with JSR235
   Provide a unified data access mechanism across
    heterogeneous data stores
    • Effectively provides a data mediation service that implements the
      Data Transfer Object (DTO) or Value Object pattern.
    • Supplements, not replaces other data access mechanisms

   Simplifies programming for data access
    •   Enhanced wizard and tool support
    •   EJB Mediator for Entity EJBs
    •   JDBC Data Mediator
    •   Compound SDOs can be navigated using simple XPath queries

   Why use SDO …? It makes creating applications a whole lot

   Beware though, although supported by the major AppServer
    vendors SDO’s are NOT part of the J2EE 1.4 standard!
           Service Data Objects (2)
To use SDO….
   Start by creating a “Dynamic Web Project” in RAD v6…
   Select the “WDO Relational database runtime” check box
    • Service Data Objects used to be called “WebSphere Data Objects”…
            Service Data Objects (3)
   On your JSF page select a control for displaying data
    directly from the palette….
   Here we have used the “Relational Record List Control”…
    • Give it a name - which will be the name of the mapping XML file
    • If you select “Add data controls”, bound HTML controls will be placed
      on the page to display the data
            Service Data Objects (4)
   Select the table you want it mapped to….
    • A database connection is required for this, so if you don’t have one
      already select “New…” and create one.
            Service Data Objects (5)
   Select the columns in the table you want to be mapped….
    • Related tasks can be seen as links on the right hand side of the
           Service Data Objects (6)
   Then define how each of the fields will be displayed…
           Service Data Objects (7)
   The code for mapping can be seen in the “Page Data” view
    at the bottom left of the screen.
   Supported data mechanisms for SDO can be seen in the
            Service Data Objects (8)
   The default output isn’t pretty, but does the job. However, it
    can be improved with minimal effort in the wizard and on the
    page during page design.
            Service Data Objects (9)
   The data mapping is defined under the dynamic web project
    /WEB-INF directory, in a subdirectory called “wdo”.
<?xml version="1.0" encoding="UTF-8"?>
< xmi:version="2.0"
   ere/sdo/mediator/jdbc/metadata.ecore" rootTable="//@tables.0">
 <tables schemaName="EMPLOYEE_SCHEMA" name="EMPLOYEE">
  <primaryKey columns="//@tables.0/@columns.0"/>
  <columns name="EMP_ID"/>
  <columns name="FIRSTNAME" type="4"/>
  <columns name="INITIALS" type="4" nullable="true"/>
  <columns name="SURNAME" type="4"/>
  <columns name="SALUTATION" type="4" nullable="true"/>
  <columns name="DEPT_ID"/>
           Service Data Objects (10)
   A “” class is
    generated that extends the
    “javax.faces.el.PropertyResolver” (i.e. the JSF Expression
    Lanaguage) to handle the property mapping

   A “” file handles some of the SDO
    mappings, with the specific code in the “codebehind” file for
    the JSF page - which extends it.

   A mediator is provided in the JSF “codebehind” file…

   JDBC is used to get the data and map it to the fields on the

   So for an example…..
              Service Data Objects (11)
package pagecode;
import;                                  mediator
import;                   classes
import commonj.sdo.DataObject;
import java.sql.Connection;
                                                                      Good old JDBC!
import java.util.List;
import javax.faces.component.html.HtmlDataTable;
import javax.faces.component.UIColumn;                                   Faces components
import javax.faces.component.html.HtmlOutputText;
                                                                         for the presentation
public class TestSDOFaces extends PageCodeBase {
  protected HtmlScriptCollector scriptCollector1;
  protected DataObject employeeParameters;
                                                                     Actual SDO data object!
  protected List employee;
  protected JDBCMediator employeeMediator;
  private static final String SDOConnection_name = "testSDO_Con2";
  private ConnectionWrapper SDOConnectionWrapper;
  private static final String employee_metadataFileName
     = "/WEB-INF/wdo/employee.xml";                                        XML file for the
  protected static final String[] employeeArgNames = {};                   data mapping…
  protected static final String[] employeeArgValues = {};
              Service Data Objects (12)
public DataObject getEmployee_EmployeeParameters() {                      Use the SDO mediator to
   if (employee_EmployeeParameters == null) {                             get the SDO data object
      try {
         employee_EmployeeParameters = getEmployee_EmployeeMediator()
         } catch (MediatorException e) { logException(e); }
   return employee_EmployeeParameters;
 public List getEmployee_Employee() {
   if (employee_Employee == null) { doEmployee_EmployeeFetchAction(); }
      return employee_Employee;
 }                                                                      Get the data itself and put
public String doEmployee_EmployeeFetchAction() {                        into a a List for use in
   try {                                                                mapping to the UI fields.
           employee_EmployeeArgNames, employee_EmployeeArgValues,
      DataObject graph = getEmployee_EmployeeMediator().getGraph(
      employee_Employee = graph.getList(0);
   } catch (Throwable e) { logException(e); }
   finally { SDOConnectionWrapper = null; }
   return "";
             Service Data Objects (13)
protected JDBCMediator getEmployee_EmployeeMediator() {
  if (employee_EmployeeMediator == null) {
                                                               Create the mediator and
     try {
                                                               map the table schema to it
           = JDBCMediatorFactoryImpl.soleInstance.createMediator(
      catch (Throwable e) {
  return employee_EmployeeMediator;

               Service Data Objects (14)
<%-- jsf:pagecode language="java” location="/JavaSource/pagecode/" --%><%--
   /jsf:pagecode --%>
<%@taglib uri="" prefix=”h"%>
                                                                                 Codebehind      file
                                              Use JSF HTML tags                  name
<%@ taglib uri="" prefix="f"%>

…                                                                     Get the data object and bind it!
<h:dataTable id="table2” value="#{pc_TestSDOFaces.employee_Employee}"
  var="varemployee_Employee" styleClass="dataTable" headerClass="headerClass"
    footerClass="footerClass" rowClasses="rowClass1" columnClasses="columnClass1" border="0"
    cellpadding="2" cellspacing="0">
 <h:column id="column4">
   <f:facet name="header">
     <h:outputText styleClass="outputText" value="Emp_id" id="text7">
     <h:outputText id="text8" value="#{varemployee_Employee.EMP_ID}"
        <f:convertNumber />                                                  Use a JSF-EL
     </h:outputText>                                                         expression to map a
 </h:column>                                                                 field in the data object
….                                                                           to the value output
          Service Data Objects (14)
Of course, you don’t NEED to know how it works…
   Just use the tools and let them do all of the hard work….
   The codebehind file works with the SDO and JSF code to
    get the data and do the binding….
   JSF Expression Language expressions are used to get the
    data and output it in JSF HTML fields.
   The JSF-EL expressions and what they map to in the table
    data can be seen on the JSF JSP page
         Programming Model Extensions
   Many extensions have moved from the WBISF/WAS-E
   Dynamic Query is one of the most powerful
    •   Supported by a stateless session bean
    •   Allows Java based criteria (I.e. a function) to be used at runtime for queries
    •   Allows multiple CMP or CMR fields to be returned in a query
    •   To use it code in an EJB method with transactional context
    String query = "select,object(e) from EmpBean e where e.salary<50000 ";
    InitialContext ic = new InitialContext();
    QueryLocalHome qh = (LocalQueryHome) ic.lookup("java:comp/env/ejb/query");
    QueryLocal qb = qh.create();
    while (it.hasNext() ) {
      IQueryTuple tuple = (IQueryTuple);
      System.out.println((String) tuple.getObject(1));
      EmpLocal e = (EmpLocal) tuple.getObject(2);

   This allows more complex queries to be built than using EJB-QL
    Programming Model Extensions (2)
   In RAD the “Snippets” can be used to produce the code
    • Simple substitution into a method can be performed - with the code
      shown previously
    • A wizard can be used for more complex examples - but this can be
    Programming Model Extensions (3)
   Dynamic Query - Simple invoke code substitution mechanism
    • Some variables can be edited in the generated code but this is limited
    Programming Model Extensions (4)
   Dynamic Query - Wizard mechanism
    • Either select an EJB reference or create a new EJB reference

The last dialog is more than a little cryptic
and unhelpful though!
    Programming Model Extensions (5)
   Last Participant Support
    • Allows non two-phase commit based systems to take part in distributed

   Startup Beans
    • Beans that perform an activity when an application starts up or stops
    • Add code to the start() and stop() methods respectively

   Scheduler Service
    • Perform EJB methods or send JMS messages to a schedule
    • Tasks can be scheduled using wsadmin or in code

   Object Pools
    • Allows applications to create and manage their own pools of objects - to
      avoid constant creation and destruction

   And others - some of which may appear in future J2EE
                Web Services Support
   Web Services Standards Support Enhancements in WAS 6

   All of these standards are supported in the WAS 6
    •   Java API for XML-based RPC (JAX-RPC) 1.1
    •   Web Services for J2EE JSR109
    •   Soap with Attachments API for Java (SAAJ) 1.2
    •   Web Services Security (WS-Security)
    •   Web Services-Interoperability (WS-I) Basic Profile 1.1
    •   Java API for XML Registries (JAXR) 1.0
    •   Universal Description, Discovery and Integration (UDDI) v3

   Service Integration Bus provides web services support along
    with the messaging engine

   This is easy to configure via the enhanced AdminConsole
           Web Services Support (2)
   Beware Tier Leakage!
    • When developing apps to support web services keep everything
    • Do NOT allow details of the web services standards support to be
      mixed with business code!

   Why?

    • There are lots of standards and they are improving all the time.


    • You may want to move some of the support out to another machine,
      such as a web services appliance, in the future….

   IBM have purchased DataPower to provide appliances to
    complement the WAS 6 web services functionality
             Web Services Support (3)
DataPower - An IBM Subsidiary.
   Appliances to support a web services infrastructure
     • Plug into the network to offload XML processing from the server
     • XML handled at machine code level
     • Integrate with Eclipse-based tools such as RAD
   XA35 XML Accelerator
     • Handles XML processing, such as XPath, XSLT, XSDs, etc
   XS40 XML Security Gateway
     • Like an XML Firewall that handles XML Encryption and WS-Security, etc.
   XI50 XML Integration appliance
     • Part of an Enterprise Service Bus
     • Maps from one target (COBOL Copybook, ASN.1, CICS) to another (i.e.
       SOAP, MQ)
        Web Services Support (4)
DataPower - An IBM Subsidiary.
                 J2EE 1.4 Changes
   WebSphere Application Server v6 supports J2EE 1.4,
    which has the following major changes
    • Enterprise Java Beans (EJB) 2.1
    • Java Messaging Service (JMS) 1.1
    • J2EE Connector Architecture (JCA) 1.5
    • Servlet 2.4
    • Java Server Pages (JSP) 2.0.
    •   JDK 1.4.X base.

   We will concentrate on JMS 1.1 and JSP 2.0

   The key aim of J2EE 1.4 is to make development MUCH
                         JSP Code Explained
<%@ taglib uri=“” prefix=“c” %>              Declare use of JSTL
<%-- A page to show some sample JSP syntax – both good and bad --%>                   JSP Comment
    int count=0;                                            JSP declaration of a page scoped count
   public void setCount(int value) { count=value; }
                                                            variable and a method to update it
  <HEAD>                                           JSP Expression         JSP scriptlets with mixed
      <TITLE>Hello World Sample JSP</TITLE>                               HTML tags. This is hard to
  </HEAD>                                                                 read and maintain because
                                                                          of the nesting, so embedded
         <H1>Hello World at <%= new Date().toString() %>!</H1>            scriptlets are best not used.
      </CENTER>                                                           The JSTL enables the same
          <TABLE>                                                         function to be performed
             <% for (int i=0; i < count; i++)                             more neatly.
                 { %> <TR><TD> <%= new Integer(i).toString() %>
                   <% setCount(i); }%>
              </TD></TR>                                        JSTL iteration over a set of items.
           <TABLE><c:forEach var=“item” begin=“0” items=“${set}”>
                     <TR><TD><c:out value=“${item}” /></TD></TR>
           <%@ include file=“standardFooter.html” %>               JSP include of an HTML to act
  </BODY>                                                          as a footer.
                         JSP Code Explained
<%@ taglib uri=“” prefix=“c” %>              Declare use of JSTL
          This is difficult to follow and over complicated. The
<%-- A page to show some sample JSP syntax – both good and bad --%>                   JSP Comment
          Java code in the scriptlet is particularly a problem
    int count=0;                                            JSP declaration of a page scoped count
                     since it doesn’t like like the rest!
   public void setCount(int value) { count=value; }
                                                            variable and a method to update it
  <HEAD>                                           JSP Expression         JSP scriptlets with mixed
                                  Scriptlets are BAD!!!!
      <TITLE>Hello World Sample JSP</TITLE>                               HTML tags. This is hard to
  </HEAD>                                                                 read and maintain because
                                                                          of the nesting, so embedded
         Mixing { and <% is also often a problem - particularly
         <H1>Hello World at <%= new Date().toString() %>!</H1>            scriptlets are best not used.
           when the code has to be deployed to be tested!
      </CENTER>                                                           The JSTL enables the same
          <TABLE>                                                         function to be performed
             <% for (int i=0; i < count; i++)                             more neatly.
                 { %> <TR><TD> <%= new Integer(i).toString() %>
                   <% setCount(i); }%>
              </TD></TR>                                        JSTL iteration over a set of items.
           <TABLE><c:forEach var=“item” begin=“0” items=“${set}”>
                     <TR><TD><c:out value=“${item}” /></TD></TR>
           <%@ include file=“standardFooter.html” %>               JSP include of an HTML to act
  </BODY>                                                          as a footer.
                Java Server Pages 2.0
   The aim of JSP for developing dynamic web pages with Java
    was “separation of concerns”.

   Web layout presentation skills and Java coding skills are
    very different
    • Not usually both found in a single person…

   JSP 1.X failed to completely separate knowledge of Java
    from the presentation
    • Scriptlets
           Embedded Java code made reading the page layout difficult

    • JavaBeans
           Limited property based functionality, and requires knowledge of how
            beans behave

    • Tags to make use of properties required knowledge of the Java
      servlet environment
           Processing directives require knowledge how the container behaves
             Java Server Pages 2.0 (2)
   JSP 2.0 is built on JSP 1.X, but allows more separation
    between the code and presentation. The big changes are:
    • JSP Expression Language (JSP-EL)
           JSP-EL allows evaluation of JavaBean properties, explicit object
            properties that are maps, or arrays using a simple scripting syntax.
           Use of JSP-EL allows powerful JSP files to be created without any
            knowledge of Java - It’s like JavaScript!

    • Tag Files
           A simple way of creating JSP templates and passing attributes to them
           Create a JSP page with common layout and JSTL code in it and a “tag”
            extension - then use it like a tag library

    • Simple Tag Libraries
           Coding of tag libraries in Java has been greatly simplified
           Boilerplate code is provided in the base class! Just how Java intended…
            JSP Expression Language
   JSP-EL allows evaluation of JavaBean properties, explicit
    object properties that are maps, or arrays
   Simple scripting syntax
   Implicit objects allow access to request parameters, session
    and application attributes, headers, and cookies.
   Under some circumstances even Java methods can be called.
    • They must be public static
    • The method and class are aliased in the Tag Library Descriptor (TLD) file
    • Parameters must be declared in the TLD

   “${…}” is used for JSP-Expression Language notation
   “.” allows the use of properties or maps
   “[]” allows the use of properties, maps, arrays, or a List.
   Syntax is the same as for the JSF-EL with Java Server Faces
         JSP Expression Language (2)
   Implicit objects are:
    • pageScope - A Map of the page scope attributes
    • requestScope - A Map of the request scope attributes
    • sessionScope - A Map of the session scope attributes
    • applicationScope - A Map of the application scope attributes
    • param - A Map of the request parameters
    • paramValues - A Map of the request parameter values for a parameter
    • header - A Map of the headers
    • headerValues - A Map of the header values for a header
    • cookie - A Map of the cookies
    • initParam - A Map of the context init parameters - NOT servlet init
    • pageContext - A pageContext object reference - NOT a Map - treat like a
          JSP Expression Language (3)
   Operators - just like any other language!
   Arithmetic
    •   Addition: +
    •   Subtraction: -
    •   Multiplication: *
    •   Division: / and div  [Supports dividing by 0 but gives infinity]
    •   Remainder: % and mod [Remainder against 0 gives an exception]
   Logical
    • AND: && and and
    • OR: || and or
    • NOT: ! and not
   Relational
    •   Equals: == and eq
    •   Not equals: != and ne
    •   Less than: < and lt
    •   Greater than: > and gt
    •   Less than or equal to: <= and le
    •   Greater than or equal to: >= and ge
         JSP Expression Language (4)
For example

   To put the “name” property of a “Person” JavaBean into a table
    field use:

   To put the third item of a List of “Products” into a table field use:

   To read the “username” request parameter, using the implicit
    parameters, use:
        JSP Expression Language (5)
   How do we benefit from this?

    • Combine with the Java Standard Tag Library (JSTL)

    • Coding dynamic web pages in what looks like HTML!

    • It’s a lot simpler than mixing Java!

   Lets look at an example…..

    • We want to see all of the parameters and headers sent up in
      a request
            JSP Expression Language (6)
<%@ taglib prefix="c" uri="" %>
<html>                                                                       JSTL core functionality is
                                                                             brought in with this tag
<head><title>Enumerate Headers and Parameters</title></head>
                                                                             library reference.
 <h1>Enumeration of Headers and Paramaters using JSTL and JSP-EL</h1>
 <br />
                                                           JSTL core “forEach” iteration functionality
 <hr />                                                    sets up a variable called “headerinfo” that is
 <h2>Headers</h2>                                          used to reference each item in the implicit
 <table>                                                   object Map of the HTTP headers.
 <c:forEach var="headerinfo" items="${header}" >
  <tr>                                              The “${XXXX}” tells the Expression Language
    <td>${headerinfo}</td>                          engine to evaluate the item inside the brackets. In
                                                    this case the “headers” implicit object java Map.
 </table>                                   Here the “headerinfo” variable is evaluated and substituted
                                            into the output stream..
 <hr />
 Calling Host: ${}
                                        The “host” string is used as a key to the “headers” map. Note
 <br />                                 the “member” type notation is used here, although an array
 <hr />                                 notation could also have been used, i.e. ${header[“host”]}
           JSP Expression Language (7)
                                                    Again, a JSTL loop that uses the “paraminfo”
 <c:forEach var="paraminfo" items="${param}" >
                                                    variable to represent each member in “param”
  <tr>                                              JSP-EL implicit object Map. This Map is an
    <td>${paraminfo}</td>                           important one as it represents the HTTP
  </tr>                                             request parameters sent from the HTML form
  </c:forEach>                                      on the web page!
  <hr />
  Values for the "name" parameter: <br />
  <c:forEach var="paramval" items="${}" >
     ${paramval} <br />
                                                    For multi-value parameters - like those in
  <hr />
                                                    check boxes or multiple selection list boxes
                                                    the “paramValues” implicit object Map is
</html>                                             used. The parameter name is used as if it were
                                                        a member variable, although the syntax
                                                        [“name”] should still work.
JSP Expression Language (8)
                                 Tag Files
• A means of creating reusable templates of JSP code
• No Java is required - only JSP and JSP-Expression Language
    • Code and presentation are separated properly!

• Create reusable JSP code fragments and save each in its
  own file in a directory with a “.tag” extension
• In the tag file
    • Define “attributes” (more akin to parameters) using the “attribute” tag
         <%@ attribute name=“blurb” required=“true” rtexprvalue=“true” %>

        • Give the attribute a “name” as a reference in the main JSP file
        • Say if the attribute is required using “required” (true or false)
        • Say if the attribute value can be calculated in JSP-EL using “rtexprvalue”
    • Use JSP code for the layout and JSP-EL for logic.
    • Tag libraries can also be used in the tag file.
                           Tag Files (2)
 In the JSP page
   • Use the “taglib” tag directive
        <%@ taglib prefix=“MyTags“ tagdir=“/WEB-INF/tags” %>

       • Define a “prefix” by which the tag file DIRECTORY can be referenced
       • Declare the tag file directory relative to the web application root using the
       “tagdir” directive

   • Code the JSP as usual.

   • Reference a tag file using the prefix and tag file name (without the
   “.tag” extension)
       <MyTags:BrandHeader blurb=“Think IBM” />

   • To include the body of the JSP document that is between the tag file
   tags use the JSP doBody tag
       <jsp:doBody />
                                 Tag Files (3)
   Think of these as a method to allow JSP templates…..
                                                       Include the tag file directory and give it a
JSP File – SomeFile.jsp                                prefix alias for use in this file.
<%@ taglib prefix=“MyTags“ tagdir=“/WEB-INF/tags” %>
    <HEAD>                                             Use the name and give a value for the
          <TITLE>Test Tag Files</TITLE>                attribute you want to substitute within the
    </HEAD>                                            expression in tag file.
          <MyTags:BrandHeader blurb=“Think IBM” />
</HTML>                                                Declare the attribute name as used in the
                                                       JSP, and say if it must be supplied (to allow
                                                       a default to be used in the code) and also
TAG FILE - BrandHeader.tag                             say if it can be calculated at runtime

<%@ attribute name=“blurb” required=“true” rtexprvalue=“true” %>

<img src=“images/IBMLogo.jpg”><br/>
<strong>${blurb}</strong> <br />
                                                       Use JSP Expression Language to perform
                                                       the substitution.
                              Tag Files (4)
                                   Declare the attribute names as used in the JSP, and say if they
TAG FILE - news.tag
                                   must be supplied and if they can be calculated at runtime.

<%@ attribute name="heading" required="true" rtexprvalue="true" %>
<%@ attribute name="colour" required="true" rtexprvalue="true" %>
<%@ attribute name="width" required="true" rtexprvalue="true" %>

<table width="${width}" bordercolor="${colour}" border="1" cellpadding="2"
      cellspacing="0">                                  Use JSP Expression Language to
<tr bgcolor="${colour}" color="#ffffff">                perform the substitutions.
      <td class="header" nowrap><h1>${heading}</h1></td>
      <td valign="top" class="contents"><jsp:doBody /></td>
                                                 The <jsp:doBody /> tag is used to substitute the
                                                 body of the JSP document between the tag file
                                                 tags in the calling JSP document.

   This tag file creates a box with a heading and a border…..
                                 Tag Files (5)
                                                          Include the tag file directory and give it a
TAG FILE - mynews.jsp                                     prefix alias for use in this file.

<%@ taglib prefix="n" tagdir="/WEB-INF/tags" %>
<%@ taglib prefix="c" uri="" %>
<html>                                                   We want to use JSTL in this file so let the
<head><title>Today's News</title></head>                 JSP engine know.
<body>                                                   Use the names and values for each of the
<h1 align="center">Today's News</h1>                     attributes to be substituted within the tag
<br/><hr/>                                               file.
<n:news heading="Important Stories" colour="#f0f0f0" width="480">
WebSphere 6 brings new features to the world of J2EE to make life easier!
<br /><hr />
<n:news heading="BBC News" colour="#f0f0f0" width="640">
<c:import url="" />
                                                Use the JSTL “import” functionality to include the
<br /><hr />                                    body of the tag from another web site. This will
</body>                                         NOT produce correct HTML since it includes the
</html>                                         <html> tag. This will be replaced in the tag file
                                                where the <jsp:doBody /> tag is used.
Tag Files (6)
                     JSP Tag Libraries
• Custom tags are used to include complex Java code in
  a JSP page
      Java Standard Tag Library (JSTL) is a good example

• Allows use of HTML skills to produce dynamic pages

• “Classic” tag libraries were complex to code with 4
  interfaces and 13 classes
      SimpleTag interface from JSP 2.0 fixes this - provides
       “boilerplate” code. Try to always use these!
      Different code and event return values for iteration and
       inclusion of a JSP body

• Tag Library Descriptor (TLD) file used to describe
  behaviour in XML
• In JSP the tag is given a prefix alias for identification
   <%@ taglib uri=“URILib” prefix=“tagprefix” %>
   i.e. <%@ taglib uri=“/WEB-INF/struts-html.tld” prefix=“html” %>
                    JSP Tag Libraries (2)
   “Classic” custom tag library class
    • either implements the “Tag”, “IterationTag”, or “BodyTag” interfaces
    • or extends the “BodyTagSupport” or “TagSupport” class
    • doStartTag() and doEndTag() methods are called when the start and
      end tags respectively are processed by the JSP engine
    • doAfterBody() is used for tags that iterate and expose the IterationTag
           Return value dictates whether iteration occurs and the JSP engine calls
            back into the tag library
           Tag library must keep a counter
           Allows the tag library access to the JSP file and its output stream

    • Also other standard methods and utility methods
           to access the environment (i.e. the pageContext output stream to access
            the body)

    • The rules for handling access to the tag body output stream are
    JSP Tag Libraries- Classic Tags (3)
package mytestLoopingTagLib;
                                                          This is a “classic” tag that implements the
import javax.servlet.jsp.*;
                                                          “IterationTag” interface to allow looping
import javax.servlet.jsp.tagext.*;
                                                          over the body elements. An alternative
public class MyLoopingTag implements IterationTag {       would have been to extend the “TagSupport”
  private PageContext pageContext;                        class to get some boilerplate code, but there
  private Tag parentTag;                                  is little gain in this.
  private int loopCounter = 0;
                                                          The JSP engine will give the library a
  public void setPageContext(PageContext pageContext) {   reference to the “pageContext” object to
    this.pageContext = pageContext;                       allow access to the rest of the page.

  public void setParent(Tag parentTag) {                   If the tag is nested the JSP engine will give
    this.parentTag = parentTag;                            a reference to the surrounding tag. This is
  }                                                        how the JSTL “choose” outer tag works
                                                           with the “when” inner tag.
  public Tag getParent() {
    return parentTag;
  }                                                        Attributes of the tag in the JSP, which
                                                           look and behave like HTML tag attributes,
 public void setLoopCount(int countAsTagAttribute) {       are passed into the tag handler with setters
    this.loopCounter = countAsTagAttribute;                - like for a Java bean. The attribute here is
  }                                                        called “LoopCount” so the method called
                                                           is “setLoopCount”
     JSP Tag Libraries - Classic Tags (4)
    public int doStartTag() throws JspException {
                                                     This is called when the JSP engine hits the start tag. If
      if (loopCounter > 0) {
                                                     we have a loop counter to iterate for then we want to tell
          return EVAL_BODY_INCLUDE;
                                                     the engine to include the tag body. If the loop counter is
      else {                                         zero or less then we don’t need the body in the output
          return SKIP_BODY;                          stream so tell the JSP engine. Note that if we had
      }                                              extended “BodyTagSupport” we could have returned
    }                                                EVAL_BODY_BUFFERED, and would have had a
                                                     “doInitBody()” call to handle as well!
    public int doAfterBody() throws JspException {
       loopCounter--;                                This is called when the JSP engine has finished putting
       if (loopCounter > 0) {                        the tag body into the output stream for every iteration.
          return EVAL_BODY_AGAIN;                    Just use the value of the loop counter to decide whether
      }                                              to iterate again or drop out to the end tag.
      else {
          return SKIP_BODY;
      }                                               This is called when the JSP engine hits the end tag and
    }                                                 the return value here tells the engine to continue
                                                      processing the rest of the page. A different return value
    public int doEndTag() throws JspException {       (SKIP_PAGE) tellls the JSP engine not to bother with
      return EVAL_PAGE;                               the rest of the page!

    public void release() {                            Unlike simple tags, classic tags are reused by the
    }                                                  container. This method is used to say it has finished.
      JSP Tag Libraries - Simple Tag (5)
package mytestLoopingTagLib;
                                                   This time the “SimpleTagSupport” class from JSP 2.0 is
import javax.servlet.jsp.*;
                                                   used, which provides most of the “boilerplate” code.
import javax.servlet.jsp.tagext.*;

public class MyLoopingTag extends SimpleTagSupport {
                                                            Attributes of the tag in the JSP, which look and
private int loopCounter = 0;
                                                            behave like HTML tag attributes, are passed
                                                            into the tag handler with setters - like for a Java
public void setLoopCount(int countAsTagAttribute) {
                                                            bean. The attribute here is called “LoopCount”
     this.loopCounter = countAsTagAttribute;
                                                            so the method called is “setLoopCount”. This is
                                                            the same as for “classic” tags.
public void doTag() throws JspException, IOException {
     for (int i=0; i < loopCounter; i++) {                  The “doTag” method is always overridden for
        getJspBody().invoke(null);                          simple tags and does all of the work of the
     }                                                      multiple methods for classic tags. Note it is
  }                                                         called only once and handles the iteration itself
}                                                           in this method, unlike for classic tags where it
                                                            asks the JSP engine to call it again.

 The getJspBody().invoke(null) call is used to
 output the tag body into the output stream, and         This does the same as the previous 2
 to output something different the “null” can be         slides for the classic tag handler. Note
 replaced with another                   that Simple tags are NOT reused by the
      Java Message Server (JMS) 1.1
   In JMS 1.02 messaging was split into point-to-point using
    Queues and publish-subscribe using Topics
    • Different code and different class hierarchies
    • Couldn’t use both in the same transaction
    • Difficult to configure
    • Difficult for the application server to optimise resources

   JMS 1.1 has changed to use a common hierarchy and code
    • Nature of the “send” is determined by the destination type, i.e. a queue
      or a topic.
    • Essentially the same code is required as for Point-to-Point in JMS 1.02
    • Can use both in the same transaction
    • Easier to configure
    • Allows the application server to optimise resources

   Messaging in WAS 6 has GREATLY improved!
                 Java & J2EE Futures
   Future WAS versions will support Java 5 and J2EE 5
    • Java 5 (Tiger)
           Java 5 is a very different beast to JDK1.4.2/Java 2
           Some of the lessons from Microsoft C# have been learnt
           All changes are beneficial, but one in particular can trip up existing code

   J2EE 5
    • Many changes planned, but EJB 3.0 is most significant and very different
           EJB 3.0 EJBs use Java 5 annotations and are coded like POJOs (“Plain Old
            Java Objects”)
           Note that they LOOK like POJO’s in code but AREN’T POJOs

   We will concentrate on the features to be aware of now…
   The release of WAS to support this is still some way off…
                         Java 5 (Tiger)
Java 5 (with a 1.5 JVM) has the following new features:
   Generics / Parameterised types
    • Essentially similar to “templates” in C++
    • Allows strongly typed utility classes to be developed, i.e. the new Collections.
    class MyGeneric<T> {
       T obj;                            The “T” placeholder is replaced with a real type
       MyGeneric (T obj) {               when the generic class is used.
         this.obj = obj;
       String getHandledName() {
         return obj.getClass().getName();
       }                                                  Say what type we want to use
    }                                                     to replace the generic type “T”.
    public class Demo {                                   Note the new syntax for type
       public static void main(String[] args) {           declarations and creation.
         MyGeneric<Double> test;
         test = new MyGeneric <Double> ();
         System.out.println(“My generic class is handling a “
            + test.getHandledName());
    }                OUTPUT>> My generic class is handling a java.lang.Double
                   Java 5 (Tiger) (2)
   Metadata / Annotations
    • More accurately, the ability to create custom annotations
    • Development time “notes” describing the usage of a method,
      interface, etc - but annotations do NOT change the runtime
    • Java has had annotations for a long time, i.e. @deprecated.
    • Can be used where other specifiers are used, i.e. public, static, etc
    • Like JavaDoc on serious steroids!
    • Can be used by tools to automatically generate code or to allow the
      infrastructure to better support the code intention - particularly
      important for EJB3.0!
    • Retention Policy controls how it is used
           SOURCE - Annotation is in the source file only
           CLASS - Annotation is stored in the class file but is not used at runtime
           RUNTIME - Annotation is stored in the class file and is available at

      UNDERSTAND THIS for migrating to EJB 3.0 in a future WAS
                     Java 5 (Tiger) (3)
    Metadata / Annotations (Contd)
                                                   Declare a “RetentionPolicy” to say how long
import java.lang.annotation.*;
                                                   we keep the annotation. Tools can use this
import java.lang.reflect.*;                        annotation at runtime.
@Retention(RetentionPolicy.RUNTIME)           The annotation “Rewrite” could be an
@interface Rewrite {                          “interface” or a “class”.
  String message() default "REWRITE THIS METHOD";
}                                             Variables are declared like methods and can
class testannotation {                             have default values.
   @Rewrite()                                      Just use the default value for “message”.
   public static void badMethod() {
     int x = 0;
     int y = 2;
     int z = y / x;
    @Rewrite(message = "THIS METHOD IS OKAY")
    public static void goodMethod() {
                                                    Change the message so tools can see we
      int x = 1;
                                                    want to say something different about this
      int y = 2;                                    message. This could be used with JUnit
      int z = y / x;                                test cases to identify methods we are ready
    }                                               to test.
                     Java 5 (Tiger) (4)
   Metadata / Annotations (Contd)
 public static void main(String[] args) {
   try {                                                     In our “tool” read the
     testannotation ta = new testannotation();               annotation at runtime.
     Annotation[] a = ta.getClass().getMethod(
        "goodMethod").getAnnotations();                      Note the new Java 5
     for (Annotation x : a) {                                “for” loop syntax.
        System.out.println("Good method annotation is " +
     System.out.println("Bad method annotation is " +
     catch (NoSuchMethodException e) {}                      In our “tool” read the
                                                             annotation at runtime.
}                  OUTPUT>>
                Good method annotation is @Rewrite(message=THIS METHOD IS OKAY)
                Bad method annotation is REWRITE THIS METHOD
                    Java 5 (Tiger) (5)
   Autoboxing and Auto-unboxing
    • Automatically coerce integral types (I.e. int, long, double, etc) to and
      from their Object equivalents without the use of wrapper classes (I.e.
      Integer, Long, Double, etc)
int testint = 5;           int testint = 5;
Vector v = new Vector();          Vector v = new Vector();
v.add(new Integer(testint));      v.add(testint);

Note the integral type being put straight into a Vector - which only takes Objects!

    • The work of the original code is still done under the covers.
            An integral type can be treated as an Object but IS NOT an Object
    • Beware as the types may not always convert the way you think!
    • Beware the type hierarchy                                       Object
            i.e. a Float is NOT compatible with a Double.
            A Float CANNOT be assigned to a Double
            BUT a float CAN be assigned to a double
                                                             Float             Double
                   Java 5 (Tiger) (6)
   Autoboxing and Auto-unboxing (Contd)
class testQuestion {                           This code fails to compile
     public double CalcArea(Integer radius) { with an “Incompatible
          System.out.println("Integer Area"); types” error.
          return Math.PI * radius * radius;
     }                                               Whilst autoboxing can
     public double CalcArea(Double radius) {         convert between integral
          System.out.println("Double Area");         types and “Number” based
          return Math.PI * radius * radius;          objects automatically, it
     }                                               does not automatically
     public double CalcArea(Float radius) {          convert between object
                                                     types unless they exist in
          System.out.println("Float Area");
                                                     the same type hierarchy. A
          return Math.PI * radius * radius;
                                                     “Double” is NOT a “Float”
     }                                               so cannot be converted
     public static void main(String[] args) {        using autoboxing, despite
          Double doubleValue;                        the fact that conversion
          Float floatValue = new Float(3.0);         would be automatic at the
          testQuestion tqObj = new testQuestion();   equivalent integral type
          doubleValue = floatValue;                  level.
          double area = (double) (float) tqObj.CalcArea(doubleValue);
          System.out.printf("Area is %3f", area);
                      Java 5 (Tiger) (7)
   Autoboxing and Auto-unboxing (Contd)
class testboxing {
   public double CalcArea(Double radius) {
       System.out.println("Double Area");
       return Math.PI * radius * radius;

    public double CalcArea(Float radius) {
                                                   Double Area
       System.out.println("Float Area");           Area is 28.274334
       return Math.PI * radius * radius;
                                                      Which method will
    public static void main(String[] args) {          be called? 3.0 can be
       testboxing tbObj = new testboxing();           coerced into either a
                                                      float or a double, but
       double area = tbObj.CalcArea(3.0);
                                                      is a double.
       System.out.printf("Area is %3f\n", area);
                     Java 5 (Tiger) (8)
    Autoboxing and Auto-unboxing (Contd)

    • For your code to work in future version of WAS….

    • DON’T have methods that are too similar in signature
        • The autoboxing of values may not turn out the way you think!

    • DON’T just expect to swap integral types and objects

    • BE EXPLICIT when giving using values,
        • i.e. use 3.0f instead of 3.0 or 6L instead of 6

    • OTHERWISE strange bugs can appear and be hard to find when
    upgrading exiting code…..
                      Java 5 (Tiger) (9)
   Enumerations
    • Allows for grouping of constants - this is useful with static imports
    enum Fruits { Tomato, Orange, Apple }

   Enhanced “for each” loop
    • Allows iteration over a collection of objects
                                                            Iterate over all of a set of objects.
           for (Annotation x : a) {
        System.out.println("Good method annotation is " +

   Variable Arguments (Varargs)
    • Declare methods as supporting a variable number of arguments
           public static void testVarArgs(String … s)
              Declares a variable number of Strings that are referenced as an array “s”
    • This was needed to support the implementation of “printf” from C
                   Java 5 (Tiger) (10)
   Static Import
     • Allows the use of static members of a class without the class name
         import static java.lang.Math.pow;
         int nine = pow(3.0, 2);

   Formatted I/O

     • i.e. System.out.printf for the PrintStream class
     System.out.printf("Area is %3f", area);

     • Uses Java5’s new “Formatter” class for generic and complex formatting
     • Also uses variable argument support
     • Allows simpler coding of formatted strings and porting of C/C++ code

   Concurrent Utilities
     • Lots of new threading classes and methods for advanced thread
       management and synchronisation

   Enhanced Garbage Collection
     • New JVM parameters allow proper control of garbage collection - at last!
                                     EJB 3.0
   Annotations can be used to replace the Deployment Descriptor
     @Stateless public class MyBean implements MyBusinessInterface {…}

     • But Deployment Descriptors can still be used
     • Here MyBusinessInterface is a Plain Old Java Interface
     • Session Beans and Message Driven Beans must have business interfaces

   Annotations are used
     •   to specify container behaviour
     •   to request services and resources
     •   to define Object-Relational mappings for CMP Entity Beans
     •   to automatically generate interfaces

   Home interfaces are no longer used

   Local and Remote interfaces are generated using the annotation information
    and expose the Business Interface methods

   Business Interface methods make EJBs look like POJOs

   Still have event call backs
     • These can be handled in separate “Callback listener” classes or defined and
                                 EJB 3.0 (2)
   Stateless Session Bean
    • Example from the EJB 3.0 Specification
    • Business Interface
    public interface Calculator {
      public float add (int a, int b);
      public float subtract (int a, int b);
    • Stateless Session Bean
    @Stateless public class CalculatorBean implements Calculator {
     public float add (int a, int b) {
       return a + b;
        public float subtract (int a, int b) {
          return a - b;

   Could have use the “PreDestroy” or “PostConstruct” call back methods
                             EJB 3.0 (3)
   Stateful Session Bean
     • Example from the EJB 3.0 Specification
     • Stateful Session Bean
     @Stateful public class ShoppingCartBean implements ShoppingCart {
                 private float total;
                 private Vector productCodes;
                 public int someShoppingMethod(){...};
                 @PreDestroy endShoppingCart() {...};

             Note the annotation defining the event callback interface method. It doesn’t
             matter what the method name is when the annotation is used.

   ShoppingCart above is a local business interface like in the previous
                                EJB 3.0 (4)
   Entity Bean
     • Example from the EJB 3.0 Java Persistence API Specification
 @Entity public class Customer implements Serializable {
  private Long id;
                                        Define this as an entity bean….
  private String name;
  private Address address;
  private Collection<Order> orders = new HashSet();
  private Set<PhoneNumber> phones = new HashSet();
  public Customer() {}
  @Id                                 Note the annotation defining the unique ID field.
  public Long getId() { return id; }
  public void setId(Long id) { = id; }
  public String getName() { return name; }
  public void setName(String name) { = name; }
  @OneToMany                         Note the annotation defining the cardinality for the ORM
  public Collection<Order> getOrders() { return orders; }
  public void setOrders(Collection<Order> orders) {
     this.orders = orders;
                                EJB 3.0 (5)
   Entity Beans (Contd)
     • Oracle are EJB 3.0 Specification Lead - so there are similarities to
       Oracle TopLink
     • Use their web site for excellent tutorials - including preparing for EJB3.0

@Entity                                                            Define this as an entity bean….
@Table(name = "EMP")                                                   Say what table it maps to
public class Employee implements {
    private int empNo;
    private String eName;
    private double sal;                     Say what field is the primary key, what it maps to
    @Id                                     in the table, and if it is also the primary key there.
    @Column(name="EMPNO", primaryKey=true)
     public int getEmpNo() { return empNo; }
     public void setEmpNo(int empNo) { this.empNo = empNo; }
     public double getSal() { return sal; }
                          EJB 3.0 (6)
   Entity Beans (Contd)
    • Oracle are also leading development of new tools for EJB 3.0
      development for Eclipse - whether IBM use these or not is NOT clear
    • Download trail versions and have a play.
    • For the real thing you really want to come back to the IBM Rational tools!
    • Note that you can test your beans outside the container like POJOs!
                                                   For relationships between
                                                   entities define the relationship
                                                   and jojn conditions like for that
                                                   between tables in the relational
                                                   database model.
@ManyToOne(cascade=PERSIST, fetch=LAZY)
@JoinColumn(name="MANAGER_ID", referencedColumnName="EMP_ID")
public Employee getManager() {
return manager;
                          EJB 3.0 (7)
   And we haven’t even mentioned features such as Interceptors
    and contexts…
    • Interceptors allow the method invocation to be controlled inside the class
      or from another class
   Why is it important to know this now?
   Well, its important we don’t suffer from tier leakage….
    • Keep business and entity classes pure with no details as to the
    • Try to avoid calling into the container via the context in business
    • Keep anything that exposes the technology (i.e. HOW the bean methods
      work) in their own functions….
   If we do this moving to EJB 3.0 will be easier
   Do note that the beans themselves are NOT POJOs but look
    like them
    • Annotations allow the infrastructure to provide the entity bean support
Summary: What have we covered?
   WebSphere 6 New Features – Overview.
    • JSF Fully Supported
    • Web Services Enhancements - but beware tier leakage
    • Service Data Objects

   J2EE 1.4 Overview.
    • JSP 2.0 is greatly improved to allow simpler development
    • JSP-Expression Language, tag files, and simpler tag libraries
    • JMS 1.1 is much simpler

   Java and J2EE Futures
    • Java 5 (Tiger) - Learn annotations and beware of autoboxing
    • EJB 3.0 - Beware tier leakage to allow POJO-like EJBs


To top