Developing an EJB3 Application. on WebSphere 6.1. using RAD 7.5



Similar documents
Implementing the Shop with EJB

Web Application Programmer's Guide

WebSphere and Message Driven Beans

How To Understand The Architecture Of Java 2Ee, J2Ee, And J2E (Java) In A Wordpress Blog Post

Java EE Introduction, Content. Component Architecture: Why and How Java EE: Enterprise Java

Creating Java EE Applications and Servlets with IntelliJ IDEA

OTN Developer Day Enterprise Java. Hands on Lab Manual JPA 2.0 and Object Relational Mapping Basics

This presentation will provide a brief introduction to Rational Application Developer V7.5.

IBM Operational Decision Manager Version 8 Release 5. Getting Started with Business Rules

Workshop for WebLogic introduces new tools in support of Java EE 5.0 standards. The support for Java EE5 includes the following technologies:

Configure a SOAScheduler for a composite in SOA Suite 11g. By Robert Baumgartner, Senior Solution Architect ORACLE

EVALUATION ONLY. WA2088 WebSphere Application Server 8.5 Administration on Windows. Student Labs. Web Age Solutions Inc.

Working with WebSphere 4.0

JBoss SOAP Web Services User Guide. Version: M5

Web Development in Java Live Demonstrations (Live demonstrations done using Eclipse for Java EE 4.3 and WildFly 8)

Struts Tools Tutorial. Version: M5

Tutorial c-treeace Web Service Using Java

Developing Physical Solutions for InfoSphere Master Data Management Server Advanced Edition v11. MDM Workbench Development Tutorial

WA2087 Programming Java SOAP and REST Web Services - WebSphere 8.0 / RAD 8.0. Student Labs. Web Age Solutions Inc.

Penetration from application down to OS

Catalog Web service and catalog commerce management center customization

Understanding class paths in Java EE projects with Rational Application Developer Version 8.0

Unique promotion code

Web Applications. For live Java training, please see training courses at

WebSphere Business Monitor V6.2 KPI history and prediction lab

Hibernate Language Binding Guide For The Connection Cloud Using Java Persistence API (JAP)

1 Introduction. 3 Open Mobile IS components 3.1 Embedded Database 3.2 Web server and Servlet API 3.3 Service API and template engine

PTC Integrity Eclipse and IBM Rational Development Platform Guide

IBM Business Monitor V8.0 Global monitoring context lab

Web Container Components Servlet JSP Tag Libraries

NetBeans IDE Field Guide

CONFIGURATION AND APPLICATIONS DEPLOYMENT IN WEBSPHERE 6.1

WebSphere Server Administration Course

IBM WebSphere Server Administration

Create a Web Service from a Java Bean Test a Web Service using a generated test client and the Web Services Explorer

WebSphere Business Monitor V7.0 Business space dashboards

Getting Started using the SQuirreL SQL Client

Deploying Physical Solutions to InfoSphere Master Data Management Server Advanced Edition v11

WebSphere Business Monitor V6.2 Business space dashboards

HP Client Automation Standard Fast Track guide

Web Service Caching Using Command Cache

BusinessObjects Enterprise XI Release 2

J2EE-Application Server

Supplement IV.E: Tutorial for Tomcat. For Introduction to Java Programming By Y. Daniel Liang

Building and Using Web Services With JDeveloper 11g

Development. with NetBeans 5.0. A Quick Start in Basic Web and Struts Applications. Geertjan Wielenga

IBM Rational Rapid Developer Components & Web Services

SOS SO S O n O lin n e lin e Bac Ba kup cku ck p u USER MANUAL

Using the DataDirect Connect for JDBC Drivers with the Sun Java System Application Server

Cloud Services ADM. Agent Deployment Guide

Java Server Pages combined with servlets in action. Generals. Java Servlets

System i Access for Web Configuring an Integrated Web Application Server Instance

ITG Software Engineering

Listeners. Formats. Free Form. Formatted

Intelligent Event Processer (IEP) Tutorial Detection of Insider Stock Trading

L01: Using the WebSphere Application Server Liberty Profile for lightweight, rapid development. Lab Exercise

JAVA PROGRAMMING PATTERN FOR THE PREFERENCES USABILITY MECHANISM

Setting up the Oracle Warehouse Builder Project. Topics. Overview. Purpose

Before you can use the Duke Ambient environment to start working on your projects or

Network DK2 DESkey Installation Guide

1. Tutorial Overview

Getting Started with Web Applications

How to install and use the File Sharing Outlook Plugin

