How to Develop a Simple Crud Application Using Ejb3 and Web Dynpro

Similar documents
How to Reference External JAR Files in Web Dynpro DC in SAP NW Portal 7.3

How to Integrate SAP xmii Services with Web Dynpro Java

Creating Rules in Process Composer and using them in Process

SDN Community Contribution

Dialog Windows in WebDynpro ABAP Applications

Fetching User Details from the Portal and Displaying it in Web Dynpro with Authentication in the Portal

Freely Programmed Help- Web Dynpro

Integration of Web Dynpro for ABAP Application in Microsoft Share Point Portal

Upload Image file from system in Web dynpro view

Easy Lookup in Process Integration 7.1

Web Dynpro ABAP: Changing ALV Contents and Saving in Database

Creating Your First Web Dynpro Application

Custom Password Reset Tool in SAP Enterprise Portal Using Web Dynpro for Java

Web Dynpro Java for Newbies: a Quick Guide to Develop Your First Application

Step By Step Procedure to Implement Soap to JDBC Scenario

Table Properties and Table Popin

How to Create Top of List and End of List of the ALV Output in Web Dynpro for ABAP

Template Designer: Create Automatic PDF Documents for Attachment or Print Purpose

Federated Portal for Composite Environment 7.1

Dynamically Enable / Disable Fields in Table Maintenance Generator

WDJ - Application to execute MDX query using the BI Java SDK

POWL: Infoset Generation with Web Dynpro ABAP

Creation of Alert Data Service VC model for the BI query exception using Information Broadcasting

Using Radio Buttons in Web Template

Tutorial: Consuming Web Services in Web Dynpro Java

Web Dynpro: Coloring Table Conditionally

BAPI Execution in offline Adobe Form

How to Integrate Web Dynpro ABAP in Portal and Capture Portal Logon User Name

Step by Step Guide How to Use BI Queries in Visual Composer

Web Dynpro Interactive Forms Data Transfer and Scripting

How to Create Tables in MaxDB using SQL Studio

Table Row Popup in Web Dynpro Component

How to Create Business Graphics in Web Dynpro for ABAP

External Driver Configuration in Process Integration 7.1 Using JSPM

Displaying SAP Transaction as Internet Application in Portal

Linking Documents with Web Templates

SUP: Personalization Keys and Synchronize Parameter

MDM Syndicator: Custom Items Tab

Replacement Path: Explained with an Illustrated Example

External Driver Configuration for Process Integration 7.0

Step-By-Step guide to Virtual InfoCube Implementation

Integration Unit Testing on SAP NetWeaver Application Server

MDM Syndication and Importing Configurations and Automation

Uploading and Downloading Files in Web Dynpro Java

WDA Tutorial II: Using Select Options in a WDA Application

Displaying HR Organizational Tree Structure in Web Dynpro

Adding Files as Attachments to SAP Interactive Forms in the Java Environment

Add /Remove Links on ESS Home Page in Business Package 1.5

Implementing Business Objects in CAF and Developing Web Dynpro Application

NetBeans IDE Field Guide

SDN Community Contribution

E-Sourcing System Copy [System refresh from Production to existing Development]

MDM Import Manager - Taxonomy Data (Attribute Text Values) Part 3

How to Create and Execute Dynamic Operating System Scripts With XI

How to use Boolean Operations in the Formula as Subsidiary for IF Condition

Different Types of iviews in Enterprise Portal 7.0

Java EE 7: Back-End Server Application Development

Open Text DocuLink Configuration - To Access Documents which are Archived using SAP

Deploying BusinessObjects Explorer on Top of a SAP BI Query

Tutorial. Interactive Forms Integration into Web Dynpro for Java Topic: Working with the PdfObject API

Internationalization in WebDynpro ABAP Applications

SDN Community Contribution

Running JPA Applications with Hibernate as a Third-Party Persistence Provider on SAP NetWeaver CE

Working with the Roadmap UI Element in Web Dynpro ABAP

Step By Step: the Process of Selective Deletion from a DSO

Accessing ABAP Functions in Web Dynpro Java

Virus Scan with SAP Process Integration Using Custom EJB Adapter Module

SDN Community Contribution

BPM Multi Line Container in Integration Process

How to Display Traffic Lights for Exceptions in BI Web Reports

Open Hub Destination - Make use of Navigational Attributes

DB Connect with Delta Mechanism

Implying Security on Business Object XI 3.1 Universe having SAP BW as Source

Web Dynpro ABAP: Dynamic Table

SAP PI/XI: Generating Sequence Number Between Multiple Instances of Mapping Execution

Material Listing and Exclusion

SEEBURGER BICMD for SAP Exchange Infrastructure - Configuration Guide

