This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
SAP® Education SAP Developer Network Web Dynpro
Web Dynpro Java
Consuming EJB’s in Web Dynpro for CE 7.1
Written by Armand Wilson, Americas NetWeaver RIG Edited by Chris Whealy, EMEA NetWeaver RIG
Copyrights No part of this publication may be reproduced or transmitted in any form or for any purpose without the
express permission of SAP AG. The information contained herein may be changed without prior no-tice.
Some software products marketed by SAP AG and its distributors contain proprietary software compo-nents of other software vendors.
Microsoft®, WINDOWS®, NT®, EXCEL®, Word®, PowerPoint® and SQL Server® are registered trademarks of Microsoft Corporation.
IBM®, DB2®, DB2 Universal Database, OS/2®, Parallel Sysplex®, MVS/ESA, AIX®, S/390®, AS/400®, OS/390®, OS/400®, iSeries, pSeries, xSeries, zSeries, z/OS, AFP, Intelligent Miner, Web-Sphere®, Netfinity®, Tivoli®, Informix and Informix® Dynamic ServerTM are trademarks of IBM Cor-poration in USA and/or other countries.
ORACLE® is a registered trademark of ORACLE Corporation.
UNIX®, X/Open®, OSF/1®, and Motif® are registered trademarks of the Open Group.
Citrix®, the Citrix logo, ICA®, Program Neighborhood®, MetaFrame®, WinFrame®, VideoFrame®, MultiWin® and other Citrix product names referenced herein are trademarks of Citrix Systems, Inc.
HTML, DHTML, XML, XHTML are trademarks or registered trademarks of W3C®, World Wide Web Consortium, Massachusetts Institute of Technology.
JAVA® is a registered trademark of Sun Microsystems, Inc.
JavaScript® is a registered trademark of Sun Microsystems, Inc., used under license for technology invented and implemented by Netscape.
MarketSet and Enterprise Buyer are jointly owned trademarks of SAP AG and Commerce One.
SAP, SAP Logo, R/2, R/3, NetWeaver, Web Dynpro and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of SAP AG in Ger-many and in several other countries all over the world. All other product and service names mentioned are trademarks of their respective companies.
1 About the Author ..................................................................................8
2 Create Dictionary Project and Database Table ..................................9 2.1 Create Dictionary Project .................................................................................. 9 2.2 Create a Database Table ................................................................................ 12 3 Verify the Table and Add Rows .........................................................14
4 Create EJB Project and Persistent Entity Bean ...............................17 4.1 Create EJB Project.......................................................................................... 17 4.2 Create a POJO for the Entity Bean................................................................. 19 4.3 Annotate for Persistence................................................................................. 22 4.3.1 Manual Annotation ..................................................................................... 22 4.3.2 JPA Editor Annotation ................................................................................ 23 4.4 Annotate for Named Queries .......................................................................... 25 4.4.1 Manual Annotation ..................................................................................... 25 4.4.2 JPA Editor Annotation ................................................................................ 26 4.4.3 Finished Code for Enity Bean..................................................................... 27 5 Create and Configure Enterprise Application Archive ....................29 5.1 Create EAR Project......................................................................................... 29 5.2 Create the JDBC Data Source Alias ............................................................... 30 5.3 Create and Configure Datasource Descriptor for the EAR ............................. 32 6 Configure EJB Module for Access to Entity Bean...........................35 6.1 Create EJB Persistence Descriptor................................................................. 35 6.2 Create Session Bean ...................................................................................... 37 6.3 Implement the Session Bean .......................................................................... 38 6.4 Check the Implementation Using the Web Service Navigator ........................ 40 7 Make EJB Application Available to Other Projects .........................43
8 Create Web Dynpro Application........................................................47 8.1 Create the Web Dynpro Project ...................................................................... 47 8.2 Define Web Dynpro Project Structure ............................................................. 49 8.3 Create the EJB Model for the Web Dynpro Application .................................. 51 8.4 Create Context to Bind Controller to Model Data Structures .......................... 53 8.5 Bind View to Controller Context ...................................................................... 55 8.6 Create the View Controller’s Layout............................................................... 57 8.7 Add Java Code to the Action Event Handler method...................................... 61 8.8 Create and implement the invokeBean() method in the component controller63 8.9 Deploy and Run the Web Dynpro Application................................................. 64
Figure 37: Partially completed coding.................................................................................................24 Figure 38: Add the @Id annotation using the Java EE Annotations wizard .......................................25 Figure 39: Add the @NamedQueries annotation using the Java EE Annotations wizard..................26 Figure 40: Perform a DC Build of the project ......................................................................................28 Figure 41: You should only see success and warning messages ......................................................28 Figure 42: Select “Other” from the “New” side bar menu....................................................................29 Figure 43: Choose a DC type of “Enterprise Application”...................................................................29 Figure 44: Select which projects should be referenced by this EJB project .......................................30 Figure 45: Managing the Java Server’s Infrastructure through the NWA ...........................................30 Figure 46: Managing DataSources through the NWA ........................................................................31 Figure 47: Create a new JDBC DataSource.......................................................................................31 Figure 48: Define the JDBC DataSource properties...........................................................................31 Figure 49: Update the EAR project properties ....................................................................................32 Figure 50: Update the EAR project’s Facets.......................................................................................33 Figure 51: Add the SAP Data Source Alias Provider Module as a Project Facet...............................33 Figure 52: Edit the project’s data-sources-aliases.xml file..................................................................33 Figure 53: Add the alias name ............................................................................................................34 Figure 54: The finished chain of connections between the EAR DataSource descriptor and the actual
database table .............................................................................................................................34 Figure 55: Add the Java Persistence as a Project Facet....................................................................35 Figure 56: Select the SAP JPA Platform.............................................................................................35 Figure 57: Edit the persistence.xml file belonging to the EJB module................................................35 Figure 58: Edit the name attribute of persistence-unit ........................................................................36 Figure 59: Edit the jta-data-source attribute........................................................................................36 Figure 60: Create a new session bean ...............................................................................................37 Figure 61: Define the session bean properties ...................................................................................37 Figure 62: Generic Type warning from the compiler...........................................................................38 Figure 63: Edit the StorePosSessionLocal.java file ............................................................................39 Figure 64: Deploy the EAR file using drag and drop ..........................................................................40 Figure 65: Successful deployment dialog ...........................................................................................40 Figure 66: Select the web service.......................................................................................................41 Figure 67: Test the web service..........................................................................................................41 Figure 68: Test results from running the web service.........................................................................42 Figure 69: Open another perspective .................................................................................................43 Figure 70: Open the Development Infrastructure perspective ............................................................43 Figure 71: Select the pos_ejb DC .......................................................................................................44 Figure 72: Edit the DC’s permissions..................................................................................................44 Figure 73: Permit this DC to perform entity forwarding.......................................................................44
Figure 112: Select all the available attributes .....................................................................................56 Figure 113: Select the layout tab ........................................................................................................57 Figure 114: Delete the DefaultTextView UI element...........................................................................57 Figure 115: Select “Insert Child” from the right-click menu in the Outline View .................................57 Figure 116: Select the Group UI element ...........................................................................................58 Figure 117: Give the Group UI element a title ....................................................................................58 Figure 118: Use the template wizard to rapidly add UI elements .......................................................58 Figure 119: Select which context attributes need to be visualised .....................................................59 Figure 120: Change the table column text ..........................................................................................59 Figure 121: Layout of the first table column in the view editor............................................................60 Figure 122: Select the Button UI element ...........................................................................................60 Figure 123: Changing the properties of the Button UI element ..........................................................60 Figure 124: Creating an action object to link a client side event with a server side response ...........61 Figure 125: Save all your work so far .................................................................................................61 Figure 126: Open the Java editor for the view controller ....................................................................62 Figure 127: Finding the model object’s full package name.................................................................63 Figure 128: Rebuild the whole Web Dynpro DC.................................................................................64 Figure 129: Deploy new archive and run ............................................................................................64
1 About the Author Armand Wilson has over 17 years of software development experience including more than eight years developing large distributed applications using Java and over four years developing J2EE applications.
He brings extensive RDBMS experience including four years experience from Informix and Oracle in database and application server development.
Armand joined SAP in February 2002, starting in the role of managing J2EE support in Palo Alto for North and South America. During the last five years, Armand has worked in the NetWeaver Regional Implementation Group (RIG) and Product Management support for the SAP NetWeaver Foundation including SAP NetWeaver AS, SAP NetWeaver Portal, Web Dynpro, CAF, SOA, and software security development.
4. Build the project by right-clicking on the project name and selecting “Development Com-ponent->Build…”:
Figure 12: Build the new Dictionary project
5. Right-click again on the project name and select “Create Archive”. After the archive is successfully created, select Deploy from the same menu to deploy the project to the Java Engine. You will be asked to enter the user name and password for the SDM the first time you do this.
3 Verify the Table and Add Rows 1. Start the SQL Studio. Login using the correct settings for your installation. Server is the
name of the machine running the Java Engine and the password is the same as the Administrator password:
Figure 14: Example SQL Studio logon screen
2. Make sure nothing is in the filter and expand the SAP<inst>DB node (where <inst> is the instance name of your Java server). At the bottom of the list, select Continue re-peatedly until you come to the TMP_POS_STORES table.
Figure 15: Locate your new database table in SQL Studio
2. Enter the Package path (com.sap.rig.wdex) and class Name (StorePos) as shown be-low:
Figure 27: Enter the class and package name
3. Next to Interfaces, select the Add button. Type “Ser” in the filter box, “Choose interfaces” and select the java.io.Serializable interface. Select the OK button.
4. The Java class should appear under ejbModule. If it is not already opened, double click on the file name to open the Java editor.
Figure 30: The new Java file in the project hierarchy
5. Add the following class attributes to the class file. Be very sure to check that the attrib-ute names are exactly the same as the columns in the database table!
public class StorePos implements Serializable { private int storeNum; private String postingDate; private int posReported; private int posVaulted; private int posDiscrep;
Listing 1: POJO attributes
6. Create getters and setters for all the attributes by right-clicking in the anywhere in the Java editor and selectiong “Source->Generate Getters and Setters…”. Select all the at-tributes and select the OK button.
Figure 31: Use one of the source wizards to create Getter and Setter methods
7. You will notice following warning (yellow icon in left column) next to the class name:
Figure 32: Warning that the POJO lacks an attribute for version control
Although the class will compile and build without taking any action it is good practice to add the version control attribute for serializable objects. In this way, changes made to future re-leases can be tracked for compatibility. You can let the Eclipse framework add the attribute
for you by clicking the left mouse button while pointing at the icon. This will bring up a menu allowing you to choose to use the default serial version ID. Select the “Add default serial ver-sion ID” selection and the code will be added to the class automatically.
Figure 33: Use the Eclipse tools to add the version control attribute
Figure 34: The corrected source code
4.3 Annotate for Persistence We will now annotate the POJO to become an Entity Bean with object relational mapping to the database table we created earlier. You can add annotations manually or use the JPA Editor for this. Both methods are described below.
4.3.1 Manual Annotation
1. Add the import statements to the POJO class: package com.sap.rig.wdex; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table;
Listing 2: Import statement added manually
2. Add the following annotations to the class file:
a. The “@Entity” annotation informs the precompiler that the class is an entity bean.
b. The “@Table” annotation maps the persistence class to the database table, TMP_POS_STORES.
c. The “@Id” annotation identifies the table key. A table key is necessary to uniquely identify each table row to a particular entity.
@Entity @Table(name = "TMP_POS_STORES") public class StorePos implements Serializable { @Id private int storeNum;
Listing 3: manual addition of annotations
According to the philosophy of Java EE 5, defaults are assumed unless the annotations are used to indicate otherwise. According to these rules, if the database table was
named STOREPOS it would not be necessary to use the @Entity annotation. If the col-umn names of the database table were different than the persistent field name of the class, the “@Column” annotation could be used to map the database and persistent field names. In our case, the names are identical so the annotation is not necessary.
Case Sensitivity of Table and Column Names Unfortunately, the JPA specification does not define whether table and column names are case-sensitive. With SAP JPA 1.0, the following applies: If a table name or column name is specified explicitly, its case is respected. If the table name or column name is generated according to a default rule, upper case is assumed.
4.3.2 JPA Editor Annotation
1. Right-click on the class name in the Outline view and select “Java EE Annotations->Entity->Entity” to add the “@Entity” annotation including the import file.
Figure 35: Add the @Entity annotation using the Java EE Annotations wizard
3. Right-click on the storeNum attribute and select “Java EE Annotations->ORM->Id”.
Figure 38: Add the @Id annotation using the Java EE Annotations wizard
4.4 Annotate for Named Queries A named query is now a static query expressed in metadata. The query can be either a Java Persistence API query or a native query. This makes reusing queries very simple.
4.4.1 Manual Annotation
1. Add the following import statements to the Java code of the POJO. import javax.persistence.NamedQueries; import javax.persistence.NamedQuery;
Listing 4: Add the import statements for Named Quer(y/ies)
2. Add the NamedQuery to select all the objects from the database. The name of the query is findAllPos. @Entity @NamedQueries ( { @NamedQuery(name = "findAllPos", Query = "SELECT p FROM StorePos p") }) @Table(name = "TMP_POS_STORES") public class StorePos implements Serializable {
Listing 5: Add the Named Query
4.4.2 JPA Editor Annotation
1. Right-click on the class file name in the Outline view and select “Java EE Annotations->Entity->NamedQueries”. Edit the code as shown below:
Figure 39: Add the @NamedQueries annotation using the Java EE Annotations wizard
The result is exactly the same as shown in Listing 5.
The finished code for your new Entity Bean class should look as follows: package com.sap.rig.wdex; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; @Entity @NamedQueries( { @NamedQuery(name = "findAllPos", query = "SELECT p FROM StorePos p") }) @Table(name = "TMP_POS_STORES") public class StorePos implements Serializable { private static final long serialVersionUID = 1L; @Id private int storeNum; private String postingDate; private int posReported; private int posVaulted; private int posDiscrep; public int getStoreNum() { return storeNum; } public String getPostingDate() { return postingDate; } public int getPosReported() { return posReported; }
public int getPosVaulted() { return posVaulted; } public int getPosDiscrep() { return posDiscrep; } public void setStoreNum(int storeNum) { this.storeNum = storeNum; } public void setPostingDate(String postingDate) { this.postingDate = postingDate; } public void setPosReported(int posReported) { this.posReported = posReported; } public void setPosVaulted(int posVaulted) { this.posVaulted = posVaulted; } public void setPosDiscrep(int posDiscrep) { this.posDiscrep = posDiscrep; } }
2. Build the class to check for errors. Right-click on the project name, select “Development Component->Build…”. The results should appear in the Problems view as only info and green icons as shown below:
Figure 40: Perform a DC Build of the project
Figure 41: You should only see success and warning messages
5 Create and Configure Enterprise Ap-plication Archive
EJB modules are not application objects and thus cannot be deployed and run on the SAP AS Java. Therefore, an EJB module must be packaged into an EAR project, since this is the deployable unit for J2EE applications.
5.1 Create EAR Project 1. Create a new local development component of type “Development Component” and se-
lect the Next button:
Figure 42: Select “Other” from the “New” side bar menu
2. Select “Development Component” as per Figure 20.
3. Select J2EE->Enterprise Application for the type of development component and select the Next button:
Figure 43: Choose a DC type of “Enterprise Application”
3. Expand the node, LocalDevelopment and select MyComponents and the Next button as per Figure 6.
4. Name the component pos_ear and select the Next button. Make sure the “Java EE ver-sion 5.0” is checked and select the Next button again.
5. Select the EJB project, pos_ejb and select the Finish button:
Figure 44: Select which projects should be referenced by this EJB project
5.2 Create the JDBC Data Source Alias A DataSource object has a set of properties that identify and describe the real world data source that it represents. These properties include information such as the location of the database server, the name of the database, the network protocol to use to communicate with the server, and so on. Data sources in the Application Server implement connection pooling. We define an alias for the DataSource object in the NetWeaver Administrator. In this way, we have a central location to configure and administer all DataSource objects. We can refer to the alias in any EAR project using the DataSource descriptor for the EAR. Several applications can refer to the same DataSource alias and the Java Engine manages connection pooling for optimal perform-ance.
1. Start the NetWeaver Administrator from the home page of the Java Engine: http://localhost:50000 and select the “SAP NetWeaver Administrator” or access it directly using the link http://localhost:50000/nwa.
2. Select tabs “Configuration Management->Infrastructure” and the link, “Application Re-
sources”:
Figure 45: Managing the Java Server’s Infrastructure through the NWA
3. Select the “Create New Resource” button and “New JDBC DataSource Alias”:
Figure 47: Create a new JDBC DataSource
4. Call the data source alias SAP/POS and assign it the “JDBC System DataSource” (“DataSource Name”): SAP<inst>DB where <inst> is the name of your Java instance.
5. Under the General tab, expand the Aliases node and select the ALIAS node under “com.sap.datasource.default”. In the box for “Alias name”, enter SAP/POS. This will configure the Datasource descriptor to point to the Database Datasource Alias created in the previous section. Now any module associated with the EAR can utilize the de-scriptor to access the database.
Figure 53: Add the alias name
JDBC System DataSource
Database
JDBC DataSource
Alias
EAR DataSource Descriptor
Figure 54: The finished chain of connections between the EAR DataSource descriptor and the actual database table
6.1 Create EJB Persistence Descriptor To configure the EJB module to access the Entity Bean we must create a persistence descrip-tor to identify the DataSource and create a Session Bean to subsequently access the Entity Bean.
1. Select “Project Facets” and select the “Modify Project…” button as per Figure 49 and Figure 50 above.
2. Click to place a check mark next to the “Java Persistence” module and click on the Next button:
Figure 55: Add the Java Persistence as a Project Facet
3. Select”SAP JPA Platform” for the Platform. Select the Finish and OK buttons to close the dialog windows.
Figure 56: Select the SAP JPA Platform
4. Expand the META-INF node under the ejbModule of the EJB project and double-click on persistence.xml:
Figure 57: Edit the persistence.xml file belonging to the EJB module
6.2 Create Session Bean 1. Right-click on the EJB project and select New->EJB Session Bean 3.0:
Figure 60: Create a new session bean
2. Enter StorePosSession for the name of “EJB Class Name” and “com.sap.rig.wdex” for the package name. Name sure that only that Local is checked for “Create Business In-terface”:
6.3 Implement the Session Bean 1. Add the following import statement to the StorePosSession bean class:
package com.sap.rig.wdex; import java.util.List;
Listing 7: Import statement for Session Bean
2. Add annotation to the persistence context, “POS”, that we set in persistence.xml (Sec-tion 6.1, step 6). The annotation sets the context for the EntityManager that can be used to execute the named query, findAllPos, that we annotated in the Entity Bean class. public class StorePosSessionBean implements StorePosSessionLocal ( @PersistenceContext(unitName="POS") private EntityManager em; public List<StorePos> getStorePos() { List<StorePos> storePos = em.createNamedQuery("findAllPos").getResultList(); return storePos; }
3. You may notice a compiler warning generated in the class due to Eclipse using a differ-ent JRE then the system. To suppress a “generic type” warning, add the following anno-tation to the source code @SuppressWarnings(“uncheckedl”):
Figure 62: Generic Type warning from the compiler
@SuppressWarnings("unchecked") @Stateless public class StorePosSessionBean implements StorePosSessionLocal ( @PersistenceContext(unitName="POS") private EntityManager em; public List<StorePos> getStorePos() { List<StorePos> storePos = em.createNamedQuery("findAllPos").getResultList();
4. The @WebService annotation creates a web service for the Stateless Session Bean class.
5. The final code for the class should look as follows: package com.sap.rig.wdex; import java.util.List; @SuppressWarnings("unchecked") @Stateless @WebService public class StorePosSessionBean implements StorePosSessionLocal ( @PersistenceContext(unitName="POS") private EntityManager em; public List<StorePos> getStorePos() { List<StorePos> storePos = em.createNamedQuery("findAllPos").getResultList(); return storePos; } }
Listing 10: Completed Session Bean Code
6. Open the local session bean interface under the ejbModule node by double-clicking on StorePosSessionLocal.java:
Figure 63: Edit the StorePosSessionLocal.java file
7. Add the method getStorePos to the local interface as shown below: @Local public interface StorePosSessionLocal { public List<StorePos> getStorePos(); }
Listing 11: New method getStorePos()
8. Build the class to check for errors. Right-click on the EAR project name, select “Devel-opment Component->Build…”. Select the OK button on the popup form. The results should appear in the Problems view as only info and green icons.
9. If the Server view is not already visible, select it from the menu bar, “Window->Show View->Other…”
10. Expand the Server node, select Servers and the OK button. You will now see the Serv-ers view in the bottom window pane
11. Click on the EAR project node with the left mouse button. Hold down the mouse button and drag the mouse to the SAP Server icon until the mouse pointer changes shape. Release the mouse pointer to add the EAR for deployment (referred to now as publish-ing). Select the EAR node, right click and select Publish.
Figure 64: Deploy the EAR file using drag and drop
12. If this is the first time you have deployed since starting the IDE, you will be asked to log in. Enter the Administrator user and password and select the OK button. When the deployment is complete, you should see a popup dialog indicating successful deployment:
Figure 65: Successful deployment dialog
6.4 Check the Implementation Using the Web Service Navigator 1. Open the server home page (http://localhost:50000)
2. Select the Web Service Navigator link and login with Administrator user and password.
7 Make EJB Application Available to Other Projects
1. Open the Development Component Perspective by selecting the from the menu bar: “Window->Open Perspective->Other…” Then in the popup window, select “Development Infrastructure” and select the OK button.
Figure 69: Open another perspective
Figure 70: Open the Development Infrastructure perspective
5. Right click on the EJB project node and select “Build…”. Select the OK button on the popup dialog.
Figure 74: Build the DC
6. Click on the EAR project node in the left window pane:
Figure 75: Select the pos_ear DC
7. Select the Public Parts tab for the “Component Properties” in the right window pane. Choose Add… to create a new public part. Enter ejb_pp in the Name field and select COMPILATION for the Purpose option. Then select the Finish button.
8. You will see a new Public Part node, ejb_pp, created. Right-click on the ejb_pp node and select Reference Entities in the context menu.
Figure 78: Add referenced entities to the public part
9. In the popup dialog, expand the MyComponents node and the pos_ejb node. Select the box next to client. Select the OK button on the popup “Add Dependencies?” and then select the Finish button.
Figure 79: Add a reference to pos_ejb
10. Rebuild the pos_ear project by right-clicking on the node and selecting “Build…”. Select the OK button on the popup dialog. This is a vitally important step because each Public Part within a DC is implemented as a separate .jar file. Therefore, every time a Public Part is created (or changed), the whole DC must be rebuilt in order for the new (or changed) Public Part to be visible to other DCs.
8 Create Web Dynpro Application Web Dynpro enables users to access business data that is stored outside the Web Dynpro applica-tion. In our case, the business data that belongs to our sample application is accessed by means of EJBs.
Within the Web Dynpro project, you can gain access to EJBs by using the model wizard to create a model object. The model wizard creates a set of proxy classes that makes all model objects look the same – irrespective of their underlying implementation.
The Model Object is a set of model classes that interact with each other through definitions known as “relations”. The model classes can be used to define the structure of context nodes in a Web Dynpro controller.
Within a Web Dynpro component there are multiple controllers. Some controllers are non-visual (such as the component controller), and some controllers are visual (such as a view controller). The design philosophy of Web Dynpro is that non-visual controllers should always act as generators of data. The visual controllers should then always act as consumers of data generated by the non-visual controllers.
In this case, we will create a node in the context of the component controller, and use our EJB model object to define its structure. Then, the data in the component controller’s context can be shared with a view controller using a technique called “Context Mapping”. Finally, the data held in the view controller’s context is supplied to the UI elements defined with the view controller’s layout.
8.1 Create the Web Dynpro Project 1. Create a new local development component of type “Development Component” and se-
lect the Next button:
2. Select “Web Dynpro” for the project type and select the Next button:
3. Expand the node, LocalDevelopment and select MyComponents and the Next button:
4. Name the project pos_wdp and select the Next and then the Finish button. Respond by selecting the No button when requested to switch to the Web Dynpro perspective.
Figure 82: Name the new Web Dynpro DC
5. Select the newly created Web Dynpro node, pos_wdp, under MyComponents in the left window pane:
Figure 83: Select the new Web Dynpro DC
6. Select the Dependencies tab for the “Component Properties” in the right window pane. Choose “Add…” to create a new dependency to the EAR project public part:
Figure 84: Display new Web Dynpro DC’s dependencies
7. Expand the MyComponents node and check the pos_ear node. Select the Next button:
8. The “Deploy Time” and “Run Time” tabs should be selected. Select the Finish button:
Figure 86: Ensure that the dependency details are set to “Deploy Time” and “Run Time”
8.2 Define Web Dynpro Project Structure 1. Open the Web Dynpro Perspective by selecting from the menu bar: “Window->Open
Perspective->Other…” Then in the popup window, select “Web Dynpro” and select the OK button.
2. You should see the “Web Dynpro Explorer” view and the pos_wdp project as shown be-low. If you do not see this view, reset the perspective by selecting “Window->Reset Per-spective” from the menu bar and selecting Yes when prompted in the popup.
Figure 87: The new Web Dynpro DC in the Web Dynpro Explorer View
3. Expand the project node in the left window pane. Under the Web Dynpro node, right-click on the Applications node and choose Create Application:
4. Enter the name, PosWdApp, for the name of the Web Dynpro application and specify, “com.sap.rig.wdex.wdapp”, for the package name. Then choose the Next button.
Figure 89: Give the new Web Dynpro Application a name and a package
5. Up till now, we have not yet created a Web Dynpro component to provide the functional-ity for this application; nonetheless, this can be done at this point in time. Select the “Create a new component” option and choose Next again:
Figure 90: Create a new Web Dynpro Component
6. Check all the boxes on the next screen and select the Next button. Accept the prede-fined settings for the window, the interface view, and the startup plug. Select the Finish button to complete.
8.3 Create the EJB Model for the Web Dynpro Application 1. Right-click on Models under the “Web Dynpro” node and select Create Model:
Figure 92: Start the model wizard by selecting “Create Model”
2. Select the “Enterprise JavaBean Model” and the Next button:
Figure 93: Select “Enterprise JavaBean Model”
3. Enter PosModel for the “Model Name” and “com.sap.rig.wdex.wdapp.posmod” for the “Model Package”. Note that the package must be empty. The model cannot share the package with other code. Select the Next button.
4. Select the pos_ear which contains the public part we exposed earlier. This Public Part is visible because we have already declared a dependency to the DC that contains it (see Figure 85 and Figure 86). Select the Next button to continue.
Figure 95: Select the Public Part
5. A list of Session Beans, interfaces and their business methods appears. In this case we only have the StorePosSessionBean interface. Expand the nodes and select the get-StorePos method. Select the Next button.
Figure 96: Select which Java bean(s) (is/are) to be imported
6. Select the Next and Finish buttons to generate all the model classes. You should see the following structure under the Models node of the Web Dynpro project:
8.5 Bind View to Controller Context The context node we just created lives in the component controller. However, the component controller is a non-visual controller – that means it has no visual interface of its own and is there-fore incapable of displaying data directly on the screen. Therefore, the component controller must pass the data it contains to a view controller (a visual controller). Here we can see how the component controller acts as a data supplier, and the view controller acts as a data consumer.
1. Expand Views under the Components node and double-click on the PosWdCompView node.
Figure 106: Double click on the view name to open the editors
2. By default, the different controllers within a Web Dynpro component are independent Java classes that do not normally share information with each other. However, we must pass the data held in the context of the component controller to the context of the view controller. Before any data sharing can actually take place, the view controller must first declare that it wishes to obtain data from the component controller. Therefore, select the Properties tab in the window pane to the right. Select the Add but-ton to the right of the list of “Required Controllers”. In the popup dialog, check the PosWdComp box and select the OK button. This declaration now enables the view con-troller to consume data (and methods) found in the component controller.
Figure 107: The view controller requires the use of the
data found in the component controller
Figure 108: Declare which controller will act as the data generator
4. We are going place all the UI elements into a visual container with a title. Therefore we need to use the Group UI element. On the right side of the popup dialog, choose Group:
Figure 116: Select the Group UI element
5. Right-click on Group_Header UI element found under the newly added Group UI ele-ment, and select Properties:
6. In the Properties tab in the lower right window pain, enter “POS Data” for the name of Group text name:
Figure 117: Give the Group UI element a title
7. Right-click on the Group node under RootElement and select “Apply Template”:
Figure 118: Use the template wizard to rapidly add UI elements
8. Select the Table template and press the Next button.
9. Expand the Context nodes until you can see the return node. Select all the attributes, then press the Next button and the Finish button. This wizard will automatically create a Table UI element for the selected context node. Each attribute in below the node will become a column in the table.
Figure 119: Select which context attributes need to be visualised
10. Expand the Table and posDiscrep column node. Select the Header node and change the name of the column header (text property) in the Properties tab (right lower window pane) to “POS Discrepancy”.
Figure 120: Change the table column text
11. Repeat the step above for the other columns as shown below:
15. To the right of the onAction property, select the Create button. Expand the list of events and against the onAction event, enter “GetPosData” in the Name field and select the Finish button. A corresponding action event handler method onActionGetPosData() is created in the view controller.
Figure 124: Creating an action object to link a client side
event with a server side response
21. Select ”File->Save All” from the menu bar. Alternatively, you can press Ctrl-Shift-S.
Figure 125: Save all your work so far
8.7 Add Java Code to the Action Event Handler method At the start of section 8, we described how within a Web Dynpro component, there are two types of controller: visual and non-visual. In addition to this, we described how non-visual controllers should always act as data generators, and visual controllers should always act as data consumers. In other words, a visual controller is not responsible for generat-ing the data it displays.
The coding we are about to add is a perfect example of where this principle of separating data generation from data consumption must be applied. Or put another way, this is a per-fect example of where people most frequently do it wrong!
The following coding needs to invoke our Java bean’s getStorePos() method, and techni-cally speaking, there is no reason why this code cannot be placed directly into the event handler method mentioned above called onActionGetPosData().
However, in which controller does this method live?
• A visual controller, or
• A non-visual controller?
The answer is that this method lives in a view controller (which is a visual controller). If we were to invoke the Java bean directly from the view controller, then the code would func-tion perfectly correctly; however, we would have violated the fundamental principle in Web Dynpro architecture that a visual controller should only ever act as a data consumer.
If this design principle is not followed, then the resulting Web Dynpro application may well be functional, but the coding it contains will have ignored the architectural difference be-
tween data generators and data consumers thus making the code much harder to main-tain. In addition to this, the coding will also tend to be excessively complex – another fac-tor that only increases code maintenance effort.
Therefore, to maintain a good Web Dynpro architecture, there will only be a single line of code in the onActionGetPosData() method of the view controller. This coding will simply delegate the Java bean interaction to the component controller. The data returned by the Java bean will be placed into the component controller’s context. But, we have already declared that the context node in the view controller is a “mapped node”. This means that it will obtain its data from a node belonging to some other controller in the component; in this case, the component controller. So the data returned by the Java Bean to the compo-nent controller is automatically available to the view controller though context mapping.
1. Under the Views nodes, right-click on the PosWdCompView and select “Open->Java Editor”.
Figure 126: Open the Java editor for the view controller
2. Go to the bottom of the file and find the onActionGetPosData method. Add the following code to call a method in the component controller. You will notice that the compiler complains about this method name saying it is undefined. At this point in time, that complaint is perfectly true - but for the time being we can ignore it.
8.8 Create and implement the invokeBean() method in the component controller
1. Open the Editor for the Component Controller by double clicking on the “Component Controller” as per Figure 100.
2. Select the Methods tab and on the right side of the screen, press the New button.
3. Make sure the Method radio button is selected rather than the Event Handler radio but-ton and press Next.
4. Enter the name invokeBean, leave the return type set to void and press Finish.
5. You may have noticed that when you double clicked on the component controller name, two tabs opened. One is for the declarative changes you can make to the controller, and the other contains the actual source code.
6. Switch now to the source code tab. There are two blocks of code that need to be added:
a. Locate the method wdDoInit() and add the following code public void wdDoInit() { //@@begin wdDoInit() PosModel myModel = new PosModel(); wdComponentAPI.getModelInstanceMap(). putDefaultInstance("com.sap.rig.wdex.wdapp.posmod.PosModel", myModel); //@@end }
Listing 13: Coding for method wdDoInit() of the component controller
Note: You can find the full pathname for the Model from its properties. Click on the model in the “Web Dynpro Navigator” and the properties will be displayed in the Properties view in the lower, right window pane:
Figure 127: Finding the model object’s full package name
b. Locate the new method invokeBean() and add the following code public void invokeBean() { //@@ begin invokeBean() try { wdContext.currentRequest_StorePosSessionLocal_getStorePosElement(). modelObject().execute(); } catch (Exception e) { wdComponentAPI.getMessageManager(). reportException(e.getLocalizedMessage()); } //@@end }
Listing 14: Coding for method invokeBean() of the component controller
7. Save your work by pressing Ctrl-Shift-S
8.9 Deploy and Run the Web Dynpro Application 1. Right-click on the Web Dynpro project node in the “Web Dynpro Explorer” and select
“Rebuild Project”. Make sure the Task view in the lower right window pane does not show any errors:
Figure 128: Rebuild the whole Web Dynpro DC
2. Right-click on the application PosWdApp in the “Web Dynpro Explorer” and select “De-ploy New Archive and Run”. Select the OK button on the popup window indicating suc-cessful deployment.
Figure 129: Deploy new archive and run
This completes the exercise on consuming an EJB within Web Dynpro CE 7.1