How To Load Data Into An Org Database Cloud Service - Multitenant Edition

How to configure the DBxtra Report Web Service on IIS (Internet Information Server)

Virtual Office Remote Installation Guide

Video Administration Backup and Restore Procedures

IBM WebSphere Adapter for PeopleSoft Enterprise Quick Start Tutorials

This is a training module for Maximo Asset Management V7.1. It demonstrates how to use the E-Audit function.

Java. How to install the Java Runtime Environment (JRE)

Developing SQL and PL/SQL with JDeveloper

ORACLE BUSINESS INTELLIGENCE WORKSHOP

Upgrading MySQL from 32-bit to 64-bit

WA1826 Designing Cloud Computing Solutions. Classroom Setup Guide. Web Age Solutions Inc. Copyright Web Age Solutions Inc. 1

Building Java Servlets with Oracle JDeveloper

Active Directory Management. Agent Deployment Guide

Crystal Reports Installation Guide

Beginning with SubclipseSVN

Aspects of using Hibernate with CaptainCasa Enterprise Client

Administering batch environments

DEVELOPING CONTRACT - DRIVEN WEB SERVICES USING JDEVELOPER. The purpose of this tutorial is to develop a java web service using a top-down approach.

JAVS Scheduled Publishing. Installation/Configuration... 4 Manual Operation... 6 Automating Scheduled Publishing... 7 Windows XP... 7 Windows 7...

WebSphere Training Outline

Important Notes for WinConnect Server VS Software Installation:

Installing and Configuring DB2 10, WebSphere Application Server v8 & Maximo Asset Management

Ready, Set, Go Getting started with Tuscany

Instant Chime for IBM Sametime For IBM Websphere and IBM DB2 Installation Guide

Rational Application Developer v7.0 (RAD7) trial version. Installation guide

WebSphere Business Monitor V7.0: Clustering Single cluster deployment environment pattern

WebSphere Business Monitor V7.0 Installation and stand-alone server profile creation

Application. 1.1 About This Tutorial Tutorial Requirements Provided Files

Cloud Tools Reference Guide. Version: GA

MyanPay API Integration with Magento CMS

ACI Commerce Gateway Hosted Payment Page Guide

Magaya Software Installation Guide

Managing Data on the World Wide-Web

CIMHT_006 How to Configure the Database Logger Proficy HMI/SCADA CIMPLICITY

LABSHEET 1: creating a table, primary keys and data types

Transcription:

Developing an EJB3 Application on WebSphere 6.1 using RAD 7.5 Introduction This tutorial introduces how to create a simple EJB 3 application using Rational Application Developver 7.5( RAD7.5 for short ) and publish the application on a WebSphere Application Server 6.1(WAS6.1 for short). In this tutorial we use a WindowsXP copy, on that have been installed WAS6.1 with EJB3 Feature pack and RAD7.5. This tutorail is divided into 2 parts Part 1 Configurating RAD7.5 Part 2 Developing an application Part 1 Configuration RAD7.5 Application Developer is an Eclipse-based design and development toolset. It provides workspace management with its perspectives, editors, views, and plug-ins. If you have worked with Eclipse before, you should find it easy to design and develop enterprise applications with Application Developer. Start it with: Start Programme IBM Software Delivery Platform IBM Rational Application Developer 7.5 IBM Rational Application Developer. 1

Step1 Change the Perspectives to Java EE You can open the perspective by selecting Window Open Perspective, or by clicking the Open Perspective icon. Step 2 Creating a server One of the important views pinned to the Java EE perspective is the Servers View. It is the view of your configured servers. Right-click anywhere in the Servers view and select new Server Select WebSphere Application v6.1 Server and click Add to create our Server runtime environment. 2

Navigate to the WAS6.1 installation directory, in this sample, c:\ibm\websphere\appserver, click ok and 2 times next. 3

Because of the security setting of the server, we must enter the User ID and Password, in this sample, they both are admin, click Finish. Now there is a new Server entry in the Servers View. Step 3 Creating a Database connection Another important view of java EE perspective is the Data Source Explorer. It should locate in the same bar where the Servers Views locates. 4

If the view does not appear, click Window->Show View-> Data Source Explorer to open it. Click right button on Databases and select New Now select a DB2 for z/os database manager. In this tutorial we use DB2 on z/os, the database name is S1D931. Type S1D931 as Location, 134.2.205.54 as Host, 4019 for Port Enter your own username and password that you get from the Administrator. For example, username: prak435 password: 1234 5