Solution to the Challenges in Pivoting

Working with Tabstrip in Webdynpro for ABAP

Creating, Configuring and Testing a Web Service Based on a Function Module

Material Master Archiving in Simple Method

Federated Portal Network Remote Role Assignment Step-by- Step Configuration

Graphical Mapping Technique in SAP NetWeaver Process Integration

Changing the Source System Assignments in SAP BW Objects without Affecting the Data Modeling

Module 8 The Java Persistence API

ios Ad Hoc Provisioning Quick Guide

Developing Crystal Reports on SAP BW

Uploading and Downloading Files in Web Dynpro Java

Web Services Testing and SAP NetWeaver Application Server, Java EE 5 Edition

How to Default Variant Created for Report Developed In Report Painter/Writer

Leverage Rational Application Developer v8 to develop Java EE6 application and test with WebSphere Application Server v8

Synchronization of Services between the IBM WebSphere Services Registry & Repository and SAP s Services Registry

SAP Biller Direct Step by Step Configuration Guide

Developing Applications with Java EE 6 on WebLogic Server 12c

SDN Community Contribution

CO Java EE 7: Back-End Server Application Development

Creating Multiple Methods/Operations and Exposing BAPI as a Webservice

List of Values in BusinessObjects Web Intelligence Prompts

Setting up Connection between BW and R/3 for Data Load

SAP BI BO Unit/Currency Logic for Unknown Units Case Study

Transcription:

How to Develop a Simple Crud Application Using Ejb3 and Web Dynpro Applies to: SAP Web Dynpro Java 7.1 SR 5. For more information, visit the User Interface Technology homepage. Summary The objective of this tutorial is to provide a simple example of a CRUD application using EJB 3 as model layer and Web Dynpro as view/controller layer. Author: Isaías Cristiano Barroso Company: Independent Consultant - Brazil Created on: 07 September 2008 Author Bio Isaías Cristiano Barroso has worked with SAP Technologies since 2007. He is an official instructor for NetWeaver Java. The prior experience of Isaías has focused on various Java technologies including development with open source frameworks and proprietary suites like Oracle SOA Suite. Isaías has worked to many companies as System Architect in the last 5 years. Currently he is involved with technologies such as Composition Application Framework, Visual Composer, Web Services and Web Dynpro, Process Integration, NetWeaver Administration and researches about possibilities use of new NetWeaver features NetWeaver Galaxy and Flash Islands) on the companies. 2008 SAP AG 1

Table of Contents Introducion...3 Creating a dictionary project...4 Step 1: Creating the project...4 Step 2: Creating the table definition...7 Step 3: Deploying the dictionary...9 Creating EJB project...12 Step 1: Creating EJB project...12 Step 2: Enabling JPA Facet to project...15 Step 3: Mapping JPA Entity...21 Step 4: Create Session Bean...23 Creating Enterprise Application...26 Step 1: Create Enterprise Application...26 Step 2 : Building and deploying...30 Creating Web Dynpro Project...31 Step 1: Creating Web Dynpro Project...35 Next, select Web Dynpro...35 Step 2: Creating Web Dynpro Component...37 Step 3: Creating a Custom Controller...39 Step 4: Importing the EJB Model...40 Step 5: Creating context on custom controller...46 Step 6: Creating the crud search screen...50 Step 7: Creating and Testing Web Dynpro Application...61 Step 8: Creating the edit and create view...62 Step 9: Testing Application...79 Conclusion...79 Related Content...80 Disclaimer and Liability Notice...81 2008 SAP AG 2

Introducion This document will cover the process to develop a simple CRUD (Create, Retrieve, Update and Delete) application exploring the new characteristics of SAP NetWeaver CE 7.1 like Import of EJB Model, use of EJB 3 and JPA. The application will be developed to maintain a simple TODO list. To develop and run this sample will be necessary NetWeaver Developer Studio 7.1 and NetWeaver Application Server 7.1 This tutorial will be divided on follow sections: Creating a dictionary Project Creating a EJB Project Creating a Application Project Creating a Web Dynpro Project All development will be based on local development component Bellow follow screens that will be gotten on finish of this tutorial. 2008 SAP AG 3

Creating a dictionary project The first step is to create a dictionary project to define the database table structure do use on application. To do this you ll need to create a Dictionary Development Component Project. Step 1: Creating the project Open your developer studio and click File -> New -> Project -> Development Infrastructure -> Development Component. The screen bellow will appear, then click Next 2008 SAP AG 4

Select dictionary and click next On the next screen select the Local Development -> My Components and click next 2008 SAP AG 5

After this we need fill the information about the development component. Then click Next and Finish. The DCs archive will be synchronized and a dialog can be show to change to dictionary perspective, click yes, and the project will be show on the dictionary perspective like the follow screen 2008 SAP AG 6

Step 2: Creating the table definition Expand the dictionary project, right click on Database Tables and select Create Table like is shown on next screen To purpose of tutorial, on the next screen leave the prefix table as TMP and put the suffix as TODO, then click on Finish. So a screen like the following will appear Now, we need to create the columns to TODO table. 2008 SAP AG 7

Click on Add Column Button to add columns to table definition. Repeat the add column step, for the other two columns (TODO_DESCRIPTION and TODO_PRIORITY) 2008 SAP AG 8

Step 3: Deploying the dictionary To reduce complexity we ll deploy the dictionary using default system datasource. So assuming that a SID used was CE1, the table will be created on SAPCE1DB schema after deploy. Right click on dictionary project and choose Rebuild project to verify if all is fine. 2008 SAP AG 9

After rebuild, if no errors occur, is the time to create archive and deploy the dictionary, to SAP Application Server. Right click on dictionary project and choose Create Archive. Right click on dictionary project and choose Deploy. 2008 SAP AG 10

After successful deploy, the table will be created on default schema. Note: To visualize the database schema was used the Database Development perspective of Developer Studio and a connection was created using a MaxDB JDBC Driver. To reduce the number of tables listed, a filter was applied to get only tables that name starts with T. 2008 SAP AG 11

Creating EJB project Now, we need create the EJB project, in this project a Session Bean 3.0 will developed to act as the Façade that will be accessed by Web Dynpro, additionally a JPA Entity will be mapped to interact with TODO database table created from dictionary project. Step 1: Creating EJB project On your developer studio click File -> New -> Project -> Development Infrastructure -> Development Component. The screen bellow will appear, then click Next 2008 SAP AG 12

Next, select J2EE -> EJB Module On the next screen, select the Local Development -> My Components and click next 2008 SAP AG 13

After this, we need to fill the information about the development component. Click on Next and another screen will appear to choose what is the JEE version will be used, keep 5.0 and click on Finish. Then click Finish. The DCs archive will be synchronized and a dialog can be show to change to J2EE perspective, click yes, and project will be show on the J2EE perspective. 2008 SAP AG 14

Step 2: Enabling JPA Facet to project This step is important to make possible to mapping, automatically, of JPA Entity based on a data source (JDBC or Dictionary). As we have a dictionary we will map it from a dictionary, to show this feature, but the mapping can be done from database directly too. To use a dictionary as a data source, first open the Database Development perspective Window-> Open Perspective -> Other -> Database Development. After, you ll see a screen like bellow:: Right click on Databases node and select New, the following screen will appear to select the type of connection: 2008 SAP AG 15

Choose DDIC Design time and click Next, after this, fills the name of connection, description and select the option to Auto-connect as show on the following screen: Click Next to choose the dictionary project: Then click Next and a screen with Summary will appear, click Finish. 2008 SAP AG 16

After finish, verify if the dictionary information was retrieved with success, as show the following screen: After this, go to Java EE perspective and right click on the EJB project and choose Properties-> Project Facets, the screen bellow will appear with the current Facets: 2008 SAP AG 17

Click on Modify Project to add JPA Facet to project: 2008 SAP AG 18

Click Next, select Platform Generic and Connection TodoAppDict, this steps are show on screen bellow: Click on Finish, and Facet will be installed as show screen bellow 2008 SAP AG 19

Click Ok, the project will be enabled to use JPA. When the JPA facet is added to EJB project, a file named persistence.xml and orm.xml are created to configure information about JPA, in this project we will change only persistence.xml, when this file is created the persistence unit name is a name of project, let's to change its name to a friendlier name. To do it, open the EJB project -> ejbmodule-> META-INF and open persistence.xml, after change the file as show bellow. From: To: <?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="localdevelopment~localdevelopment~todo(2fejb~demo.sap.com"> <mapping-file> META-INF/orm.xml</mapping-file> </persistence-unit> </persistence> <?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="todounit"> <mapping-file> META-INF/orm.xml</mapping-file> </persistence-unit> </persistence> <<< INSERT CONFIGURATION OF DATASOURCE >>> 2008 SAP AG 20

Step 3: Mapping JPA Entity Right click on EJB project, select JPA Tools -> Generate Entities. A screen will appear to fill some parameters to generate class. On package input sap.com.todo.ejb.entity, select TMP_TODO, change the Entity Name to Todo instead TmpTodo. 2008 SAP AG 21

After click Finish, a new JPA Entity class will be generated on ejbmodule src folder. This class will contain JPA Annotations. 2008 SAP AG 22