Now a new database connection named S1D931 is created and appears in the view. After expanding the connection you will find too many schemas, because this database is used for many users. Click right button on this connection and click Properties. In the next Window choose Default Schema Filter on the left side, deselect Disable filter and enter your own username(case sensitive), for example PRAK435, click ok. Click F5 to refresh the connection view, there is only your schema left. 6

Step 4 Creating a table and inserting data Click right button on the S1D931, select New SQL Script In the text area enter following code to create a new table and insert some data. CREATE TABLE ITEM ( ID INTEGER NOT NULL PRIMARY KEY, NAME VARCHAR(20) WITH DEFAULT NULL, QUANTITY INTEGER WITH DEFAULT NULL ) Click right button anywhere in the text area and select Run SQL If the table is successfully created, the SQL Results View will show the following message. 7

Now we insert some date into the table, enter the following code in text area and execute them. INSERT INTO ITEM VALUES ( 1001, 'Book', 20); INSERT INTO ITEM VALUES ( 1002, 'CD', 20); INSERT INTO ITEM VALUES ( 1003, 'DVD', 20) The SQL Results View will show you whether the SQL codes are successfully executed. Part 2 Creating an Enterprise Application EJB3 exhances the EJB2.X and make a great progress. In EJB2.X all resources contact each other throught JNDI, EJB3 simplifies the model, the most resources can be defined using a tag @. A typicial EJB3 project consists of 4 parts. _JPA Project persists the data stored in a database. _Client Project define the business logic that can be accessed by remote user. _EJB Project implements the interfaces defined in Client project _Dynamic Web Project 8

Step 1 Creating an Enterprise Application Project Select File New Project. In the New Project wizard, select Java EE Enterprise Application Project In the EAR Application project panel, type Shop as the Project name.for Target Runtime, select WebSphere Application Server v6.1. For EAR version, select 5.0 and select Default Configuration for WebSphere Application Server v6.1 as Configuration. 9

Click Next. Do not select any existing modules (if there are any). Select Generate Deployment Descriptor. Click Finish. If you are not already in the Java EE perspective, you are prompted to switch to it. Click Yes 10

Do not worry about the error (the Red Cross icon in the Shop project). It is because the deployment descriptor file, application.xml, does not contain any modules. Step 2 Creating a JPA project Select File New Project, then select JPA JPA Project. Click Next. Enter ShopJPA as Project name, select Add project to an EAR, and select Shop as EAR Project Name. Notice the Configuration: Utility JPA project with Java 5.0. Click Next The JPA Facet panel is the most important panel in the JPA Project wizard. We specify how a JPA provider manages the entities and whether they should be listed in the persistence.xml file or not. You can optionally create an orm.xml file, which is used for entity-relational mapping. For Connection select S1D931 which is a DB2 11

connection we created in part 1. Click Finish Creating a JPA entity Click right button on ShopJPA project then select JPA Tools->Generate Entities Select S1D931 as Connection and PRAK435 (you should select your schema) as Schema. Click Next 12