Step 4: Create Session Bean Through Session EJB we can access the CRUD methods to maintain the TODO table, in this section we will create a Session Bean to be the Façade of our simple application. To create a new Session Bean, right click on EJB project and select New -> EJB Session Bean 3.0 Fill EJB Class Name with TodoServiceBean and Default EJB Package with sap.com.todo.ejb.service. As the EJB and Web Dynpro will be at the same server just Local interface is required. Click Next, then click Finish 2008 SAP AG 23

After Finish, the interface and implementation to Session Bean will be generated like screen bellow. Now, we will insert the following methods signature on the interface TodoServiceLocal.java @Local public interface TodoServiceLocal { Todo create(todo todo); Todo update(todo todo); void delete(integer pk); List<Todo> findbydescription(string description); } After, declared methods on interface must to be implemented on the Session Bean, before to implement the methods is important lets clear that JPA Entity Manager will provide methods to manipulate Todo Entity. The JPA Entity Manager will be injected through the following annotation: @Stateless(name="AgenciaGerServiceBean") public class AgenciaGerServiceBean implements AgenciaGerServiceLocal { } @PersistenceContext(unitName="todoUnit") private EntityManager em; When the code runs, the attribute em will be initialized with a instance of Entity Manager according with informations defined on persistence.xml file. 2008 SAP AG 24

The code bellow, shows the complete code to Session Bean class: @Stateless(name="TodoServiceBean") public class TodoServiceBean implements TodoServiceLocal { @PersistenceContext(unitName="todoUnit") private EntityManager em; public Todo create(todo todo) { em.persist(todo); return todo; } public void delete(integer pk) { Todo todo = em.find(todo.class, pk); em.remove(todo); } @SuppressWarnings("unchecked") @TransactionAttribute(TransactionAttributeType.SUPPORTS) public List<Todo> findbydescription(string description) { Query query=em.createnamedquery("todo.findbydescription"); description = description == null? "%%" : "%"+description+"%"; query.setparameter("description", description); List<Todo> result=query.getresultlist(); return result; } public Todo update(todo todo) { em.merge(todo); return todo; } } Note: The method findbydescription uses a named query Todo.findByDescription, this query needs to be defined on Entity. The Entity named query declaration will be show bellow. Todo.java Named Query @Entity @Table(name="TMP_TODO") @NamedQueries({ @NamedQuery(name="Todo.findByDescription", query="select t FROM Todo t WHERE t.tododescription LIKE :description") }) public class Todo implements Serializable { } 2008 SAP AG 25

Creating Enterprise Application To deploy the EJB project, will necessary to create an Enterprise Application. Step 1: Create Enterprise Application On your developer studio click File -> New -> Project -> Development Infrastructure -> Development Component. The screen bellow will appear, then click Next: 2008 SAP AG 26

Next, select J2EE -> Enterprise Application On the next screen, select the Local Development -> My Components and click next 2008 SAP AG 27

After this, we need fill the information about the development component. After click Next, select what is the JEE version, in this case 5.0 2008 SAP AG 28

After click Next, select which the project will packed by this Enterprise Application, select the TODO EJB and click Finish. Before execute the build and deploy of Enterprise Application, is necessary put datasource information on persistence.xml configuration file. To it open the ejb project -> ejbmodule-> META-INF and edit the file, we need to input the <jta-data-source> as child of <persistence-unit> as showed bellow. <?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="todounit"> <jta-data-source>todo/todods</jta-data-source> <mapping-file> META-INF/orm.xml</mapping-file> </persistence-unit> </persistence> Note: TODO/TODODS must be an Alias to System Data source 2008 SAP AG 29

Step 2 : Building and deploying To build and deploy the Enterprise Application project, open the Development Infrastructure perspective. Open Window -> Open Perspective -> Other -> Development Infrastructure Open Local Development -> My Components Right click on todo/app -> Deploy After successful deploy of Application, the last development component, Web Dynpro, will be created. 2008 SAP AG 30

Creating Web Dynpro Project This is the last point to our application, the MVC Web Dynpro Application. In this application we will access the Enterprise Java Bean through of Enterprise Application that was developed previously. To access the EJB through EAR, is necessary to change the permissions of EJB Development Component allowing Entity Forwarding, with this change another Development Component, in this case, Enterprise Application will can reference the public part of EJB DC. To do it, open the Development Infrastructure perspective -> My Components -> Select todo/ejb. On component properties select the Permissions tab and select the option Entity Forwarding Allowed. It will appear like screen bellow. After this, build de project. The EJB DC contains two public parts, COMPILATION (client) and ASSEMBLY (ejbjar), they are show at screen bellow 2008 SAP AG 31

The Enterprise Application uses only ASSEMBLY part, to import the EJB, we need of compilation part. To see the current dependencies of Enterprise Application DC, select the todo/app then select tab dependencies: On the above image just ejbjar (ASSEMBLY) part was selected, now select the client (COMPILATION) and on Dependency Details of right side select Build Time. Now, the Application can access the public part COMPILATION from EJB DC, but, to Web Dynpro to access, we need to create a Public Part on Enterprise Application DC of COMPILATION type, that point to Entity of EJB DC. 2008 SAP AG 32

Select todo/app, select Public Parts tab and click Add, put ejb_pp on Name and COMPILATION on Purpose, as show screen bellow After click Finish, right click on Public Part and select Reference Entities as screen bellow 2008 SAP AG 33

After, select My Components -> todo/ejb -> client as show screen bellow. After click Finish, build and deploy the Application project. Now, the project is ready to be imported by Web Dynpro as EJB Model, so the Web Dynpro project can be created. 2008 SAP AG 34

Step 1: Creating Web Dynpro Project On your developer studio click File -> New -> Project -> Development Infrastructure -> Development Component. The screen bellow will appear, then click Next: Next, select Web Dynpro 2008 SAP AG 35

On the next screen, select Local Development -> My Components and click next After this, we need fill the information about the development component. Then click next and Finish. The DCs archive will be synchronized and a dialog can be show to change to Web Dynpro perspective, click yes and the project will be show on the Web Dynpro perspective. 2008 SAP AG 36

Step 2: Creating Web Dynpro Component Now, we need create a Web Dynpro component that will be used to manage the EJB Session Bean, previously created. On Web Dynpro Explorer, expand the project and right click on Components and select Create Component, like show screen bellow: Put the name of component as CrudApp, select the option Default Window and Views like screen bellow: 2008 SAP AG 37

After, click Next, a screen like bellow, will appear After click Finish, the component will be created. At the screen bellow we have a view of the component. 2008 SAP AG 38

Step 3: Creating a Custom Controller A custom controller will be created, in this controller the EJB Model will be mapped. Double click on Web Dynpro component CrudApp and the toolbar select the option Create Custom Controller and click at component diagram on right side. A new dialog will open, fill the name with CrudAppCust. 2008 SAP AG 39

After this, the custom controller will shown at component diagram. Step 4: Importing the EJB Model Before start EJB Model import, is necessary to define the dependency between Web Dynpro and Enterprise Application project. To do it, on Development Infrastructure -> Local Development -> MyComponents and select todo/wdp. Select Dependencies tab and click add, then select MyComponents -> todo/app 2008 SAP AG 40

Click next and verify if Public Part is selected then click Finish After Finish, we can see the dependency as screen bellow. 2008 SAP AG 41

Now, the EJB can be imported. To do it, open Web Dynpro perspective and Double Click CrudApp, then click on Create Model option, and click on Component Diagram. After this, a Wizard will open to select the model type, select Enterprise JavaBean Model. 2008 SAP AG 42

Click next and fill Model Name as EJBCrudModel and fill Model Package as com.sap.demo.todo.wdp.model Click on Next and select todo/app Click on Next and select all available methods. 2008 SAP AG 43

Click on Next and a screen with the classes that will be generated will be show. After, click on Next and the a screen with the classes will be show separated by groups, for each method will be generated a corresponding Request object and, to each method that contain return, will generate a Response object, finally Model classes will be generated at Others group. 2008 SAP AG 44

Click on Next and a log will be show. Click Finish and model will be generated and will appear on Component Diagram as screen bellow. 2008 SAP AG 45

Step 5: Creating context on custom controller In this step the context of custom controller will provide access to EJB through EJB Model. Select Create Data Link and click on CrudAppCust and drag and drop to EJBCrudModel. After, a screen with available methods will be show, select and drag and drop the update and findbydescription methods to left side. The next screen shows the process to findbydescription 2008 SAP AG 46

Repeat the process to update method. Note that return node has a problem, it occurs because already exists a node with the name return and Response, that was created previously to findbydescription. To solve it change the name of return node to returnupdate and ResponseUpdate. The next screen show the return node changed. 2008 SAP AG 47

2008 SAP AG 48

After complete the mapping the context will be like screen bellow. Note: The EJB have 4 methods, and all method were imported, but just update and findbydescription were mapped to context, all methods will be used on the simple crud application. But only these will need to bind to UI. The others will be used just programmatically. 2008 SAP AG 49

Step 6: Creating the crud search screen The search screen will be created using the CrudAppView, the first step is mapping the context to custom controller context. Click on Create Data Link and Drag and Drop to CrudAppCust. It is the same procedure of Step 5. When the next screen appears drag and drop the Request_TodoServiceLocal_findByDescription node to ViewController context. After click Finish and the mapping will be complete. 2008 SAP AG 50