Type shop as Package and select Item shown in Tables. Click Finish Now a entity bean is automatic created without any Typing. The source code is like the below text package shop; import java.io.serializable; import javax.persistence.entity; import javax.persistence.id; @Entity /* define an Entity Bean */ public class Item implements Serializable { @Id /* define the key for the bean */ 13

private int id; private String name; private int quantity; private static final long serialversionuid = 1L; public Item() { super(); public int getid() { return this.id; public void setid(int id) { this.id = id; public String getname() { return this.name; public void setname(string name) { this.name = name; public int getquantity() { return this.quantity; public void setquantity(int quantity) { this.quantity = quantity; Then we add 2 Queries, one without parameter, another with a parameter id. Click right button on Item shown in Project Explorer, select JPA Tools->Configure JPA Entities to open the Configuration window. Select Item from the table list and click next. Select Named Queries and click Add 14

Select all of the three Attributs, type getitem as Named Query Name, type select i from Item i in the text area of Query Statement Panel. Click OK 15

Click Add once again. Select all of the three Attributs, type getitembyid as Named Query Name, type select i from Item i where i.id =:id in the text area of Query Statement Panel. Click OK Click Finish Open the source code of Item.java, you will find the source code is changed. There are a few new lines to the code that are shown below in green.... @Entity @NamedQueries( { @NamedQuery(name="getItem", query = "SELECT i FROM Item i"), @NamedQuery(name="getItemByID", query = "SELECT i FROM Item i 16

WHERE i.id = :id") ) public class Item implements Serializable {... Mapping runtime enviroment Double click persistence.xml in ShopJPA project to edit it. Select JTA as Transaction Type, for both of JTA Data Source and Non JTA Data Source enter jdbc/db2, which is the Data Source we defined in WAS6.1. About how to define a data source in WAS6.1, please see tutorial Installation and Configuration of WAS6.1. Expand Persistence Unit Properties and add a new Property named openjpa.jdbc.schema to the value "PRAK435". 17

Click the Source tab to see the content of persistence.xml, it's shown below. <?xml version="1.0" encoding="utf-8"?> <persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"> <persistence-unit name="shopjpa"> <jta-data-source>jdbc/leia</jta-data-source> <non-jta-data-source>jdbc/leia</non-jta-data-source> <class> shop.item </class> <properties> <property name="open.jdbc.schema" value="prak435" /> </properties> </persistence-unit> </persistence> Save the Changes. Also add the class shop.item (as shown in the code above) into the source or add it via the GUI browser. 18

Step 3 Creating an EJB 3.0 project for the session bean In the Java EE perspective, select File New Project and then EJB EJB Project. Click Next. Enter ShopEJB as the project name, select Default Configuration for WebSphere Application Server v6.1, and add the project to the Shop enterprise application, click Next Select Create an EJB Client JAR module to hold the client interfaces and classes, and accept the default names. Select Create an EJB Client JAR module to hold the client interfaces and classes, and accept the default names. The EJB 3.0 project is accessed by Web clients that are developed with Application Developer as Dynamic Web Projects. The ShopEJBClient.jar contains public (business) interfaces of the EJBs, and as such, is the only jar file needed by clients (such as Web clients). The EJB Client project is therefore a dependency of the client projects that access the EJB 3.0 bean. Besides, it is always a good design approach to separate the public interface (the business interface of the EJB 3.0 bean) from its implementation (the implementation class of the EJB 3.0 bean). Having two projects with a well-established purpose makes their maintenance easy. 19

Click Finish Adding the persistence module to the EJB module The session bean for the shipping cart will access the Item entity bean. We add the JPA module as a dependency to the EJB client module: Click right button on the ShopEJBClient project and select Properties. Select Java EE Module Dependencies. Select ShopJPA.jar and click OK 20

Creating a business interface An EJB 3.0 session bean implements a business interface. We create this interface before we create the session bean. Create a business interface shop.cart in the ShopEJBClient project (under ejbmodule). The interface has four public methods 21

_ public void add(int id) Add an item to the cart. _ public void remove(int id) Remove an item from a cart _ public List<Item> getitems() List the available items in the store. _ public List<Item> checkout() Check out with the selected items. The code is displayed below package shop; import java.util.list; public interface Cart { public List<Item> getitems(); public List<Item> checkout(); public void add(int id); public void remove( int id); Creating a stateful session bean Having the business interface shop.cart defined, we create its implementation as a stateful session bean in the ShopEJB project. The stateful session bean can handle entities in sync with the database. Add ShopEJBClient and ShopJPA projects as dependencies of the ShopEJB project. Use the Java EE Module Dependencies in the Properties dialog for ShopEJB. Click OK. In the ShopEJB project, create the bean class shop.cartbean, which implements the shop.cart interface. The code is displayed below. package shop; import java.util.arraylist; import java.util.list; import javax.ejb.remove; import javax.ejb.stateful; import javax.persistence.entitymanager; import javax.persistence.persistencecontext; import javax.persistence.persistencecontexttype; import javax.persistence.query; @Stateful public class CartBean implements Cart { @PersistenceContext(type = PersistenceContextType.EXTENDED) EntityManager em; private List<Item> selecteditems = new ArrayList<Item>(); public void add(int id) { Query query = em.createnamedquery("getitembyid"); query.setparameter("id", id); Item item = (Item) query.getsingleresult(); 22

item.setquantity(item.getquantity()-1); selecteditems.add(item); @Remove public List<Item> checkout() { System.out.println("Checkout:"); Item[] items = selecteditems.toarray(new Item[ selecteditems.size()]); for (int i=0; i< items.length; i++){ Item item = items[i]; System.out.println(item.getId() + " " + item.getname()); em.flush(); return selecteditems; public List<Item> getitems() { return em.createnamedquery("getitem").getresultlist(); public void remove(int id) { Query query = em.createnamedquery("getitembyid"); query.setparameter("id", id); Item item = (Item) query.getsingleresult(); item.setquantity(item.getquantity()+1); selecteditems.remove(item); The stateful session bean uses an extended persistence context to keep the entities attached to the entity manager. The persistence context (the set of entities) is maintained between transactions rather than being discarded at the end of each transaction. The changes are written to the database at the end of every transaction, in this case are at the end of each add or remove method. When executing the method annotated with @Remove, the stateful bean is removed. In methods add and remove we use the named query getitembyid, which is defined in Item entity bean. Open the Properties and specify the ShopJPA and ShopEJBClient projects as its Java EE Module Dependencies Step 4 Creating an Dynamic Web Project Click Project->New->Dynamic Web Project. Type ShopWAR as Project name,choose Default Configurateion for WebSphere Application Server v.6.1 for 23

Configuration,select Add project to an EAR. Click Finish Open the Properties and specify the ShopJPA and ShopEJBClient projects as its Java EE Module Dependencies Create a servlet named shop.shopservlet by clicking right button on the Deployment Descriptor and New Servlet 24

Click Finish and the ShopServlet opens in the editor. Type the following code for the class package shop; import java.io.ioexception; import java.util.list; import javax.ejb.ejb; import javax.naming.context; import javax.naming.initialcontext; import javax.naming.namingexception; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import javax.servlet.http.httpsession; public class ShopServlet extends HttpServlet { private static final long serialversionuid = 1L; public static final String CART_REF_NAME = "shop.cart"; public ShopServlet() { 25

super(); protected void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getsession(); Cart cart = (Cart) session.getattribute(cart_ref_name); if (cart == null) { try { System.err.println("runs here"); Context ctx = new InitialContext(); cart = (Cart) ctx.lookup("java:comp/env/ejb/cart"); session.setattribute(cart_ref_name, cart); catch (NamingException ne) { throw new ServletException(ne); /**** the business logic ****/ java.io.printwriter out = response.getwriter(); // display the available items out.println("<h2>items</h2>"); List<Item> itemlist = cart.getitems(); Item[] items = itemlist.toarray(new Item[itemlist.size()]); for (int i=0; i< items.length; i++){ Item item = items[i]; out.println(item.getid() + " " + item.getquantity() + " " + item.getname()+ "<br>"); // fill the shopping cart cart.add(1001); // add a book to cart cart.add(1001); // add a book to cart cart.add(1003); // add a dvd to cart cart.add(1002); // add a cd to cart cart.add(1002); // add a cd to cart cart.add(1002); // add a cd to cart cart.remove(1001); // remove a book from cart cart.remove(1002); // remove a cd from cart // display the remaining items out.println("<h2>remaining Items</h2>"); itemlist = cart.getitems(); items = itemlist.toarray(new Item[itemlist.size()]); 26

for (int i=0; i< items.length; i++){ Item item = items[i]; out.println(item.getid() + " " + item.getquantity() + " " + item.getname()+ "<br>"); // checkout and list the content of the shopping cart out.println("<h2>checkout Cart</h2>"); itemlist = cart.checkout(); items = itemlist.toarray(new Item[itemlist.size()]); for (int i=0; i< items.length; i++){ Item item = items[i]; out.println(item.getid() + " " + item.getname()+ "<br>"); // remove session data session.removeattribute(cart_ref_name); protected void dopost(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException { doget(request, response); Mapping the EJB logical reference Open the Deployment Descriptor editor for ShopWAR Switch to Source tab of the Web Deployment Descriptor editor and add the ejb/cart reference. Because the Web application and the enterprise bean are in the same enterprise application, we can use ejb-local-ref element to create the reference <?xml version="1.0" encoding="utf-8"?> <web-app id="webapp_id" version="2.4"...> <display-name>shopwar</display-name> <servlet> <description></description> <display-name>shopservlet</display-name> <servlet-name>shopservlet</servlet-name> <servlet-class>shop.shopservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>shopservlet</servlet-name> <url-pattern>/shopservlet</url-pattern> </servlet-mapping> <ejb-local-ref> <description> 27

</description> <ejb-ref-name>ejb/cart</ejb-ref-name> <ejb-ref-type>session</ejb-ref-type> <local-home></local-home> <local>shop.cart</local> <ejb-link>cartbean</ejb-link> </ejb-local-ref> <welcome-file-list>.. </web-app> Step 5 Running project on Server Click right button on Shop project, choose Run As-> Run on Server, choose the server environment that we created in part 1. 28

Click Finish Waiting until all projects are started. Open a Web browser, type localhost:9080/shopwar/shopservlet, you will get the page like the figure shown below. 29

30