To get the search screen working correctly will be necessary initialize the node Request_TodoServiceLocal_findByDescription. To do it open the Java Editor of Custom Controller and locate the method wddoinit and put the following code. At others section of the Web Dynpro code, declare and initialize the model that will be used for other methods. This section can be found at end of file. //@@begin others EJBCrudModel model = new EJBCrudModel(); //@@end //@@begin javadoc:wddoinit() /** Hook method called to initialize controller. */ //@@end public void wddoinit() { //@@begin wddoinit() EJBCrudModel model = new EJBCrudModel(); Request_TodoServiceLocal_findByDescription request = new Request_TodoServiceLocal_findByDescription(model); wdcontext.noderequest_todoservicelocal_findbydescription().bind(request); //@@end } 2008 SAP AG 51

After this, the method to call the search method needs to be created on Custom Controller. Select the Methods tab and click on New button, select Method and click next, after fill the name as searchtodo, after click finish. Select File-> Save All Select the method and right click, then select Navigate To -> Implementation //@@begin javadoc:searchtodo() /** * Method declared by application. */ //@@end public void searchtodo( ) { //@@begin searchtodo() try { wdcontext.currentrequest_todoservicelocal_findbydescriptionelement(). modelobject().execute(); wdcontext.noderesponse().invalidate(); } catch (Exception e) { wdcomponentapi.getmessagemanager(). reportexception(e.getlocalizedmessage()); } //@@end } 2008 SAP AG 52

Now, the method searchtodo can be called by view. To do it, open CrudAppView and select Actions tab, click on New Button and put name SearchTodo 2008 SAP AG 53

Click on Finish and select File -> Save All Right click on SearchTodo action and select Navigate To -> Implementation Implement the method with the following code //@@begin javadoc:onactionsearchtodo(serverevent) /** * Declared validating event handler. * * @param wdevent generic event object provided by framework */ //@@end public void onactionsearchtodo(com.sap.tc.webdynpro.progmodel.api.iwdcustomevent wdevent ) { //@@begin onactionsearchtodo(serverevent) wdthis.wdgetcrudappcustcontroller().searchtodo(); wdcontext.noderesponse().invalidate(); //@@end } 2008 SAP AG 54

Now, we can create the UI to search. Open the CrudAppView and insert a Transparent Container as child of RootElement. Change the layout of RootElement to FlowLayout. Right click on it and select Apply Template, choose Form and click next 2008 SAP AG 55

Select Description and click next, after click Finish and the criteria input will show on search view. 2008 SAP AG 56

Now, we need to put the response data on screen, to do it, select Root Element and select Apply Template then choose the Table option. Click Next and select return node and click Finish. 2008 SAP AG 57

Click next, and place the todoid on the first position After select the table and change the width property to 700px. 2008 SAP AG 58

Insert a Button as child of RootElement, change text property to Search. Apply the SearchTodo action to Button. 2008 SAP AG 59

After this procedures, at outline of view, a screen like this should be appears. Now, change the labels according the following table: Default Label New Label description_label Description todoid ID tododescription Description todopriority Priority 2008 SAP AG 60

Step 7: Creating and Testing Web Dynpro Application Select Applications -> Create Application Set name CrudApp and click Next, select use existing component then Finish. Now, select the application and choose Deploy new Archive and Run. 2008 SAP AG 61

A screen like bellow will appear, click on Search to make a simple test, no data will return, but It will certify that all is ok. On the nest Step we will create the edit/create page of CRUD. Step 8: Creating the edit and create view The EJB Model contains separated methods to edit and create a new record. Only one view will use the node Request_TodoServiceLocal_update to bind data for the two operations. Programmatically, based on a boolean attribute that will be created on custom controller context, the correct method will be called. To do it, let s to create the boolean attribute. Open the CrudAppCust context, right click on Context root -> New -> Attribute 2008 SAP AG 62

On the next screen, select the option manually and fill the name with updatemode, then select type boolean. This will indicate if the record is on update mode or create mode.. After this, click Finish. Two methods will be created to initialize the mode of record (initedit and initcreate). Go to Methods tab of Custom Controller and create these methods, after File-> Save All. The methods body must be in according with code bellow. //@@begin javadoc:initedit() /** * Method declared by application. */ //@@end public void initedit( ) { //@@begin initedit() Request_TodoServiceLocal_update requestupdate = new Request_TodoServiceLocal_update(model); Todo todo = new Todo(model); WDCopyService.copyCorresponding(wdContext.currentReturnElement(), todo); requestupdate.settodo(todo); wdcontext.currentcontextelement().setupdatemode(true); wdcontext.noderequest_todoservicelocal_update().bind(requestupdate); //@@end } 2008 SAP AG 63

//@@begin javadoc:initcreate() /** * Method declared by application. */ //@@end public void initcreate( ) { //@@begin initcreate() Request_TodoServiceLocal_update requestupdate = new Request_TodoServiceLocal_update(model); Todo todo = new Todo(model); requestupdate.settodo(todo); wdcontext.currentcontextelement().setupdatemode(false); wdcontext.noderequest_todoservicelocal_update().bind(requestupdate); //@@end } Note: Both methods are using the request update node, this strategy was adopted to reduce redundancy to build a view to each one (edit and create). The data of operations are the same, so isn t necessary to duplicate the code. The WDCopyServices was used to copy data of a node to another with the same structure. The updatemode attribute is initialized according the operation. The methods to initialize the context were created, now is necessary create a method to save the record, this method must to decide if a update or insert operation will be called, this will based on updatemode attribute. At the methods tab of CrudAppCust, create a new method named savetodo, then File-> Save All. After, put the code bellow in the method. //@@begin javadoc:savetodo() /** * Method declared by application. */ //@@end public void savetodo( ) { //@@begin savetodo() try{ if (wdcontext.currentcontextelement().getupdatemode()){ wdcontext.currentrequest_todoservicelocal_updateelement().modelobject().execute(); } else { Request_TodoServiceLocal_create requestcreate = new Request_TodoServiceLocal_create(model); requestcreate.settodo(wdcontext.currentrequest_todoservicelocal_updateelement(). modelobject().gettodo()); requestcreate.execute(); wdcontext.currentcontextelement().setupdatemode(true); } wdcomponentapi.getmessagemanager().reportsuccess("operation was completed with success"); } catch (Exception e){ wdcomponentapi.getmessagemanager().reportexception(e); } //@@end } 2008 SAP AG 64

To complete the CRUD, the remove operation must exists. To this, execute the previous step to create a new method named removetodo. After, put the code bellow in the implementation. //@@begin javadoc:removetodo() /** * Method declared by application. */ //@@end public void removetodo( ) { //@@begin removetodo() try{ Request_TodoServiceLocal_delete requestdelete = new Request_TodoServiceLocal_delete(model); Integer pk = wdcontext.currentrequest_todoservicelocal_updateelement(). modelobject().gettodo().gettodoid(); requestdelete.setpk(pk); requestdelete.execute(); wdcontext.nodereturn().removeelement(wdcontext.currentreturnelement()); wdcontext.nodereturn().invalidate(); wdcomponentapi.getmessagemanager().reportsuccess("operation was completed with success"); } catch (Exception e){ wdcomponentapi.getmessagemanager().reportexception(e); } //@@end } Note: To remove operation, the pk is retrieved of current record and passed to method of EJB. After, the current element is removed of result list. 2008 SAP AG 65

The next step is create a new View to edit screen, select the Views of component, right click -> Create View On next screen, put view name as CrudAppEditView and click Finish. 2008 SAP AG 66

Now, is necessary to map the context of CrudAppCust to CrudAppEditView context. To do it, open the CrudApp component diagram. Click on Create Data Link and Drag and Drop the data link from CrudAppEditView to CrudAppCust. A dialog to mapping will appear, in it drag and drop node update and updatemode attribute. Click on Finish and the mapping is ready. The diagram should be like screen bellow. 2008 SAP AG 67

To build the edit/create view, open the CrudAppEditView and remove the DefaultTextView of RootElement. Insert a Group component child of RootElement, and right click and Apply Template. On next screen, select Form and click Next, then select the input parameters. 2008 SAP AG 68

Click Next, and place id field on the first position. Click Finish and change the labels of fields according to table bellow. Default Label New Label todoid_label ID tododescription_label Description todopriority_label Priority Group_Header Todo Detail Now, insert two buttons on RootElement with text Save, Cancel and Delete, at the later step we will set the actions to they. 2008 SAP AG 69

In this sample the ID will be input by user, so the field can be edited only to new records. To make this control, the attribute updatemode will be used. If in updatemode the field can t be edited. To do it, select the id field and select the property readonly, click on bind button and select the attribute updatemode.. On the next screen select the attribute updatemode. 2008 SAP AG 70

After click OK, the readonly property will use the attribute to control the edit status. To navigate from a screen to another, the plugs need to be created, select the Window and double click, initially only CrudAppView is on diagram.. 2008 SAP AG 71

Click on Embed existing View, and then click on diagram. A dialog will open to choose what view must be embedded. Select CrudAppEditView. After click Finish, and the view will appear in the diagram. Create an Outbound Plug on CrudAppView with name ToEditView, and create an Inbound plug with name FromEditView. 2008 SAP AG 72

Create an Outbound Plug on CrudAppEditView with name ToSearchView, and create an inbound plug with name FromSearchView. 2008 SAP AG 73

Now create a link between inbound plugs and outbound plugs. After it, the navigation can be done between the views. Open CrudAppEditView, and go to Actions tab and create a new action named Cancel, select ToSearchView for FirePlug option. This action will return to search view. 2008 SAP AG 74

After, click on Finish and create a new Action named Save Click Finish and then File-> Save All Go to Implementation of Save action. 2008 SAP AG 75

At the implementation, put the following code. //@@begin javadoc:onactionsave(serverevent) /** * Declared validating event handler. * * @param wdevent generic event object provided by framework */ //@@end public void onactionsave(com.sap.tc.webdynpro.progmodel.api.iwdcustomevent wdevent ) { //@@begin onactionsave(serverevent) wdthis.wdgetcrudappcustcontroller().savetodo(); wdthis.wdfireplugtosearchview(); //@@end } Now, create the last action, Delete. To this, create a new Action named Delete Click Finish and then File-> Save All Go to Implementation of Delete action. 2008 SAP AG 76

At the implementation, put the following code. //@@begin javadoc:onactiondelete(serverevent) /** * Declared validating event handler. * * @param wdevent generic event object provided by framework */ //@@end public void onactiondelete(com.sap.tc.webdynpro.progmodel.api.iwdcustomevent wdevent ) { //@@begin onactiondelete(serverevent) wdthis.wdgetcrudappcustcontroller().removetodo(); wdthis.wdfireplugtosearchview(); //@@end } Now, is necessary to set the actions to buttons Save, Cancel and Delete. To this, select the button and change the property onaction to Save, Cancel and Delete respectively. After, the edit view is fully configured. Now we need to add the edit and create actions to search view. Open the CrudAppView and insert two new button, Create and Edit. Note that buttons doesn t have actions associated. So let s to create the actions, select the Actions tab and create a new action named Create and select Fire Plug ToEditView, click on Finish, then click on save menu and goes to implementation method and put the following code. //@@begin javadoc:onactioncreate(serverevent) /** * Declared validating event handler. * * @param wdevent generic event object provided by framework */ //@@end public void onactioncreate(com.sap.tc.webdynpro.progmodel.api.iwdcustomevent wdevent ) { //@@begin onactioncreate(serverevent) wdthis.wdgetcrudappcustcontroller().initcreate(); wdthis.wdfireplugtoeditview(); //@@end } After, create a new action named Edit and select ToEditView for the Fire Plug option, click on Finish. Click on save menu and goes to implementation method and put the following code. 2008 SAP AG 77

//@@begin javadoc:onactionedit(serverevent) /** * Declared validating event handler. * * @param wdevent generic event object provided by framework */ //@@end public void onactionedit(com.sap.tc.webdynpro.progmodel.api.iwdcustomevent wdevent ) { //@@begin onactionedit(serverevent) wdthis.wdgetcrudappcustcontroller().initedit(); wdthis.wdfireplugtoeditview(); //@@end } With the actions created, set the actions to respective buttons (Create and Edit). 2008 SAP AG 78

Step 9: Testing Application Select CrudApp and Deploy new Archive and Run. The first screen provides description criteria to find TODOs, and a button to edit an existing TODO and another to create a new. At edit view, you can save or delete a existing TODO. To back to search screen the Cancel button can be used. Conclusion This is a very simple application that shows the development using EJB 3 and Web Dynpro. This can be improved with forms validation [Tutorial] 2008 SAP AG 79

Related Content Getting Started with Java Persistence API and SAP JPA 1.0 SAP NetWeaver J2EE Preview: Application Development with the EJB 3.0 Programming Model Basics of the Java Persistence API Understanding the Entity Manager For more information, visit the User Interface Technology homepage. 2008 SAP AG 80

Disclaimer and Liability Notice This document may discuss sample coding or other information that does not include SAP official interfaces and therefore is not supported by SAP. Changes made based on this information are not supported and can be overwritten during an upgrade. SAP will not be held liable for any damages caused by using or misusing the information, code or methods suggested in this document, and anyone using these methods does so at his/her own risk. SAP offers no guarantees and assumes no responsibility or liability of any type with respect to the content of this technical article or code sample, including any liability resulting from incompatibility between the content within this document and the materials and services offered by SAP. You agree that you will not hold, or seek to hold, SAP responsible or liable with respect to the content of this document. 2008 SAP AG 81