You are on page 1of 128

Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
Developing o @
8 ent
Applications for
the a Java
s d
do EESt6uPlatform
r
( a nc this- Eclipse
Activity Guide
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

D65269GC20
Edition 2.0
June 2011
D73428
Pontifícia Universidade Católica do Rio Grande do Sul

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Disclaimer

This document contains proprietary information and is protected by copyright and other intellectual property laws. You may copy and
print this document solely for your own use in an Oracle training course. The document may not be modified or altered in any way.
Except where your use constitutes "fair use" under copyright law, you may not use, share, download, upload, copy, print, display,
perform, reproduce, publish, license, post, transmit, or distribute this document in whole or in part without the express authorization
of Oracle.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

The information contained in this document is subject to change without notice. If you find any problems in the document, please
report them in writing to: Oracle University, 500 Oracle Parkway, Redwood Shores, California 94065 USA. This document is not
warranted to be error-free.

Restricted Rights Notice

If this documentation is delivered to the United States Government or anyone using the documentation on behalf of the United
States Government, the following notice is applicable:

U.S. GOVERNMENT RIGHTS


The U.S. Government’s rights to use, modify, reproduce, release, perform, display, or disclose these training materials are restricted
by the terms of the applicable Oracle license agreement and/or the applicable U.S. Government contract.
s a
Trademark Notice ) h a
c o m

ail ideฺ
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective
owners.
m
g Gu
o @
8 ent
Authors s
do Stud
Paromita Dutta a r
( a nc this
Technical Contributors and Reviewers o
s u s e
Tom Mc Ginn, Matthieu Heimer, Greg o
rd Stachnick,
to Moises Lejter
a e
i d is C licens
i c ola using:
This book was published
b l e Oracle Tutor
r e N fera
a n d rans
x -t
Ale non
Pontifícia Universidade Católica do Rio Grande do Sul

Table of Contents
Practices for Lesson 1: Placing the Java EE Model ................................................................................. 1-1
Practices for Lesson 1............................................................................................................................. 1-2
Practice 1-1: Categorizing Java EE Services............................................................................................ 1-3
Practice 1-2: Describing the Java EE Platform Layers .............................................................................. 1-4
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Practice 1-3: Examining the Java SE Broker Tool Application ................................................................... 1-5
Practice Solutions ................................................................................................................................... 1-7
Practices for Lesson 2: Java EE Component Model and Development Steps ........................................ 2-1
Practices for Lesson 2............................................................................................................................. 2-2
Practice 2-1: Java EE Component Model and Development Steps............................................................ 2-3
Practice 2-2: Describing Options for Packaging Applications .................................................................... 2-4
Practice Solutions ................................................................................................................................... 2-5
Practices for Lesson 3: Web Component Model ...................................................................................... 3-1
Practices for Lesson 3............................................................................................................................. 3-2 s a
Practice 3-1: Creating a Basic JSP Component........................................................................................ 3-3
) h a
o m
Practice 3-2: Troubleshooting a Web Application...................................................................................... 3-5
c

ail ideฺ
Practice 3-3: Creating a Basic Servlet Component ................................................................................... 3-6
g Gum
Practice 3-4: Describing Web Components .............................................................................................. 3-8
@
8 ent
Practice Solutions ................................................................................................................................... 3-9
o
do Stud s
Practices for Lesson 4: Developing Servlets ........................................................................................... 4-1
a
c his r
Practices for Lesson 4............................................................................................................................. 4-2
Practice 4-1: Developing the BrokerTool Web Application ( a n........................................................................
t 4-3
o us e
s ..................................................................................
Practice 4-2: Implementing Controller Components
r d o..........................................................................................
t o
4-5
Practice 4-3: Describing Servlet Components
C a se 4-9

i d i licen
s
Practice Solutions ................................................................................................................................... 4-10
a lewith JavaServer Pages Technology ............................................... 5-1
Practices for Lesson 5:lDeveloping
o
N c
i 5: Overview
Practices for Lesson ab .............................................................................................................
rAllCustomers.jsp 5-2
e
Practicer5-1: Creating fthe
d 5-2: Creating e
s the Portfolio.jsp Component .................................................................................. 5-5
Component ........................................................................... 5-3
a n r a n
x Practice
-t(Optional): Creating the CustomerDetails.jsp Component ...................................................... 5-7
Ale Practice
o n5-3
n 5-4: Describing JavaServer Pages Components ......................................................................... 5-8
Practice
Practice Solutions ................................................................................................................................... 5-9
Practices for Lesson 6: Developing with JavaServer Faces Technology ................................................ 6-1
Practices for Lesson 6............................................................................................................................. 6-2
Practice 6-1: Creating the Stocks.xhtml Component ................................................................................. 6-3
Practice 6-2 (Optional): Implementing the JSF CustomerDetails.xhtml View ............................................. 6-8
Practice Solutions ................................................................................................................................... 6-12
Practices for Lesson 7: EJB Component Model....................................................................................... 7-1
Practices for Lesson 7............................................................................................................................. 7-2
Practice 7-1: Creating and Deploying a Simple EJB Application ................................................................ 7-3
Practice 7-2: Describe the EJB Component Model ................................................................................... 7-6
Practice Solutions ................................................................................................................................... 7-7
Practices for Lesson 8: Implementing EJB 3.1 Session Beans ............................................................... 8-1
Practices for Lesson 8............................................................................................................................. 8-2
Practice 8-1: Coding the EJB Component and Client ................................................................................ 8-3
Practice 8-2: Optional - Creating a Java SE EJB Client That Uses JNDI ................................................... 8-5

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Developing Applications for the Java EE 6 Platform Table of Contents


iii
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 8-3: Describing Session Beans................................................................................................... 8-8


Practice Solutions ................................................................................................................................... 8-9
Practices for Lesson 9: Java Persistence API.......................................................................................... 9-1
Practices for Lesson 9............................................................................................................................. 9-2
Practice 9-1: Create the Java Persistence API Version of the BrokerTool Project ...................................... 9-3
Practice 9-2: Describing Java Persistence API ......................................................................................... 9-8
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Practice Solutions ................................................................................................................................... 9-9


Practices for Lesson 10: Implementing a Transaction Policy.................................................................. 10-1
Practices for Lesson 10 ........................................................................................................................... 10-2
Practice 10-1: Determining When Rollbacks Occur .................................................................................. 10-3
Practice 10-2: Using the Versioning Features of the Persistence API to Control Optimistic Locking............ 10-5
Practice Solutions ................................................................................................................................... 10-8
Practices for Lesson 11: Developing Java EE Applications Using Messaging ....................................... 11-1
Practices for Lesson 11 ........................................................................................................................... 11-2
s a
Practices for Lesson 12: Developing Message-Driven Beans ................................................................. 12-1
) h a
Practices for Lesson 12 ........................................................................................................................... 12-2

c
Practice 12-1: Implementing the Message-Driven Bean............................................................................ 12-3o m

ail ideฺ
Practice 12-2: Describing Message-Driven Beans .................................................................................... 12-5
g Gum
Exercise Solutions .................................................................................................................................. 12-6

o @
8 ent
Practices for Lesson 13: Web Services Model ......................................................................................... 13-1
o s d
c a rd Stu
Practices for Lesson 13 ........................................................................................................................... 13-2
Practices for Lesson 14: Implementing Java EE Web Services
( a n withthJAX-RS is and JAX-WS .................... 14-1
o us e
Practices for Lesson 14 ...........................................................................................................................
s 14-2
Practice 14-1: Creating a JAX-WS Web Service o
rd e to ....................................................................................... 14-3
Practice 14-2: Creating a Web Service a
C Servicen..........................................................................................
s
Client ........................................................................................... 14-5
Practice 14-3: Create a JAX-RS
i d isWeb l i c e 14-7
o l
Practice 14-4: Describing a Web
l e
Services .................................................................................................. 14-9
Practice Solutionsi c ra b
N ................................................................................................................................... 14-10
r e s f e
x a nd forforLesson
Practices
t r a n 15:15...........................................................................................................................
Implementing a Security Policy........................................................................ 15-1
-
Ale Practice
Practices Lesson 15-2
n o n15-1: Using the EJB Security API to Get the User's Identity in an EJB Component ....................... 15-3
Practice 15-2: Creating Roles, Users, Groups, and a Web-Tier Security Policy ......................................... 15-4
Practice 15-3: Creating an EJB Tier Security Policy.................................................................................. 15-7
Practice 15-4: Describing Java EE Security ............................................................................................. 15-9
Practice Solutions ................................................................................................................................... 15-10

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Developing Applications for the Java EE 6 Platform Table of Contents


iv
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
Practices ofor @
8 ent 1:
Lesson
s
Placing
a r tud EE Model
dotheSJava™
( ainncContext
t his
so Chapter e
us 1
r d o t o
C a se
i d i licen
s
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Placing the Java™ EE Model in Context


Page 1 of 8
Pontifícia Universidade Católica do Rio Grande do Sul

Practices for Lesson 1: Overview

Practices Overview
In these practices, you categorize Java EE services, describe the Java EE platform layers, and
explore the existing Java BrokerTool_SE project.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Placing the Java™ EE Model in Context


Page 2 of 8
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 1-1: Categorizing Java EE Services

Overview

In this practice, you complete a matching activity to check your understanding of the Java EE
service categories.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Tasks
1. Place each Java EE service in the appropriate Java EE service category in the following
table:
• Persistence, Scalability, Naming, Threading
• Remote Object Communication, Connector, Load Balancing, Failover
• Security, Life-cycle Services, Transaction, Messaging
No. Service Category Java EE Services s a
) h a
1 Deployment-based services
c o m
2 API-based services ฺ
ail ideฺ
3 Inherent services
m
g Gu
o @
8 ent
4 Vendor-specific functionality s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Placing the Java™ EE Model in Context


Page 3 of 8
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 1-2: Describing the Java EE Platform Layers

Overview

In this practice, you complete a matching activity to check your understanding of the layers in
the Java EE platform.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Tasks
Match the number of each term with the corresponding layer shown in the figure:
a. Databases and other back-end services
b. API layer
c. Service layer
s a
d. Component layer
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Placing the Java™ EE Model in Context


Page 4 of 8
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 1-3: Examining the Java SE Broker Tool Application

Overview

In this practice, you examine the existing BrokerTool_SE project. The BrokerTool_SE project is
a Java Platform, Standard Edition (Java SE) application.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

ABC StockTrading is an established stock trading company that manages portfolios for a small
set of clientele. ABC StockTrading had an intern develop a prototype Java application to
manage their clientele. You have been hired as a Java developer by ABC to further develop the
prototype as part of a study to modernize their software by leveraging the power of the Java EE
platform.

Prerequisites
s a
) h a
Eclipse should be installed and the BrokerTool_SE project should be present on your system.
c o m
Tasks

ail ideฺ
1. Launch Eclipse.
m
g Gu
@
8 ent
a. Double-click the desktop shortcut to start Eclipse. so
r do select
b. In the Workspace Launcher dialog box, clickaBrowse, S tudthe
D:\labs\eclipse\projects folder, a c clickhOK.
nand is
( e t
c. Close the Welcome page.
d o so us
d. Select Show View from a r Window
the
e to Click Project Explorer from the list.
menu.
2. Open the BrokerTool_SE
i d is C e
project.
c ns
li menu.
a. Select Import
c o lafrom the
l e File
N
b. In the
e
i dialog
Select
f e r abbox that appears, expand General, click Existing Projects into
a n drWorkspace
r a n s and then click the Next button.
x c. In-thet Import Projects dialog box, provide the following information:
Ale no• n Select root directory: Select the radio button and click Browse to select the folder:
D:\labs\eclipse\solutions\JavaEEModel.
• In the Projects text area, select the entry named BrokerTool_SE.
• Check the box next to “Copy Projects into Workspace.”
d. Click the Finish button.
3. Build the BrokerTool_SE project.
a. Click the BrokerTool_SE node on the Project Explorer tab,
b. Click the Project menu and select Build Project if the Build Automatically option is not
enabled.
4. Run the BrokerTool_SE project.
a. Select and right-click the BrokerTool_SE node.
b. Click the Run As option from the context menu and select Java Application.
c. In the Select Java Application dialog box, select Broker2TierApp.trader and click
OK.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Placing the Java™ EE Model in Context


Page 5 of 8
Pontifícia Universidade Católica do Rio Grande do Sul

d. On the All Customers tab, view the list of customers. Write down several Customer
IDs.
e. Click the Customer Details tab. Using a Customer ID that you wrote down, complete
the Customer Identity field and click the Get Customer button.
f. Try the other buttons.
g. Quit the BrokerTool_SE application.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Placing the Java™ EE Model in Context


Page 6 of 8
Pontifícia Universidade Católica do Rio Grande do Sul

Practice Solutions

Solutions for Practice 1

Compare your answers with the service category and Java EE services shown in the following
table:
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

No. Service Category Java EE Services


1 Deployment-based services Persistence, Transaction, Security
2 API-based Services Naming, Messaging, Connector
3 Inherent services Life-cycle services, Threading, Remote object
communication
s a
4 Vendor-specific functionality Scalability, Load balancing, Failover
) h a
c o m

ail ideฺ
Solution for Practice 2 m
g Gu
@
8 inethentfollowing figure:
Compare your answers with the number and description of the layers
o
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Placing the Java™ EE Model in Context


Page 7 of 8
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Placing the Java™ EE Model in Context


Page 8 of 8
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
@
8 ent 2: Java
Practices ofor Lesson
s
do StudModel and
EE Component
a r
( a nc this Steps
Development
o s o use
a rd e toChapter 2
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Java EE Component Model and Development Steps


Page 1 of 6
Pontifícia Universidade Católica do Rio Grande do Sul

Practices for Lesson 2: Overview

Practices Overview
In these practices, you describe Java EE roles and responsibilities and list the options for
packaging applications.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Java EE Component Model and Development Steps


Page 2 of 6
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 2-1: Java EE Component Model and Development Steps

Overview
In this practice, you complete a matching activity to check your understanding of the Java EE
roles and responsibilities.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Tasks
In the following table, identify each role with the responsibility that best matches it:
Roles Responsibility
Application component provider (1) Resolves references to external
resources, and configures the run-time
environment of the application
Application assembler (2) Is the vendor of the application server
Deployer (3) Maintains and monitors the application
s a
server environment
) h a
System Administrator
c o m
(4) Implements development, packaging,

ail ideฺ
assembly, and deployment tools
Tool provider m
g Gu (5) Develops EJB components and web
components
o @
8 ent (6) Resolves cross-references between
Product provider s
do Stud components
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Java EE Component Model and Development Steps


Page 3 of 6
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 2-2: Describing Options for Packaging Applications

Overview

In this practice, you complete a matching activity to check your understanding of the options for
packaging applications.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Tasks

For each of the following figures, identify the type of archive file that best describes the
packaging option. The archive files include:
• Enterprise Archive (EAR) file
• Web Archive (WAR) file
• EJB component Java Archive (JAR) file
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
Figured
n 1
a n s Figure 2 Figure 3
x a - t r
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Java EE Component Model and Development Steps


Page 4 of 6
Pontifícia Universidade Católica do Rio Grande do Sul

Practice Solutions

Use the following solutions to check your answers to these practices.

Solutions for Practice 1


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

The following table shows the Java EE roles matched to the correct responsibilities.

Role Matching Responsibility


Deployer (3) Maintains and monitors the application
server environment
Product provider (6) Resolves cross-references between
components
System administrator (4) Implements development, packaging,
assembly, and deployment tools s a
Tool provider (5) Develops EJB components and web
) h a
components
c o m
Application component provider ฺ
ail ideฺ
(1) Resolves references to external resources,
m
and configures the run-time environment of
g Gu
o @the application
8 ent
Application assembler s
do Stud
(2) Is the vendor of the application server
a r
( a nc this
Solutions for Practice 2
o s o use
a rd e to
Figure 1: EAR File
i d is C licens
Figure 2: JAR File la
N
Figure 3: WAR co rable
iFile
n d re nsfe
l e xa n-tra
A no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Java EE Component Model and Development Steps


Page 5 of 6
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Java EE Component Model and Development Steps


Page 6 of 6
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
Practices ofor @
8 ent 3: Web
Lesson
Component
s ud
do StModel
a r
( nc
Chapter 3 th
a is
so us e
r d o to
a e
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Web Component Model


Page 1 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practices for Lesson 3: Overview

Practices Overview
In these practices, you:
• Create a basic JavaServer Pages (JSP) component
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Configure, deploy, and test a web module


• Create a basic servlet
• List the ways that JSP components and servlets fit into the web component model

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Web Component Model


Page 2 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 3-1: Creating a Basic JSP Component

Overview

In this practice, you create, deploy, and run a web application project with a basic JSP
component.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Prerequisites

The application server should be installed and configured in Eclipse.

Tasks
1. Add the GlassFish server.
a. Ensure that the Java EE perspective is open. To open the Java EE perspective, click
the Window menu and select Open Perspective > other and then click Java EE.
s a
b. Switch to the Servers view, right-click the Servers window, and select New >Server. ) h a
o m
c. In the “Define a New Server” dialog box, expand the GlassFish node and select
c
GlassFish 3.1. Click the Next button. ฺ
ail ideฺ
d. In the “New GlassFish 3.1 Runtime” dialog box:
m
g Gu
o @
8 ent
1) Click the installed JRE preferences link, which opens a “Preferences” dialog box.
s
do Stud
Here you have to provide the JDK location instead of a JRE location.
a r
2) Click the Add button.
( a nc this
o s o use
3) Select Standard VM and click Next.
rd e to
4) If it is not provided by default for the JRE home field, click the Directory button and
a
i d is C licens
select D:\Program Files\Java\jdk1.6_24 (or whichever

ola ble
available).
i c
5) Click the Finish button to return to the Installed JREs dialog box. If it is not
N fera
r e
d rans
selected by default, select the jdk1.6_24 entry from the list and click the OK
a n button to return to the “New Server” dialog box.
x -t
Ale non e. In the drop-down menu for the JRE field, select jdk1.6_24.
1) For the Application Server Directory, click the Browse button and select
D:\glassfish3\glassfish.
2) Click the Next button.
f. Accept the default entries in the next two dialog boxes and click the Finish button.
2. Develop a basic JSP page.
a. Make sure that Eclipse is running. You are in the D:\Labs\eclipse\projects
workspace. Project Explorer view is open.
b. In Eclipse, select File > New > Project.
c. Under the New Project wizard, expand Web.
d. Select Dynamic Web project.
e. Click the Next button.
f. The new Dynamic Web project should have the following characteristics:
• Project Name: SampleWebApplication
• Use Default Location: D:\Labs\eclipse\projects\SampleWebApplication
– Checked
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Web Component Model


Page 3 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

• Target Runtime: GlassFish 3.1


• Dynamic Web Module Version: 3.0
• Configuration: Default Configuration for GlassFish 3.1
• Accept default values for all other properties and click Next.
g. Accept the entries in the Java dialog box and click the Next button.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

h. In the Web Module dialog box, select the Generate web.xml deployment descriptor
check box.
i. Click the Finish button.
j. Click the Yes button in the Open Associated Perspective dialog box (if the dialog box
appears).
k. Expand the newly created SampleWebApplication and then expand the
WebContent folder. If you don't see a file called index.jsp, create one now. Right-
click the project and select New > JSP File. Provide the name index.jsp, and click
Finish. s a
) h a
l. Open the index.jsp file. You can place any static HTML on a JSP page. Experiment
c o m
with adding Java code to the JSP page. ฺ
ail ideฺ
m. The following is an example of what you might enter: m
g Gu
<%= new java.util.Date() %>
o @
8 ent
4. Run the sample application and test it. s
do Stud
a r
a. Test the application by right-clicking the project folder and selecting Run As > Run on
a nc this
Server. Select GlassFish 3.1 at localhost in the following dialog box and click Finish.
(
o s o URL:use
b. In a web browser, enter the following
a rd e to
http://localhost:8080/SampleWebApplication/index.jsp

i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Web Component Model


Page 4 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 3-2: Troubleshooting a Web Application

Overview

In this practice, you introduce an error into the SampleWebApplication project. You then
redeploy the application and review the errors generated by your change to the code.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Prerequisites

You should have completed Practice 3-1.

Tasks
1. Create a faulty web component.
a. Ensure that the SampleWebApplication project is open in Eclipse.
b. Modify the index.jsp web component to produce an exception at execution. Enter s a
the following on your index.jsp page: ) h a
c o m
<% ฺ
ail ideฺ
Object o = null; m
g Gu
o.toString();
o @
8 ent
%> s
do Stud
a r
2. Run and test the faulty application.
( a nc this
a. Save any modified files.
o s o use
rd the
b. Test the application by selecting
a e o option from the Run menu and then entering
tRun
the following in a webC ns
browser:
i d i s c e
c o la le li
http://localhost:8080/SampleWebApplication/index.jsp

e N i
f e r ab displayed in your browser.
a n dr rans
c. Notice the error message
3. t
x View the-Application Server error messages.
Ale non a. Bring up the Application Server log in the IDE.
1) Switch to the Server window.
2) Right-click the GlassFish 3.1 at localhost server node and select GlassFish > View
Log File.
3) The log is displayed on a Console tab on the output pane.
b. Find the location where the web application causes an exception to be generated. The
line should be similar to:
Servlet.service() for servlet jsp threw exception
java.lang.NullPointerException
When looking for errors in the log file, you may find it helpful to clear the log to ensure that
you are viewing only recent errors.
4. Remove the error placed in the index.jsp file during Task 1 and run the application again.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Web Component Model


Page 5 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 3-3: Creating a Basic Servlet Component

Overview
In this practice, you create a basic servlet component in a web application.

Prerequisites
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

The application server should be installed and running along with Eclipse.

Tasks
1. Create a servlet
a. Ensure that the SampleWebApplication project is open in Eclipse.
b. Right-click the SampleWebApplication project select New > Servlet.
c. Enter the following information for the servlet:
s a
• Project: SampleWebApplication
) h a
• Source Folder: \SampleWebApplication\src
c o m
• Java Package: test

ail ideฺ
m
g Gu
• Class Name: BasicServlet
o @
8 ent
• Super Class: javax.servlet.http.HttpServlet s
do Stud
a r
c “deployment
d. Click Next. Accept the default entries inn
information” dialog box and click Next. ( a
the
t h is descriptor specific
o s u se and method stubs to generate”
o to implement,
dialog box, ensure that a rddoPost
e. In the “Specify modifiers, interfaces
the e to doGet methods are selected. Click Finish.
and
i d
f. Create a processRequestis C licemethod
ns in the BasicServlet servlet to display a
dynamically
i c olagenerated
b le message.
N
•re Modify your f a
erservlet using the following code as a guide:
d s
an void processRequest(HttpServletRequest request,
e x an protected
- t r
Al nonHttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {

out.println("<html>");
out.println("<head>");
out.println("<title>Servlet BasicServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet BasicServlet at " +
request.getContextPath() + "</h1>");
out.println("Generated at: " + new java.util.Date());
out.println("</body>");
out.println("</html>");
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Web Component Model


Page 6 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

} finally {
out.close();
}
}
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

g. Ensure that both the doGet and doPost methods call the processRequest method.
h. Ensure that the BasicServlet class has a @WebServlet annotation at the class
level. Add a urlPatterns attribute to the annotation to specify the URLs for the
servlet. It should look like this:
@WebServlet(name="BasicServlet", urlPatterns={"/BasicServlet"})
public class BasicServlet extends HttpServlet {
i. urlPatterns indicates URLs that are relative to the context root for the application.
Thus, you can access the servlet by entering s a
http://localhost:8080/SampleWebApplication/BasicServlet in your web ) h a
browser or Eclipse window. c o m
2. Deploying the application and testing it.

ail ideฺ
m
g build G u
@
a. Save any modified files. If “Build Automatically” is not enabled,
8 en t the
SampleWebApplication Web project manually. so
a r o
d As >SRun tudon Server.
c. Test the application by selecting Run(a
nc Run
b. Right-click SampleWebApplication and select
from the
Run
t s
himenu or by entering the following
s o s e
URL in a web browser:
a rdo e to u
C ns
http://localhost:8080/SampleWebApplication/BasicServlet
d. You should see i dais ce generated web page. This indicates that the servlet has
dynamically
l a l i
N ico rable
been successfully invoked.

n d re nsfe
l e xa n-tra
A no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Web Component Model


Page 7 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 3-4: Describing Web Components

Overview
In this practice, you check your understanding of web components.

Task
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

In the following sentences, fill each blank with the missing word (or words):
1. At run time, JSP components are essentially just ______________.
2. JSP components and servlets are packaged into a web application, along with any
static content that is required. The web application is deployed in a ___________ file.
3. ______________________ are useful for generating presentation, particularly HTML
and XML. _____________, on the other hand, are useful for processing form data,
computation, and collecting data for rendering.
s a
4. The web container calls the _________________ method once for each incoming
) h a
request.
c o m
5. ฺ
ail ideฺ
Because HTTP is _______________, the server cannot ordinarily distinguish between
m
successive requests from the same browser and a single request from different
g Gu
browsers.
o @
8 ent
6. s
do Stud
The two most common HTTP request types that are used with servlets are
____________ and ___________. a r
7. a nc this
In the HTTP model, a client sends a ____________ to a server and receives a
(
s o use
________________ from the server.
o
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Web Component Model


Page 8 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice Solutions
This section contains the practice solutions.

Solutions for Practices 3-1, 3-2, and 3-3


You can find solutions for these practices in the following directory:
D:\Labs\eclipse\solutions\WebComponents
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Solutions for Practice 3-4


Compare your responses with the following answers:
1. At runtime, JSP components are essentially just servlets.
2. JSP components and servlets are packaged into a web application, along with any static
content that is required. The web application is deployed in a WAR file.
3. JSP components are useful for generating presentation, particularly HTML and XML.
Servlets, on the other hand, are useful for processing form data, computation, and
s a
collecting data for rendering.
) h a
4. The web container calls the service() method once for each incoming request.
c o m
5. Because HTTP is stateless, the server cannot ordinarily distinguish a ฺ
il successive
between e ฺ
m
g browsers.
requests from the same browser and a single request from different u i d
@ t G
6. The two most common HTTP request types that are used
o s o8withdservlets
e n are GET and
POST.
a radserver S tu
a n
7. In the HTTP model, a client sends a requestc to
h is receives a response from
and
the server. (
o use t
o s
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Web Component Model


Page 9 of 10
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Web Component Model


Page 10 of 10
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
Practices ofor @
8 ent 4:
Lesson
s
Developing
a r tud
do SServlets
( nc
Chapter 4 th
a is
so us e
r d o to
a e
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Developing Servlets


Page 1 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practices for Lesson 4: Overview

Practices Overview
In these practices, you:
• Create a Java EE Web Application Project in Eclipse
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Create servlets to dynamically process form data


• Describe controller components

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Developing Servlets


Page 2 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 4-1: Developing the BrokerTool Web Application

Overview
In this practice, you create the BrokerTool Web Application, copy provided Java classes, and
make the CustomerDetails servlet the default index page:
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Prerequisites
The application server should be installed and configured in Eclipse.

Tasks
1. Create the BrokerTool project.
a. In Eclipse, from the menu select File then New > Project.
b. In the “Select a Wizard” dialog box, expand Web and select Dynamic Web Project.
c. Click the Next button.
s a
d. The new Dynamic Web project should have the following characteristics:
) h a
• Project Name: BrokerTool
c o m
• Use Default Location: D:\Labs\eclipse\projects\BrokerTool ฺ
ail ideฺ
• Target Runtime: GlassFish 3.1 m
g Gu
• Dynamic Web Module Version: 3.0 o @
8 ent
s
• Configuration: Default Configuration for GlassFish
a r do 3.1 S tud
e. Click the Next button. Make no changes a c clickhNext.
nand is
( e t
f. Select the check box to generate
d o sothe web.xml
u s descriptor file.
g. Accept the default entries arand click e theo
t Finish button.
C
is classes. n s
2. Copy the BrokerTool_SE
i d l i c e
a. Right-click
c la BrokerTool
othe l e project icon. Select New and then Package. Enter
i
N forfthe b
rapackage name.
trader
r e s e
x a nb.d ClicktrathenFinish button.
- classes from the BrokerTool_SE project to the trader package in the
Ale c.nonCopy
BrokerTool project.
1) Open the BrokerTool_SE project.
2) Expand the src node, then the trader node.
3) To copy a class, right-click the class you want to copy in the BrokerTool_SE
trader package and select Copy. Next, right-click the target trader package in
the BrokerTool project and select Paste. The copy of the class is complete.
Copy the following classes:
trader.BrokerException
trader.BrokerModel
trader.BrokerModelImpl
trader.Customer
trader.CustomerShare
trader.Stock
d. Close the BrokerTool_SE project.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Developing Servlets


Page 3 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

3. Copy the CusomerDetails servlet


a. Right-click the BrokerTool project icon.
b. Select New and then select Package.
c. Enter trader.web as the package name.
d. Copy the CustomerDetails.java file from the D:\Labs\eclipse\resources
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

directory.
e. Paste the CustomerDetails.java file in the trader.web package of the
BrokerTool project.
f. View the source code for the CustomerDetails servlet. When accessed with a web
browser, this servlet will present an empty HTML form. The CustomerDetails
servlet is designed to function as an MVC view. You implement the corresponding
MVC controller later in these practices.
4. Set the BrokerTool default home page.
s a
a. In the Project Explorer window, expand BrokerTool > Web Content > WEB_INF.
) h a
b. o m
The web.xml deployment descriptor should be present. Click it to open it in the editor
c
window.

ail ideฺ
m
g Gu
c. Switch to the Design view of the web.xml deployment descriptor.
o @
8under the n t
d. Enter a value of CustomerDetails for Welcome s File
ud e Welcome-File-List
r do File
entry. You can remove the other additional Welcome
a S tentries.
a nc toththeisdeployment descriptor. You
e. Switch to the Source view to see the(changes
should see the following:
o s o use
<?xml version="1.0" a rdencoding="UTF-8"?>
e to
d is C licenxmlns="http://java.sun.com/xml/ns/javaee"
<web-app version="3.0"
i
s
i c ola ble
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

r e N fera
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

n s
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
d ra<display-name>BrokerTool</display-name>
n
x a -t
Ale non <welcome-file-list>
<welcome-file>CustomerDetails</welcome-file>
</welcome-file-list>
</web-app>
5. Run the BrokerTool application and test it.
Save any modified files. If “Build Automatically” is not enabled, build the project from
the Project menu.
a. Run the application by selecting the Run option from the Run menu. You might have to
select the Run on Server option from the “Run as” dialog box.
b. Select GlassFish 3.1 at localhost under localhost in the “Run on Server” dialog box.
c. The browser window in Eclipse opens: http://localhost:8080/BrokerTool/.
You should see an empty customer details form.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Developing Servlets


Page 4 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 4-2: Implementing Controller Components

Overview

In this practice, you create the CustomerController and PortfolioController servlets.


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Prerequisites

The application server should be installed, and Practice 4-1 should be completed.

Tasks
1. Create the CustomerController servlet.
a. Create a new servlet in the BrokerTool project. In the project window, right-click
BrokerTool and select New > Servlet.
s a
b. In the “Create Servlet” dialog box, enter the following information:
) h a
• Class Name: CustomerController c o m

ail ideฺ
• Java Package: trader.web m
c. Click the Finish button. @ g Gu
s o 8 ent
r d o
d. Using the @WebServlet annotation and the urlPatterns
t u dattribute, make the servlet
available at two URLs:
a n ca his S
• /CustomerController
o ( se t
• /AllCustomers s
do to u
a r
e. Import the content of C
i s the trader
e n sepackage.
o l aid le lic
f. Import javax.servlet.RequestDispatcher.
N
g. Create ica processRequest
r ab method:
e
drprotected f e
s void processRequest(HttpServletRequest request,
a n r a n
x -t
Ale non throws ServletException, IOException {
HttpServletResponse response)

1) Retrieve the singleton instance of the BrokerModelImpl class by adding the


following line:
BrokerModel model = BrokerModelImpl.getInstance();
2) Use the HttpServletRequest object to get the path used to invoke the servlet.
String path = request.getServletPath();
3) If the path was /CustomerController, perform the following steps:
a) Retrieve the request form parameter values for customerIdentity,
customerName, customerAddress, and submit. Assign the values to
string variables id, name, address, and submit.
b) Use the value of the submit variable to determine if one of the submit buttons
in the CustomerDetails servlet was clicked to invoke this servlet. If a
submit button was clicked, perform the appropriate action from the following:

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Developing Servlets


Page 5 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

• If the Get Customer submit button was clicked: Use the model to look
up the customer with the customerIdentity request parameter. Store
the customer as a request attribute named customer (case-sensitive).
• If the Update Customer submit button was clicked: Use the model to
update the customer with the ID of the customerIdentity request
parameter to have the values of customerName and
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

customerAddress. Retrieve and store the updated customer as a


request attribute named customer (case-sensitive).
• If the Add Customer submit button was clicked: Use the model to
create a new customer with the customerIdentity, customerName,
and customerAddress request parameters. Retrieve and store the new
customer as a request attribute named customer (case-sensitive).
• If the Delete Customer submit button was clicked: Use the model to
delete the customer with the ID of the customerIdentity request
s a
parameter.
) h a
c o m
c) Use exception handling to deal with any errors that might occur when using the

ail ideฺ
model variable. If exceptions occur, call the Exception class getMessage
m
method and store the value in a request attribute named message.
g Gu
d) Use a RequestDispatcher to forward the response
o @
8 toenthet
CustomerDetails servlet. s
do Stud
=c a r
RequestDispatcher dispatcher n
( a e t his
so response);
request.getRequestDispatcher("CustomerDetails");
dispatcher.forward(request,
r d o t o us
C a path was
se used to invoke this servlet, perform the following
s
4) If the /AllCustomers
i e n
steps: laid lic
o
c thermodel l e
e
a) iUse
N f e ab variable to retrieve an array of all customers.
a n dr rb)aStore
n s the array of all customers as a request attribute named customers.
x -t c) Use exception handling to deal with any errors that might occur when using the
Ale non model variable. If exceptions occur, call the Exception class getMessage
method and store the value in a request attribute named message.
d) Use a RequestDispatcher to forward the response to AllCustomers.jsp.
RequestDispatcher dispatcher =
request.getRequestDispatcher("AllCustomers.jsp");
dispatcher.forward(request, response);
h. Make sure that you invoke the processRequest method from the doGet and
doPost methods.
2. Create the PortfolioController servlet that is designed to retrieve a customer’s
portfolio and forward that data to a Portfolio.jsp for display.
a. Create a new Servlet in the BrokerTool project.
b. In the “Create Servlet” dialog box, enter the following information:
• Class Name: PortfolioController
• Package: trader.web

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Developing Servlets


Page 6 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

c. Click the Finish button.


d. Using the @WebServlet annotation, set the URL of the PortfolioController
servlet to /PortfolioController.
e. Import the content of the trader package.
f. Import javax.servlet.RequestDispatcher.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

g. Implement the processRequest method as follows:


You can use the PortfolioController template located at
D:\Labs\eclipse\resources\brokertool\PortfolioController.java
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

String customerId = request.getParameter("customerIdentity");


s a
) h a
BrokerModel model = BrokerModelImpl.getInstance();
c o m

ail ideฺ
try { m
g Gu
o @
8 ent
CustomerShare[] shares =
s
do Stud
model.getAllCustomerShares(customerId);
a r
( a nc this
Customer customer = model.getCustomer(customerId);

o s o use shares);
request.setAttribute("shares",

a rd e to
request.setAttribute("customer", customer);

i d is C licens be) {
} catch (BrokerException
l a le
request.setAttribute("message",
o
be.getMessage());
} ic
e N f e r ab
n d rrequest.getRequestDispatcher("Portfolio.jsp");
s
RequestDispatcher
n dispatcher =

e ra
xa n-tdispatcher.forward(request,
A l no response);
}
h. Make sure that you invoke the processRequest method from the doGet and
doPost methods.
3. Run and test the application.
a. Save any modified files. If “Build Automatically” is not enabled, build the BrokerTool
web application manually.
b. Select the BrokerTool project in the Project Explorer window. Run the application by
selecting Run from the Run menu. You might have to select the Run on Server option
from the “Run as” dialog box.
c. Select GlassFish 3.1 at localhost under localhost in the “Run on Server” dialog box.
d. Test the servlet by entering the following URL in a browser:
http://localhost:8080/BrokerTool/

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Developing Servlets


Page 7 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

e. You will see an empty customer details form. You should be able to enter a known
customer identity, such as 111-11-1111, and retrieve information for that customer. Try
all the buttons on the customer details page. Links such as View Portfolio, All
Customers, and Stocks will not function yet. Fix any errors that occur when using the
Customer Details form.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Developing Servlets


Page 8 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 4-3: Describing Servlet Components

Overview

In this practice, you check your understanding of web components.


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Task
1. In the following sentences, fill in each blank with the appropriate word (or words):
a. The _____________________________ package contains the HTTP- specific servlet
classes.
b. The _______________ object type is representative of the storage area that is
provided by a Java EE web container for managing sessions in the web component
model.
c. The method signature of the initialization method inherited from HttpServlet that is a
recommended for use is ______________.
h a s
m
d. The __________________ method typically calls the doGet or doPost method. )
ฺ c o
e.
ail ideฺ
In the WEB-INF directory of a web application, a configuration file named
m
________________ is used to configure the application.
@ g Gu
f. 8 ent
In Java EE 6, the __________________ annotation can be used in place of the init
s o
method for a servlet.
a r do Stud
g.
is used. ( a nc this
To read form data, the ____________________ method of an HttpServletRequest

h. o s o use
__________________ class has a forward and include method used to invoke a
a rd e to
servlet from within another servlet.
i. is C licens
In Java EE 6, the __________________ annotation can be used in place of the
i d
c o la le
deployment descriptor to specify a URL for a servlet.
j.
e N i r ab
Every time a request.getSession method is called, the server attempts to send a
f e
a n dr rans
________________ to the client.
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Developing Servlets


Page 9 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice Solutions
This section contains the practice solutions.

Solutions for Practices 4-1 and 4-2


You can find solutions for these practices in the following directory:
D:\Labs\eclipse\solutions\Servlets.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Solutions for Practice 4-3

Compare your responses with the following:


a. The javax.servlet.http package contains the HTTP-specific servlet classes.
b. The HTTPSession object type is representative of the storage area that is provided by a
Java EE web container for managing sessions in the web component model.
c. The method signature of the initialization method inherited from HttpServlet that is s a
recommended for use is init(). ) h a
c o m
d. The service(HttpServletRequest, HttpServletResponse) method typically calls the doGet
or doPost method.

ail ideฺ
m
gfile named uweb.xml is
e. In the WEB-INF directory of a web application, a configuration @ t G
used to configure the application.
o s o8 den
f. In Java EE 6, the @PostConstruct annotationacan rd be used
S tinuplace of the init method
for a servlet. a n c his
( e t
d o so usmethod of an HttpServletRequest is
g. To read form data, the getParameter("name")
used.
a r e to
h. RequestDispatcheris C has anforward
class s and include method used to invoke a servlet
i d l i c e
i c o6,lathe @WebServlet
from within another servlet.
b le
i. In Java
e N EE
f e r a annotation can be used in place of the deployment

n r
ddescriptor n s specify a URL for a servlet.
to
a r a
n-t time
x j. Every
Ale nocookie
the request.getSession method is called, the server attempts to send a
to the client.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Developing Servlets


Page 10 of 10
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
@
8 ent 5:
Practices ofor Lesson
s
Developing
a r tud JavaServer
do Swith
( a nc tTechnology
Pages his
e
so Chapter
us 5
r d o t o
C a se
i d i licen
s
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Developing with JavaServer Pages Technology DEVELO


Page 1 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practices for Lesson 5: Overview

Practices Overview
In these practices, you:
• Create a JSP component
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Use JSP scriptlet tags


• Use JSTL tags
• Use the Expression Language (EL)

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Developing with JavaServer Pages Technology DEVELO


Page 2 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 5-1: Creating the AllCustomers.jsp Component

Overview

In this practice, you create the AllCustomers.jsp component that displays the identities,
names, and addresses of all customers registered in the BrokerTool application (as shown in
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

the following figure):

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
AlePrerequisites
n o n
• The application server should be installed.
• You have completed the previous lesson’s BrokerTool practice.

Tasks
1. Create the AllCustomers.jsp component.
a. In Eclipse, open the BrokerTool project located at D:\Labs\eclipse\projects.
b. In the Project Explorer window, right-click the BrokerTool icon.
c. Select New and then select JSP File.
d. Enter the following information in the “New JSP File” dialog box:
• Parent Folder: BrokerTool/WebContent
• File Name: AllCustomers
e. Click the Finish button.
f. Modify the AllCustomers.jsp component to ensure the following behavior:
1) Add a page import directive to import the classes in the trader package.
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Developing with JavaServer Pages Technology DEVELO


Page 3 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

2) Make the page title All Customers.


3) Create a table-based navigational menu along the top that includes links to:
<a href=’CustomerDetails’>Customer Details</a>
<a href='AllCustomers'>All Customers</a>
<a href='Stocks.xhtml'>Stocks</a>
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

4) Create a table with the following headers: Customer Id, Name, Address, and
Portfolio.
5) Using a scriptlet tag, create a customers array variable of type Customer[].
Retrieve the array data from customers attribute stored in the request scope and
assign it to the customers array. This attribute was created by the
CustomerController.
6) Create a for loop to iterate through all the customers. For each iteration, display a
table row with a customer’s ID, name, and address as well as a link to view the
customer’s portfolio. Use JSP expression tags to display the data. The following is s a
a sample portfolio link: ) h a
<a href='PortfolioController?customerIdentity=<%=
c o m
customers[i].getId() %>'>View</a> ฺ
ail ideฺ
7) Close the table. m
g Gu
o @
8 ent
8) Using scriptlet tags, display the message stored in the request scope under the
attribute name message.
s
do Stud
a r
<%
( a nc this
String message =
o s o use
a rd e to
(String)request.getAttribute("message");
C null)ns{
is != ce
if(message
l a i d l i
c o l e
out.println("<font color='red'>" + message +

e N i
f e r ab "</font>");

a n dr ra} ns
x %>-t
Ale non
2. Run the application.
a. Save any modified files. If “Build Automatically” is not enabled, build the BrokerTool
web application manually.
b. Run the application. Test your JSP by entering the following URL in a browser:
http://localhost:8080/BrokerTool/AllCustomers

c. You should see a table of all customers. Fix any errors that occur.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Developing with JavaServer Pages Technology DEVELO


Page 4 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 5-2: Creating the Portfolio.jsp Component

Overview

In this practice, you create the Portfolio.jsp component that displays the symbols and
quantities of stocks owed by the customer most recently selected on the CustomerDetails
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

page:

Prerequisites
• The application server should be installed.
• You have completed the previous BrokerTool exercise.

Tasks
1. Create the Portfolio.jsp component in BrokerTool. a
a. Enter the following information in the “New JSP File” dialog box and click the Finish h a s
button: m )
o
• Parent Folder: BrokerTool/WebContent a ilฺc eฺ
• File Name: Portfolio
@ gm Guid
b. Add a page import directive to import the classes insthe o t
8traderenpackage.
c. Add a directive to include the Java StandardaTag r tuindthe following example:
dolibrary,Sas
( a nc this
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
o e
d. Give the page the title Portfolio.
r d os to us
e. Create a table-basedC a semenu along the top that includes links to:
navigational
i d i licen
s
o l a
<a href=’CustomerDetails’>Customer
l e
Details</a>

N ic rab
<a href='AllCustomers'>All Customers</a>

d n s fe
r<ae href='Stocks.xhtml'>Stocks</a>
n traa JSTL <c:choose>
xa f. ntest="${...}">
Create tag. Inside <c:choose>, create a <c:when
l e -
A no tag and a <c:otherwise> tag.
g. The test in <c:when test="${...}"> should use the EL to test if there is a
message stored in requestScope. ${requestScope.message == null}
1) If there is no message, do the following:
a) Display a message with the customer’s name:
${requestScope.customer.name}'s Stocks <br />
b) Create a table with Stock Symbol and Quantity as headers.
c) Use JSTL and EL to display the CustomerShare[] array stored in the
request scope by the PortfolioController.
<c:forEach var="share" items="${requestScope.shares}">
<tr>
<td>${share.stockSymbol}</td>
<td>${share.quantity}</td>
</tr>
</c:forEach>

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Developing with JavaServer Pages Technology DEVELO


Page 5 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

2) If there is a message, display it inside the <c:otherwise> tags by using the EL to


read the string stored under the attribute name of the message in the request
scope.
2. Run the application.
a. Save any modified files. If “Build Automatically” is not enabled, build the BrokerTool
web application manually.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

b. Run the application. Test your JSP by entering the following URL in a browser:
http://localhost:8080/BrokerTool/
Get the details of a customer with shares. You can read BrokerModelImpl.java to find
a customer with shares, or you can use 123-45-6789. After getting the details for a
customer, use the View Portfolio link to view that customer’s portfolio.
You should see a table of all shares for the customer. Fix any errors that occur.

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Developing with JavaServer Pages Technology DEVELO


Page 6 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 5-3 (Optional): Creating the CustomerDetails.jsp


Component

Overview
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

This practice is optional and provides fewer instructions in order to provide a challenge for more
advanced students. Ask your instructor if you have time to complete this exercise.

In this practice, you create the CustomerDetails.jsp component that displays the identities,
names, and addresses of all customers registered in the BrokerTool application.

Prerequisites
• The application server should be installed.
• You have completed the previous BrokerTool exercise.
s a
) h a
Tasks m
ฺ c o
1. Create the CustomerDetails.jsp component.
m ail ideฺ
@ g Gu
a. Create a new JSP component in the BrokerTool project.
s o 8 ent
b. Enter the following information in the “New JSP r dFile” d
o dialogtubox:
a
nc this S
• Parent Folder: BrokerTool/WebContent
(
o usea
• JSP File Name: CustomerDetails
o s
a
c. View the details of a customer rd by eusingto the existing CustomerDetails servlet at
d is C licens
http://localhost:8080/BrokerTool/.
i
d. View the c o la output
HTML le of the CustomerDetails servlet using your web browser.
N i a b
d r s fer of the CustomerController servlet.
e thenbehavior
e. View

e x anf. Using
- trathe information gathered in steps d and e, code the functionality of
A l no n
CustomerDetails.jsp. Use JSTL and EL; avoid scriptlets.
g. Modify the CustomerController servlet to forward to the new JSP page.
h. Modify the default welcome page in the web.xml deployment descriptor.
i. In all JSP pages, modify all links that point to the CustomerDetails servlet to point
to CustomerDetails.jsp.
2. Run the application.
a. Save any modified files.
b. Run the BrokerTool application. Test your JSP by entering the following URL in a
browser:
http://localhost:8080/BrokerTool/

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Developing with JavaServer Pages Technology DEVELO


Page 7 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 5-4: Describing JavaServer Pages Components

Overview

In this practice, you check your understanding of JSP components.


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Tasks

In the following sentences, answer “true” or “false” or fill in the blanks with the appropriate word
(or words):
1. A JSP typically has fewer lines of Java code than HTML. (True or false?)
2. A typical scriptlet tag starts with ______ and ends with ______.
3. To import the classes in the java.util package in a JSP, you add
_________________________________ to the JSP. s a
4. In place of scriptlet code, a jsp:useBean tag in the form of ) h a
c o m
_________________________________ can be used to locate a Customer object

ail ideฺ
stored with the HttpServletRequest.setAttribute("Customer", cust)
method.
m
g Gu
o @
8 ent
5. Java EE has a prewritten set of custom tag libraries known as the _________.
s
do Stud
r
6. The ____________________ is the name of the new JavaScript-like language that is
a
( a nc this
executed during the server-side execution of a JSP.

o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Developing with JavaServer Pages Technology DEVELO


Page 8 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice Solutions
This section contains the practice solutions.

Solutions for Practices 5-1 and 5-2


You can find solutions for these practices in the following directory:
D:\Labs\eclipse\solutions\JSP
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Solutions for Practice 5-3


You can find solutions for this practice in the following directory:
D:\Labs\eclipse\solutions\JSPs\Practice3

Solutions for Practice 4: Describing JavaServer Pages Component

Compare your responses with the following answers:


1. A JSP typically has fewer lines of Java code than HTML. (True) s a
) h a
2. A typical scriptlet tag starts with <% and ends with %>. m
ฺ c o
3. To import the classes in the java.util package in a JSP, you add <%@
import="java.util.*" %> to the JSP. m ail ipage
d eฺ
@ g Gu
4. In place of scriptlet code, a jsp:useBean tag in the form
o8a Customer
of t
<jsp:useBean
e n
id="Customer" scope="request" /> can be used to o
d s
locate
u d object stored with
r t
the HttpServletRequest.setAttribute("Customer",
a n ca his S cust) method.
5. Java EE has a prewritten set of custom
o e t known as the JSTL.
( tag libraries
s
ois the tname s
uof the new JavaScript-like language that is
6. The Expression Language (EL)
a r d o
i s e se of a JSP.
C nexecution
executed during the server-side

o l aid le lic
N ic rab
n d re nsfe
l e xa n-tra
A no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Developing with JavaServer Pages Technology DEVELO


Page 9 of 10
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Developing with JavaServer Pages Technology DEVELO


Page 10 of 10
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
@
8 ent 6:
Practices ofor Lesson
s
Developing
a r tud JavaServer
do Swith
( a nc thiTechnology
Faces™ s
e
so Chapter
us 6
r d o t o
C a se
i d i licen
s
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Developing with JavaServer Faces™ Technology


Page 1 of 12
Pontifícia Universidade Católica do Rio Grande do Sul

Practices for Lesson 6: Overview

Practices Overview
In these practices, you:
• Enable the JSF framework in a Java EE application
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Create a JSF Facelet page


• Create a JSF managed bean
• Use JSF tags
• Use the Expression Language (EL) with managed beans

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Developing with JavaServer Faces™ Technology


Page 2 of 12
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 6-1: Creating the Stocks.xhtml Component

Overview

In this practice, you create the Stocks.xhtml component, which displays the names and
prices of all stocks in the BrokerTool application (as seen in the following figure):
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale •nonThe application server should be installed.
Prerequisites

• You have completed the previous BrokerTool exercise (thru Practice 5-2).

Tasks
1. Configure the JSF facelet servlet.
a. Open the web.xml file
b. Switch to the design view. Modify the deployment descriptor to add a new Servlet
element. Right-click the web-app element and select Add Child >locale-encoding -
mapping-list – welcome-file-list and click servlet. Add the following child elements:
• Servlet Name: Faces Servlet
• Servlet Class: javax.faces.webapp.FacesServlet
• Load-On-Startup:1

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Developing with JavaServer Faces™ Technology


Page 3 of 12
Pontifícia Universidade Católica do Rio Grande do Sul

c. Add a servlet-mapping entry to web-app and add the following child elements.
• Servlet Name: Faces Servlet
• URL Pattern(s): *.xhtml
d. Click the source tab to view the XML code of web.xml.
e. The following XML servlet and servlet-mapping tags are included in the
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

web.xml deployment descriptor:


<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-
class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping> s a
<servlet-name>Faces Servlet</servlet-name> ) h a
c o m
<url-pattern>*.xhtml</url-pattern>

ail ideฺ
</servlet-mapping>
m
g Gu
2. Configure your project for JSF settings.
o @
8 eand n t
a. Select and right-click the BrokerTool project in Project
d o s u d
Explorer, then select
r S t
Properties.
a n caclick hProject
i s
b. In the Properties for BrokerTool dialog
o ( se t
box, Facets on the left.
s box and click the Further configuration required
rd e to u
c. Select the Java Server Facesocheck
link at the bottom of the a page.
1) Click the Manage
i d i s CLibraries
c e nsicon on the right of the “JSF Capabilities” dialog box to
i JSTL user library.
add jars
o lato the JSF
l e land
N c
a) i In the “User
r b Libraries” dialog box, click the New button to create a User
aand
d r e f e
Library
s name it JSF. Click OK.
n n
l e xa n-trb)a Select JSF and click the Add Jars button. Browse to the location
A no D:\glassfish3\glassfish\modules
jsf-api.jar files. Click OK.
and select the jsf-impl.jar and

c) Create another User Library with the name JSTL and add jars to it (similar to
what you did in step b). The location is the same, and the jar files are jstl-
impl.jar and jstl-connector.jar. Click OK.
d) In the “JSF Capabilities” dialog box, remember to select the listed User
Libraries as shown in the following diagram and click OK. Click OK again to
close the Project Facets dialog box.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Developing with JavaServer Faces™ Technology


Page 4 of 12
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x t StocksManagedBean JSF component.
-the
Ale3. Create
n o
a.
n
Right-click the BrokerTool project and select New > Class.
b. Enter the following values in the “Java Class” dialog box:
• Source Folder: BrokerTool/src
• Package: trader.web
• Name: StocksManagedBean
c. Click Finish.
d. In the class, add the following annotations to declare this class a managed bean:
@ManagedBean(name="stocks")
@RequestScoped
e. Add an instance variable of type BrokerModel in the StocksManagedBean class.
private BrokerModel model = BrokerModelImpl.getInstance();
f. Declare the following method:
public Stock[] getAllStocks() { }
g. Add any required import statements.
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Developing with JavaServer Faces™ Technology


Page 5 of 12
Pontifícia Universidade Católica do Rio Grande do Sul

h. Implement the getAllStocks method as follows:


• Retrieve an array of all Stock objects using the model variable.
• Catch any exceptions that occur. Return null if an Exception occurs.
5. Create the Stocks.xhtml facelet page.
a. Select and right-click BrokerTool in the Project Explorer window. Select New > XHTML
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

page. In the “New XHTML file” dialog box, specify the following values:
• Parent Folder: BrokerTool/WebContent
• File Name: Stocks
Click the Next button.
b. In the “Select XHTML Template” dialog box, select the option (as shown in the
following figure). Click the Finish button.

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Developing with JavaServer Faces™ Technology


Page 6 of 12
Pontifícia Universidade Católica do Rio Grande do Sul

c. Add the core JSF tags to the Stocks.xhtml page:


<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
d. Modify the Stocks.xhtml page as follows:
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Specify a value of Stocks for the page title.


• Delete the content of the existing body tag.
e. Create a table-based navigational menu along the top that includes links to:
<a href=’CustomerDetails’>Customer Details</a>
<a href='AllCustomers'>All Customers</a>
<a href='Stocks.xhtml'>Stocks</a>
f. Use the <h:dataTable> tag to display the symbol and price of all stocks.
s a
6. Run the application.
) h a
o m
a. Save any modified files. If “Build Automatically” is not enabled, build the BrokerTool
c
web application manually. ฺ
ail ideฺ
m
g Gu
b. Run the application. Test your JSF page by entering the following in a browser:
o @
8 ent
s
http://localhost:8080/BrokerTool/Stocks.xhtml
do Stud
r
You should see a table of all stocks. Fix any errors that occur.
a
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Developing with JavaServer Faces™ Technology


Page 7 of 12
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 6-2 (Optional): Implementing the JSF


CustomerDetails.xhtml View

Overview
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

This practice is optional and provides fewer instructions in order to provide a challenge to more
advanced students. Ask your instructor if you have time to complete this exercise.
In this practice, you create the CustomerDetails.xhtml page that displays the identities,
names, and addresses of all customers registered in the BrokerTool application.

Prerequisites
• The application server should be installed.
• You have completed the previous BrokerTool exercise.
s a
Tasks
) h a
1. Create the CustomerManagedBean JSF component.
c o m

ail ideฺ
a. On the Project Explorer window, expand Broker Tool > WebContent > WEB_INF. Click
faces-config.xml to open it in the editor window.
m
g Gu
o @
8 ent
s
b. Switch to the ManagedBean tab of the faces-cofig.xml file in the editor window
do Stud
and click the Add button.
a r
( a nc this
c. In the “Java Class Selection” dialog box, select the “Create a new Java class” option.
Then click Next.
o s o use
rd e to
d. Enter the following values in the “Java Class” dialog box:
a
i d is C licens
• Source Folder: BrokerTool/src
• Package:
i c olatrader.web
b le
• N
e nsfer a
Name: CustomerManagedBean
d r
e x ane. Click
- t r athe Next button and provide the following information in the “Managed Bean

Al non
Configuration” dialog box:
• Name: CustomerDetails
• Scope: request
Click the Next button to view the wizard summary and then click the Finish button. Save
the file.
2. Update the CustomerManagedBean class.
a. Add the following import statements to the class.
import trader.BrokerException;
import trader.BrokerModel;
import trader.BrokerModelImpl;
import trader.Customer;
b. Add an instance variable of type BrokerModel in the CustomerManagedBean class.
private BrokerModel model = BrokerModelImpl.getInstance();
c. Create the following variables along with getters and setters in the
CustomerManagedBean class:
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Developing with JavaServer Faces™ Technology


Page 8 of 12
Pontifícia Universidade Católica do Rio Grande do Sul

private String message = "";


private String customerId = "";
private String customerName = "";
private String customerAddress = "";
d. To automate the creation of getters and setters, right-click a variable name. Select
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Source and then Generate Getters and Setters. This will automate the creation of the
getters and setters.
e. Create controller methods by completing the following instructions:
• All methods should use the variables from step 5 and the model variable from step 4
during execution.
• In the event of an a BrokerException the message variable should be set to the
value of Exception.getMessage().
• Return a String value of CustomerDetails. a
• Add the following method signatures. Implement the functionality of the methods h a
as
s
indicated by the method name. m )
o
public String retrieveCustomer() a ilฺc eฺ
public String updateCustomer()
@ gm Guid
public String addCustomer()
s o 8 ent
public String deleteCustomer()
a r do Stud
3. Create the CustomerDetails.xhtml facelet a c his
npage.
a. Select and right-click BrokerTool s o ( s e t Explorer window. Select New >
in theuProject
XHTML page. In the “New a do File”
rXHTML to dialog box, specify the following value:
C ns e
• Parent Folder:
i d is BrokerTool/WebContent
l i c e
l a le
N icothe Next
• File Name:
Click r
CustomerDetails
a bbutton.
d r ethe “Select
s f eXHTML
a In
a n
nClick thetrFinish
b. Template” dialog box select the option (as shown in the figure).
x - button
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Developing with JavaServer Faces™ Technology


Page 9 of 12
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non
c. Add the core JSF tags to the CustomerDetails.xhtml page:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
d. Modify the CustomerDetails.xhtml page as follows:
• View the details of a customer by using the existing CustomerDetails servlet
at http://localhost:8080/BrokerTool/.
• View the HTML output of the CustomerDetails servlet using your web
browser. Use this as a guide for the structure of the facelet page.
• Specify a value of Customer Details for the page title.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Developing with JavaServer Faces™ Technology


Page 10 of 12
Pontifícia Universidade Católica do Rio Grande do Sul

• Remove any existing body content.


• Create a table-based navigational menu along the top that includes links to:
<a href=’CustomerDetails.xhtml’>Customer Details</a>
<a href='AllCustomers'>All Customers</a>
<a href='Stocks.xhtml'>Stocks</a>
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Use the h:form, h:inputText, and h:commandButton tags along with EL


to implement the Customer Details form.
4. Configure, deploy, and run the application.
a. Save any modified files.
b. Run the application. Test your JSF by entering the following URL in a browser:
http://localhost:8080/BrokerTool/CustomerDetails.xhtml
The other views of the application still link to the previous implementation of the Customer
Details view. Do not remove the older CustomerDetails implementation. Converting all s a
the views and controllers to use JSF is beyond the scope of this course. The solution
) h a
c o m
project for this exercise is an example of converting the entire application to JSF.

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Developing with JavaServer Faces™ Technology


Page 11 of 12
Pontifícia Universidade Católica do Rio Grande do Sul

Practice Solutions
This section contains the practice solutions.

Solutions for Practices 6-1 and 6-2


You can find solutions for these practices in the following directory:
D:\Labs\eclipse\solutions\JSF
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Developing with JavaServer Faces™ Technology


Page 12 of 12
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
Practices ofor @
8 ent 7: EJB
Lesson
Component
s ud
do StModel
a r
( nc
Chapter 7 th
a is
so us e
r d o to
a e
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: EJB Component Model


Page 1 of 8
Pontifícia Universidade Católica do Rio Grande do Sul

Practices for Lesson 7: Overview

Practices Overview

The purpose of these practices is to learn the basic structure of an EJB module and how to
deploy it. The existing SampleWebApplication is modified to become a simple EJB client. This
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

EJB client makes use of EJB annotations to find an EJB for use.

In these practices, you:


• Create and deploy a simple EJB component module
• Use annotations and dependency injection
• Run a simple EJB client application

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: EJB Component Model


Page 2 of 8
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 7-1: Creating and Deploying a Simple EJB Application

Overview
In this practice, you create and deploy an EJB module and an EJB client.

Prerequisites
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• The application server should be installed and configured in Eclipse.


• You have completed the SampleWebApplication practice.

Tasks
1. Create an EJB application module.
a. From the Eclipse menu select File, and then select New > Project.
b. Expand EJB, and then select EJB Project.
c. Click Next.
s a
d. Enter the following information in the “EJB Project” dialog box. ) h a
• Project Name: SampleEJBApplication c o m

ail ideฺ
• Project Location: Select Use Default Location m
(D:\Labs\eclipse\projects\SampleEJBApplication)
@ g Gu
• Target Runtime: GlassFish 3.1 s o 8 ent
• EJB module version: 3.1 a r do Stud
• Configuration: Default Configuration ( a nc thfor is GlassFish 3.1
so in the e
us“Java” dialog box and click the Next button.
e. Click Next. Accept the default
r d oentries
t o
f. Click Finish. C a se
2. Create a basic session i d i EJB.licen
s
c la SampleEJBApplication
othe le
a. Right-click
N i r a b project and select New. Then select Session
e
drIn thera“Create
Bean (EJB
s f e
3.x).
a n
b. t n EJB 3.x Session Bean” dialog box, enter the following information:
l e x n -
A no • Java Package: test
• Class Name: BasicSession
• Superclass: (blank)
• State Type: Stateless
• Create Business Interface: Remote
• Uncheck the No-interface check box
c. Click Next. Accept all the default entries and click Finish.
3. Add a business method to the BasicSession EJB.
a. Add a method signature in BasicSessionRemote.java.
String getMessage();

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: EJB Component Model


Page 3 of 8
Pontifícia Universidade Católica do Rio Grande do Sul

b. Add a business method to BasicSession.java. The method should be:


public String getMessage() {
return "Hello EJB World";
}
c. Perform a Clean of the project if “Build Automatically” is not enabled on the Projects
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

menu.
4. Configure GlassFish 3.1 server to use Jar archives for deployment.
a. Ensure that the Java EE Perspective is open.
b. Switch to the Servers tab of the Java EE Perspective window.
c. Double-click the GlassFish 3.1 at localhost entry to open its Overview window in the
editor window.
d. Scroll to the Application Server section of the window.
e. Select the “Use Real Jar Archives for Deployment” check box.
s a
f. Save the change and close the window.
) h a
5. Add the EJB project to the libraries of the SampleWebApplication:
c o m

ail ideฺ
a. Open the SampleWebApplication project in Eclipse. m
g Gu
b. Ensure that on the Project menu, “Build Automatically” 8 is @ t
not selected.
s o e n
a r do Stud
c. In the Project Explorer window, right-click SampleWebApplication.
d. Select Properties and click the Deployment
( a nc Assembly
t h is property.
e. On the right panel, click Add. Insthe o ensuingu e box, select Project and click Next.
sdialog
f. Select the SampleEJBApplication
o
rd e toproject from the list and click Finish.
a
g. Click the Ok button
i d istoCclose
li c e ns“Properties” dialog box.
the
6. Use annotations
c o lain the BasicServlet
l e to look up and use the BasicSession EJB.
i
N fera b
a. In SampleWebApplication, open BasicServlet within test package to modify
r e s
x a nd it. tran
-
Ale b.nonImport the javax.ejb.* classes. Most EJB annotations reside in this package.
c. Add an annotated field to the BasicServlet class. An annotated field is typically a
standard non-final instance variable. Within the class add:
@EJB private BasicSessionRemote basicSessionBean;
d. When the BasicServlet is instantiated any annotated fields are automatically
initialized before any of the servlet methods can execute. You can use the session
bean by adding the following line in the processRequest method:
out.println("Message: " + basicSessionBean.getMessage());
7. Deploy and test the application.
a. Ensure that GlassFish server is started. In the Servers window, verify if the “GlassFish
3.1 at localhost” entry has “started” written within brackets.
b. Expand the GlassFish Server entry.
c. If the SampleWebApplication is deployed, undeploy it by right-clicking
SampleWebApplication and selecting Remove. This will clear out any previous
versions.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: EJB Component Model


Page 4 of 8
Pontifícia Universidade Católica do Rio Grande do Sul

d. In the Project Explorer window, select the SampleWebApplication project. On the


menu bar click Run > Run as > Run on Server menu option.
e. In the “Run on Server” dialog box, click the “Choose an existing server” option button
and select “GlassFish 3.1 at localhost” entry under localhost node.
f. Click the Finish button.
g. Test your modified servlet and new EJB by pointing the browser at:
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

http://localhost:8080/SampleWebApplication/BasicServlet
h. You should see the Hello EJB World message displayed.

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: EJB Component Model


Page 5 of 8
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 7-2: Describe the EJB Component Model

Overview
In this practice, you check your understanding of the EJB component model.

Tasks
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

1. In the following sentences, fill in each blank with the missing word (or words):
1. The two types of EJBs are _______________ and _______________ beans.
2. Scheduling the execution of an EJB for a later time can be accomplished with the
_______________________.
3. True or False: An Enterprise Bean instance can have its methods directly invoked by a
client.
4. The three different access types to a Session EJB are ___________, ___________,
and ___________.
s a
5. The two Java technologies that a client can use to gain a reference to a Session Bean
) h a
interface are __________ and __________________.
c o m

ail ideฺ
6. A session EJB always requires an interface. (True or false?)
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: EJB Component Model


Page 6 of 8
Pontifícia Universidade Católica do Rio Grande do Sul

Practice Solutions
This section contains the practice solutions.

Solutions for Practice 7-1


You can find solutions for this practice in the following directory:
D:\Labs\eclipse\solutions\EJBComponents.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Solution for Practice 7-2: Describing the EJB Component Model


Compare your responses with the following answers:
1. The two types of EJBs are session and message-driven beans.
2. Scheduling the execution of an EJB for a later time can be accomplished with the EJB
Timer Service.
3. False (clients use stubs): An Enterprise Bean instance can have its methods directly
invoked by a client.
s a
4. The three different access types to a Session EJB are Local Stub, Remote or ha
Distributed Stub, and Web Service. m )
o
a
5. The two Java technologies that a client can use to gain a reference ilฺacSession
to e ฺ Bean
interface are JNDI and Annotations or Dependency Injection.g m u i d
@ t G
o s o8 A session
6. False (Java EE 6 has a local no-interface session bean):
d e n EJB always
requires an interface.
c a rd Stu
( a n
e t his
d o so us
a r e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: EJB Component Model


Page 7 of 8
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: EJB Component Model


Page 8 of 8
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
@
8 ent 8:
Practices ofor Lesson
s
do StuEJB
Implementing d 3.1
a r
( a nc thiBeans
Session s
e
so Chapter
us 8
r d o t o
C a se
i d i licen
s
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Implementing EJB 3.1 Session Beans DEVELO


Page 1 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practices for Lesson 8: Overview

Practices Overview

In these practices, you learn how to create a singleton session bean as part of a web application
project. A singleton EJB is used for in-memory persistence. These practices also demonstrate
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

the essential features of the Java Naming and Directory Interface (JNDI) API as an alternative
way to find EJB components.

After completing these practices, you should be able to:


• Code a session EJB component
• Create EJB references for web-tier clients
• Create a Java SE EJB client
s a
• Describe session beans
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Implementing EJB 3.1 Session Beans DEVELO


Page 2 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 8-1: Coding the EJB Component and Client

Overview
In this practice, you code a session EJB component.

Prerequisites
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• The application server is installed.


• You have completed the previous BrokerTool practice.

Tasks
1. Ensure that the BrokerTool project is open in Eclipse. Modify the BrokerModelImpl
class to be a local singleton session bean.
Because the BrokerModelImpl class maintains all application data and changes to that
data in memory, a client must have access to the same BrokerModel instance for every
s a
request to see any changes. Allowing the client to reuse the same BrokerModel instance
) h a
can be achieved by making BrokerModelImpl a singleton session bean.
m
ฺ c o
m ail ideฺ
a. The BrokerModelImpl currently implements the traditional singleton design pattern
in such a way that it uses a private constructor. Session beans cannot have non-public
@ g Gu
constructors. Modify the BrokerModelImpl class so that it no longer implements the
singleton design pattern. s o 8 ent
a r do Stud
b. Remove the static model instance and make the constructor public.
// ( a nc this
private static BrokerModel instance = new
BrokerModelImpl();
o s o use
a rd e to
//
i d s C icBrokerModel
public istatic e ns getInstance() {
// olareturn l l
e instance;
// N }i c ra b
r e s f e
x a nd tran
- Creates a new instance of BrokerModelImpl */
Ale non
/**
public BrokerModelImpl() {
c. Add the following import statements:
import javax.ejb.Local;
import javax.ejb.Singleton;
d. Add the annotations required to make the BrokerModelImpl class a singleton
session bean with a local interface.
@Local @Singleton
2. Modify the BrokerModel clients to use the BrokerModelImpl local session bean.
All the servlet- and JSF-managed bean classes that function as controllers in the web tier
must be modified to be EJB clients.
a. Expand the trader.web package in the BrokerTool project.
b. Clean and build the BrokerTool project to discover the classes that need to be
modified to use the new BrokerModelImpl singleton session bean.
c. For all the classes that must be modified perform the following actions:
1) Remove any lines of code that call BrokerModelImpl.getInstance().
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Implementing EJB 3.1 Session Beans DEVELO


Page 3 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

2) Remove any model local variable declarations.


3) Create an instance-level variable:
@EJB private BrokerModel model;
The @EJB annotation cannot be applied to local variables.
1) Add the needed import for the @EJB annotation.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

2) If needed, modify any methods that do not compile to use the new model variable.
Do not call new on the BrokerModelImpl class. Calling new on a session bean is valid
Java syntax but it treats the bean class as a POJO. Any benefits of EJB technology such as
the EJB lifecycle, security handling, and container-managed transactions are lost when
calling new on an EJB bean class.
3. Deploy the application and test it.
a. Save any modified files. If “Build Automatically” is not enabled then build the
BrokerTool web application manually. From the Run menu, click Run As > Run on
Server option. s a
1) In the “Run on Server” dialog box, click the “Choose an existing server” option ) h a
o m
button and select “GlassFish 3.1 at localhost” entry under localhost node.
c
2) Click the Finish button.

ail ideฺ
m
g Gu
b. Test your application by entering the following URL in a browser:
http://localhost:8080/BrokerTool/ o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Implementing EJB 3.1 Session Beans DEVELO


Page 4 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 8-2: Optional - Creating a Java SE EJB Client That Uses JNDI

Overview

In this practice, you code a session EJB component.


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Prerequisites
• The application server is installed.
• You have completed the previous SampleEJBApplication exercise.

Tasks
1. Create the SampleEJBClient project.
a. From the Eclipse menu select File, and then select New > Project.
b. Expand Java and select Java Project. s a
c. Click Next. ) h a
c o m
d. Enter the following information in the “Name and Location” dialog box. ฺ
ail ideฺ
• Project Name: SampleEJBClient m
g Gu
• Use Default Location: D:\Labs\eclipse\projects\SampleEJBClient
o @
8 ent
• JRE: Use default JRE
s
do Stud
a r
• Project Layout: Create separate folders
( a nc for tsources
his and class files
e. Click Next. so us e
d o
r in the o Settings dialog box and click Finish.
tJava
f. Accept the default information a e
Note: If you see a dialog
i d is C e
box with
li c nthes title "Open Associated Perspective?" click Yes.
2. Open and build o a SampleEJBApplication
lthe l e Project.
N i c a b
d r s fer
e thenSampleEJBApplication
x a n Model.
a. Open
t r a project created in Lesson 7, EJB Component
-
Ale non
b. Build the SampleEJBApplication project.
3. Configure the SampleEJBClient Project libraries. Add the gf-client.jar library to the
SampleEJBClient project. The gf-client.jar library allows JNDI lookups from a Java
SE application to a GlassFish 3.1 server.
a. In the Project Explorer window, right-click SampleEJBClient and select Properties.
In the “Properties for SampleEJBClient ” window, select Java Build Path on the left
panel.
b. Switch to the Libraries tab in the “Java Build Path” dialog box. Click the Add External
Jars button.
c. Browse to the D:\glassfish3\glassfish\lib\ folder.
d. Provide the name in the File Name text box: gf-client.jar.
e. Click the Open button.
f. Click OK.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Implementing EJB 3.1 Session Beans DEVELO


Page 5 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

4. Add the SampleEJBApplication as a library to the SampleEJBClient project. The


SampleEJBApplication library provides the BasicSessionRemote interface to the
EJB client.
a. In the Project Explorer window, right-click SampleEJBClient and select Properties
from the context menu. In the “SampleEJBClient Properties” window, select Java
Build Path on the left panel.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

b. Switch to the Projects tab in the “Java Build Path” dialog box. Click the Add button.
c. Select SampleEJBApplication from the Required Project Selection dialog box and
click OK. Click OK to close the “SampleEJBClient Properties” window.
5. Code the EJB client class.
a. Select SampleEJBClient and create a test package. Create a Main class in the
test package. In the test.Main class make the following changes:
b. In the main method, obtain a JNDI Context.
s a
Context ctx = new InitialContext();
) h a
c. Use JNDI to perform a lookup of the BasicSession EJB. The syntax of the JNDI
c o m
name used is java:global/<module-name>/<bean-name>. ฺ
ail ideฺ
m
d. Cast the result of the JNDI lookup to BasicSessionRemote and store it in a local
g Gu
variable. This is the EJB stub.
o @
8 ent
s
do Stud
e. Use the EJB stub to call the getMessage method of the BasicSession and print the
result. a r
( a nc this
f. Catch any exceptions that occur using a try/catch block.
6. o s
Test the EJB client application. o use
a rd e to
a. Click the SampleEJBClient project and click Project menu. If the “Build
i d is C licens
Automatically” option is not selected, click the Build Project option. Do not run the

i c ola ble
project yet. Correct any errors that occur.

r e N fera
b. Ensure that the GlassFish server is started. In the Servers window, “GlassFish 3.1 at

a n d rans
localhost” entry should have “started” written within brackets.
x -t
c. Remove the SampleWebApplication deployment from the GlassFish Server.
Ale non 1) Open the Java EE Perspective.
2) In the Servers tab, expand the GlassFish 3.1 at localhost server.
3) Right-click the SampleWebApplication deployment and select Remove.
d. In the Project Explorer window, select the SampleEJBApplication project. From the
menu bar, click Run > Run as > Run on Server option.
1) In the “Run on Server” dialog box, click the “Choose an existing server” option
button and select “GlassFish 3.1 at localhost” entry under localhost node. Click
Finish.
e. From Eclipse, run the SampleEJBClient project’s Main class.
1) In the Project Explorer window, expand the SampleEJBClient >src >test
node.
2) Right-click Main.java and select Run as > Java Application.
3) You will see the “Hello EJB World” message in the Console window.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Implementing EJB 3.1 Session Beans DEVELO


Page 6 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

If you run SampleEJBClient without SampleEJBApplication deployed, you might


receive an error message similar to the following:
javax.naming.NamingException: Lookup failed for
'java:global/SampleEJBApplication/BasicSession' in
SerialContext,orb'sInitialHost=localhost,orb'sInitialPort=37 00
[Root exception is javax.naming.NameNotFoundException:
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

SampleEJBApplication]
If you receive the following error message:
javax.naming.NoInitialContextException: Need to specify class
name in environment or system property, or as an applet
parameter, or in an application resource file:
java.naming.factory.initial
it indicates that you have not added gf-client.jar to the SampleEJBClient project.
7. Additional troubleshooting tips:
s a
a. To determine what the GlassFish server is publishing as the lookup names of the EJB
) h a
c o m
objects, right-click the GlassFish Server at localhost icon in the Servers tab and select
GlassFish -> View Log File. ฺ
ail ideฺ
b. You should see messages like this: m
g Gu
INFO: Portable JNDI names for EJB BasicSession
o @
8 e:nt
s
do Stud
[java:global/SampleEJBApplication/BasicSession!test.BasicSession
a r
Remote, java:global/SampleEJBApplication/BasicSession]
( a
INFO: Glassfish-specific (Non-portable) nc this JNDI names for EJB
s o use
BasicSession : [test.BasicSessionRemote#test.BasicSessionRemote,
o
test.BasicSessionRemote]
a rd e to
i d is C licens was successfully deployed in 235
INFO: SampleEJBApplication
milliseconds.
c la le
othat
e N i
c. Make sure
f e r ablookup matches either the portable or non-portable JNDI names
the

a n dr ransTry changing the value of the lookup to the non-portable JNDI names.
published
d. (Optional)
by GlassFish.

x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Implementing EJB 3.1 Session Beans DEVELO


Page 7 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 8-3: Describing Session Beans

Overview

In this practice, you check your understanding of the EJB component model.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Tasks

In the following sentences, fill in each blank with the missing word (or words):
1. The three types of session beans are _______________, _______________ and
_______________.
2. To declare a session EJB as a remote EJB, you can place the @Remote annotation on
the _________________ or _________________.
3. For a session bean to access its environment including transaction status, the bean s a
needs a reference to its _________________.
) h a
4. o m
The two annotations that have meaning in a stateful session bean but not a stateless
c

ail ideฺ
session bean are _________________ and _________________.
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Implementing EJB 3.1 Session Beans DEVELO


Page 8 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice Solutions

Use the following solutions to check your answers to the exercises in this practice.

Solutions for Practices 8-1 and 8-2


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

You can find solutions for these practices in the following directory:
D:\Labs\eclipse\solutions\SessionBeans\

Solutions for Practice 8-3

Compare your responses with the following answers:


1. The three types of session beans are singleton, stateful, and stateless.
2. To declare a session EJB as a remote EJB, you can place the @Remote annotation on
s a
the bean class or business interface.
) h a
3. o m
For a session bean to access its environment including transaction status, the bean
c
needs a reference to its SessionContext. ฺ
ail ideฺ
4. The two annotations that have meaning in a stateful session g m u a stateless
bean but not
session bean are @PostActivate and @PrePassivate. 8@ t G
o s o den
c a rd Stu
( a n
e t his
d o so us
a r e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Implementing EJB 3.1 Session Beans DEVELO


Page 9 of 10
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Implementing EJB 3.1 Session Beans DEVELO


Page 10 of 10
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
Practices ofor @
8 ent 9: The
Lesson
Java
s
do Stud API
Persistence
a r
( nc
Chapter 9 th
a is
so us e
r d o to
a e
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: The Java Persistence API


Page 1 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practices for Lesson 9: Overview

Practices Overview
In these practices, you:
• Create and configure a persistence unit
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Use the basic functionality of the Java Persistence API


• Describe the Java Persistence API

In this practice, you modify the broker application to use a database. Currently, the broker
application stores all domain data in memory. You create and populate a database to hold
customer, share, and stock data. The BrokerModelImpl session bean is modified to use the
Java Persistence API and the Customer, CustomerShare, and Stock classes are turned into
entity classes.
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: The Java Persistence API


Page 2 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 9-1: Create the Java Persistence API Version of the


BrokerTool Project

Overview
In this practice, you create a database and a persistence unit, and you modify classes to use
the Java Persistence API.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Prerequisites
• The application server and Java DB database are installed, and the application server
is running.
• You have completed the previous BrokerTool exercise.

Tasks
1. Create the StockMarket database. a
a. Start the Java DB database server from the GlassFish asadmin console.
h a s
1) Open a command prompt or a terminal window from the Start button > Run…> m )
ฺ c o
cmd in Windows.
m ail ideฺ
2) At the command prompt, use the cd command to change to
@ g Gu
D:\glassfish3\glassfish\bin folder.
s o 8 ent
3) Enter the asadmin command.
a r do Stud
( a nc this command.
4) At the asadmin prompt, enter the start-database
b. Create a new Connection Profile.o
s u s e
1) Ensure that the GlassFish o
rd server tois running.
a
a) Switch to theCServersnwindow e
s of the Java EE perspective.
i d i s c e
b) Select
o l a “GlassFish
l e li 3.1 at localhost”, right click and select the Start option.
c ab the Windows menu and select Open Perspective > Other >
2) In iEclipse, click
N r
e
dr3) rInathe f
Database e Development.
sDatabase Development window, right-click Databases Connections and
a n n
x -t
Ale non select New.
4) In the “Connection Profile” dialog box, select Derby as the Connection Profile
Types and in the Name text box, enter StockMarket. Click Next.
c. Enter the following information for the database:
• Database Name: StockMarket
• Host: localhost
• Port: 1527
• User Name: user
• Password: user
• Create database: (selected)
• Save Password: (selected)
d. Click Next and then click Finish. This creates the database and adds a connection for
the database under the Database Connection icon.
Right-click the connection you just created and select Open SQL Scrapbook. This
opens a SQL Command window in Eclipse.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: The Java Persistence API


Page 3 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

e. From within Eclipse open the StockMarket.sql file provided in the


D:\Labs\eclipse\resources\brokertool directory.
f. In the StockMarket.sql tab select the Name: StockMarket.
g. Right-click in the StockMarket.sql window and select Execute All to execute the
SQL statements. You will need to select to continue executing the statements in spite
of a few failed executions of the SQL Drop Table commands.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

2. Examine the contents of the database.


a. In the Data Source Explorer window, expand the StockMarket connection under the
Databases Connections node. Right-click StockMarket and select Refresh from the
context menu.
b. Expand StockMarket database and then expand Schemas > USER > Tables node to
see the CUSTOMER, STOCK, and SHARES tables. If the PUBLIC schema does not
show the tables, check the USER schema.
c. Right-click the CUSTOMER table node and select Data > Edit. A SQL window opens to
s a
display the data in the table.
) h a
d. Repeat the previous step for the STOCK and SHARES tables.
c o m
3. Create a Sun Resources descriptor file. ฺ
ail ideฺ
a. Right-click the BrokerTool project and select New > Other. m
g Gu
b. Select GlassFish > JDBC Resource and click Next.
o @
8 ent
s
do Stud
c. Enter the following values in the Sun Resources File dialog:
a r
• Project: BrokerTool
( a nc this
• JNDI Name: jdbc/StockMarket
o s o use
• Connection: StockMarket a rd e to
d. Click Finish.
i d is C licens
e. In line 4 of
c la sun-resources.xml
othe l e file, change the pool-name to following:
i
N fera b
pool-name="StockMarketPool"
4. n r e
d arJDBC
Create n sconnection pool and a JDBC resource in GlassFish.
a a
-t that the GlassFish server is running.
x a. Ensure
Ale b.nonIn the Servers window, right-click GlassFish, select GlassFish > View Admin Console.
The URL http://localhost:4848 opens.
c. Log in to the Admin Console using the administration user name and password
(defaults are admin/adminadmin or admin/ ) on the welcome screen.
d. In the left navigation bar, click Resources > JDBC > Connection Pools. A list of
connection pools appear on the right window.
e. Click New to create a new JDBC connection pool with the following properties:
1) Name: StockMarketPool
2) Resource Type: javax.sql.DataSource
3) Database Vendor: Derby
f. Click Next and scroll to the “Additional Properties” section. Provide the following values
for the properties:
1) User: user
2) Database Name: StockMarket
3) Port Number: 1527

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: The Java Persistence API


Page 4 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

4) Password: user
5) (Add) driverClass: org.apache.derby.jdbc.ClientDriver
6) URL: jdbc:derby://localhost:1527/StockMarket;create=true
7) ServerName: localhost
Click the Add Property button to add the properties that are not visible on the window. Click
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

the Finish button.


g. In the left navigation bar, click Resources > JDBC > JDBC resources. View the
resources created on the application server at the right window.
h. Click New to create a new JDBC resource with the following properties:
• JNDI Name: jdbc/StockMarket
• Pool Name: StockMarketPool
• Status: Enabled
i. Click OK and verify if the resource is listed on the window.
s a
j. Close the Admin Console.
) h a
5. Create a Persistence Unit.
c o m
a. Right-click the BrokerTool project and select Properties.

ail ideฺ
m
g Properties
u listed on
b. In the Properties dialog box, click Project Facets from the@ Project
t G
the left.
o s o8 den
c. Select the JPA check box and click the Further a S tu Required link appearing
rdConfiguration
at the bottom of the Project Facets list. a n c his
in o
( e t
d. Enter the following information s
o s Faceted Project” dialog box:
the “Modify
u
• Platform: EclipseLink d
ar2.0.xse t o
C n Library Configuration
is licDisable
• JPA Implementation:
i d e
• Connection:
i c ola StockMarket
b le
N
•e Persistent
f a
erClass Management: Discover Annotated Classes Automatically
d r s
x ane. Click
- t r aOKnand then click OK again. A persistence unit is created.
e
Al f.nonPersistence.xml
In the Project Explorer window, expand BrokerTool > JPA Content and click
to open in the editor window. You can also view the XML file from
BrokerTool > Java Resources: src > META-INF.
g. Switch to the Connection tab of Persistence.xml. In the Database section, for the
JTA Data source element, enter the value as jdbc/StockMarket. Select JTA from
the drop-down list for Transaction Type. Save the file.
6. Convert the Customer.java class to a Java Persistence API class. In the BrokerTool
project, add the annotations required to convert Customer to a persistence class.
a. Import the javax.persistence package.
b. Add the @Entity annotation to the Customer class.
c. Map the Customer class to the CUSTOMER table with a @Table annotation.
d. Using field-based access, specify that the ID field is the primary key value (@Id). The
ID field should map to the SSN database column using the @Column annotation.
e. The name field should map to the CUST_NAME database column.
f. The addr field should map to the ADDRESS database column.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: The Java Persistence API


Page 5 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Some databases are case-sensitive. You should use the correct case for column names
when specifying the column mapping.
7. Convert the CustomerShare and Stock classes to use the Java Persistence API. Modify
the two classes of the BrokerTool project.
a. Import the javax.persistence package.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

b. Add no-arg constructors for each class.


c. Add any annotations necessary to make CustomerShare and Stock Entity classes.
d. Using the database table structure as information, add field-based persistence
annotations to CustomerShare.java and Stock.java.
e. For the CustomerShare class, add the following annotations for the id field.
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "ID")
8. Modify the BrokerModelImpl.java class of the BrokerTool project to use the Java
s a
Persistence API. Modify all methods to use the newly modified Customer,
) h a
CustomerShare, and Stock entity classes.
c o m
a. Import the javax.persistence package.

ail ideฺ
m
g Guinstance
b. Use dependency injection to obtain a reference to an EntityManager
o @
8 ent
named em. s
do Stem; ud
@PersistenceContext private EntityManager a r
c. Modify the BrokerModelImpl class ( a ncthat there
so t hisare no more in-memory lists of
domain objects. Perform the following so changes:
us e
r d o t o
1) Change BrokerModelImpl
C a se to a stateless session bean.
2) Remove the
i d s icenshares, and stocks list instance variables.
icustomers,
3) Remove c o laall codelein lthe constructor.
e
Eclipse N
will
i
f e
identify r ab
a number of errors after the instance variables are removed. Use the
a n drsteprtoanfixsall the errors.
next
x -t the following sample methods as a starting point to modify all the
Ale d.nonUseBrokerModelImpl methods to use the Java Persistence API:
public Stock[] getAllStocks() throws BrokerException {
Query query = em.createNativeQuery("SELECT * FROM STOCK",
Stock.class);
List stocks = query.getResultList();
return (Stock[]) stocks.toArray(new Stock[0]);
}

public Stock getStock(String symbol) throws BrokerException {


Stock stock = em.find(Stock.class, symbol);
if (stock == null) {
throw new BrokerException("Stock : " + symbol + " not
found");
} else {
return stock;
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: The Java Persistence API


Page 6 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

}
}

public void addStock(Stock stock) throws BrokerException {


try {
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

em.persist(stock);
} catch (EntityExistsException exe) {
throw new BrokerException("Duplicate Stock : " +
stock.getSymbol());
}
}

public void updateStock(Stock stock) throws BrokerException {


s a
Stock s = em.find(Stock.class, stock.getSymbol());
) h a
if (s == null) {
c o m

ail ideฺ
throw new BrokerException("Stock : " + stock.getSymbol()
+ " not found"); m
g Gu
} else {
o @
8 ent
em.merge(stock); s
do Stud
a r
nc this
}
} ( a
o use
o s
a rd e to stock) throws BrokerException {
is= Cstock.getSymbol();
ns
public void deleteStock(Stock
d
String iid
li c e
c o la= em.find(Stock.class,
l e
N iif (stock
stock
a b id);

d r e nsfer == null) {
e x an + -"tranot throw new BrokerException("Stock : " + stock.getSymbol()

Al non
found");
} else {
em.remove(stock);
}
}
9. Deploy the application and test it.
a. Save any modified files. If “Build Automatically” is not enabled then build the
BrokerTool project manually.
b. Deploy the application by right-clicking BrokerTool in the Project Explorer window.
Then, from the Run menu, select Run as >Run on Server.
1) In the “Run on Server” dialog box, click the “Choose an existing server” option
button and select “GlassFish 3.1 at localhost” entry under localhost node.
2) Click the Finish button.
c. Test your application by entering the following in a browser:
http://localhost:8080/BrokerTool/

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: The Java Persistence API


Page 7 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 9-2: Describing Java Persistence API

Overview

In this practice, you check your understanding of the Java Persistence API.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Tasks
1. Answer the question or fill in the blanks of the following sentences with the missing word or
words:
1. The Java Persistence API requires an application server. (True or false?)
2. The fully qualified annotation used by classes to be marked as Entity classes is
_________________.
3. Entity classes often function as data transfer objects (DTOs) and implement the
_________________ interface.
s a
4. True or False: An entity class can have either field-based or property-based access but
) h a
not both.
c o m

ail ideฺ
5. The _________________ annotation is used to have an EntityManager injected in a
managed component. m
g Gu
@
8 ent
6. Every entity class must have a property or field that is annotated as the
o
_________________. s
do Stud
a r
7. When the transaction ends, the entity instance becomes _________________.
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: The Java Persistence API


Page 8 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice Solutions

Use the following solutions to check your answers to the practices.

Solutions for Practice 9-1


You can find solutions for this practice in the following directory:
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

D:\Labs\eclipse\Solutions\Persistence\

Solutions for Practice 9-2

Compare your responses with the following answers:


1. False: The Java Persistence API requires an application server.
2. The fully qualified annotation used by classes to be marked as Entity classes is
s a
javax.persistence.Entity.
) h a
c o m
3. Entity classes often function as data transfer objects (DTOs) and implement the
java.io.Serializable interface. ฺ
ail ideฺ
m
g Gu
4. False for JPA 2.0, True for JPA 1.0: An entity class can have either field-based or
property-based access but not both.
o @
8 ent
s
do Stud
5. The @PersistenceContext annotation is used to have an EntityManager injected in a
managed component. a r
( a nc this
6. Every entity class must have a property or field that is annotated as the primary key.
o s o instanceu sebecomes detached.
a rd e to
7. When the transaction ends, the entity

i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: The Java Persistence API


Page 9 of 10
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: The Java Persistence API


Page 10 of 10
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
@
8 ent 10:
Practices ofor Lesson
s
do Studa Transaction
Implementing
a r
( a nc this
Policy
o s o use
a rd e toChapter 10
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Implementing a Transaction Policy


Page 1 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practices for Lesson 10: Overview

Practices Overview
In these practices, you:
• Determine when rollbacks occur in specific scenarios
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Use the Java Persistence API versioning features to control optimistic locking

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Implementing a Transaction Policy


Page 2 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 10-1: Determining When Rollbacks Occur

Overview

In this practice, you become familiar with the effect of transaction attributes on the handling of
transaction rollback when failures occur in various parts of an application.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Tasks

In each of the following scenarios, you are shown a call stack. That is, you are shown a
sequence of nested method calls between servlets and EJB components. The indentation
shows which methods are called in a particular transaction scope. Here is an example:
methodA()
methodB()
s a
methodC()
) h a
c o m

ail ideฺ
In this example, methodA calls methodB and then calls methodC. The calls to methodB and
methodC are both in the same scope. m
g Gu
Each method call has been assigned a transaction attribute. The o @ n t call is always on
8first method
s
o API e
d calls. So, you can
u(JTA)
the Controller servlet, which does not use any Java Transaction
assume that when the first method call is made by c a r d S t
transaction is in effect at that point. ( a n the servlet
t h ison an EJB component, no
o s o use
Review the scenarios and answer the
a rd questions
e tothat follow.
Scenario 1 i d is C licens
Consider the scenario
i c olaof creating
b e a new customer record and sending a notification to the
lthat
customer by N
e email. Suppose
f e r a you have the following call stack:
r
Nod transaction
s
1.an
x - t r an Controller.addCustomer(...)
e
non
Al 3. Required
2. Customer cust = new Customer()
BankMgr.addCustomer(cust)
4. em.persist(cust)
5. RequiresNew DBLogBean.writeStatusToLog()
6. NotSupported BankMgr.sendNotificationMessage()

Answer the following questions about this scenario:


1. Which methods get rolled back if a system exception is thrown from the method on line 5,
writeStatusToLog?
2. Which methods get rolled back if a system exception is thrown from the method on line 6,
sendNotificationMethod?
3. If the transaction attribute for the method on line 6 were Required rather than
NotSupported, which methods would be rolled back if the method on line 6 failed?

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Implementing a Transaction Policy


Page 3 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Scenario 2

Consider the scenario of transferring money between two customer accounts. Suppose that you
have the following call stack:
1.No transaction Controller.transferMoney()
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

2.Required BankMgr.transferMoney()
3. Customer cust1 = em.find(Customer.class, id1)
4. Customer cust2 = em.find(Customer.class, id2)
5. cust1.setBalance()
6. cust2.setBalance()
1. Which methods would be rolled back if the method started on line 2 threw a system
exception after running lines 3, 4, 5, and 6 all successfully?
2. Which methods would be rolled back if the method on line 2 threw a BankException after
running lines 3, 4, 5, and 6 all completed successfully? s a
) h a
3. Which lines would be rolled back if a call was made between lines 5 and 6 to
c o m
setRollbackOnly? ฺ
ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Implementing a Transaction Policy


Page 4 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 10-2: Using the Versioning Features of the Persistence API to


Control Optimistic Locking

Overview
In this practice, you modify the BrokerTool application to use versioning.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Prerequisites
• The application server and the Java DB database are installed, and the application
server is running.
• You have completed the previous BrokerTool practice.

Tasks
1. Demonstrate lost updates in the BrokerTool application.
a. Deploy the BrokerTool web application if it is not deployed currently.
s a
b. Launch two web browsers (referred to as Browser A and Browser B). ) h a
c. o m
In both Browsers A and B, launch the BrokerTool application using the URL
c
http://localhost:8080/BrokerTool/.

ail ideฺ
m
g Gu
d. In both Browsers A and B, retrieve the same customer’s details.
o @
8 ent
s
e. In Browser A, change the customer’s name or address and click the update button.
do Stud
r
f. Browser B does not know that the customer being displayed has been changed. In
a
( a nc this
Browser B, change the name or address to something other than what was entered in

o s o use
Browser A, and click the update button. The changes made in Browser B overwrite
rd e to
those made in Browser A. This is called a lost update.
a
is C licens
2. Modify the StockMarket Database to support versioning.
i d
a. Start the Java DB database server if it is not already started.
i c ola ble
b. Connect to the “StockMarket” database using the StockMarket connection.
r e N fera
c. Re-create the database tables and populate them by executing
a n d rans
VersioningStockMarket.sql provided in the
x -t
Ale non D:\Labs\eclipse\resources\brokertool directory.
• Click File > Open File.
• Select the VersioningStockMarket.sql file and click Open.
• In the Connection Profile, select StockMarket for the Name from the drop-down
list.
• Right-click in the Connection Profile window and select Execute All. You should
see the list of commands running in a status window in the lower right.
d. View the data stored in the CUSTOMER,STOCK, and SHARES tables.
e. Open each table and you will see a new column, Version.
Note: You may need to refresh the data to see the changes. Right-click the USER schema
and select Refresh.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Implementing a Transaction Policy


Page 5 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

3. Update the entity classes in the trader package to support versioning.


a. Modify Customer.java, CustomerShare.java, and Stock.java to support
versioning by adding the following code to each class:
@Version
@Column(name = "VERSION")
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

private int version = 1;

public int getVersion() {


return version;
}
b. Add any required import statements.
c. Add a new multi-arg constructor in each entity class to receive all initialization data and
an additional version value. An example constructor for Customer is provided as a
follows:
h a s
m )
public Customer(String id, String name, String addr, int
ฺ c o
ail ideฺ
version){
this(id, name, addr); m
g Gu
this.version = version;
o @
8 ent
} s
do Stud
a r
4. Add a Hidden Version Form Input Field to the
( a ncCustomerDetails
t h is Servlet
The steps listed below assume you are using
s s e
o theuCustomerDetails servlet. If you preformed
the optional CustomerDetails.jsp o
rd lab eplease
to modify the steps as needed.
a
C fornuse s in the form. It should be a local variable with a
a. Create a version
i d isvariable
c e
li the Customer object stored in the request scope. This can
value that isla obtained from
c o l e
be done
e N f e ab way the name, ID, and address data is retrieved.
i in the rsame
b.drModify thesCustomerDetails servlet in the BrokerTool project to support a new
a n t
hiddenr n element. Insert the hidden form element after the form element and before
aform
e x -
Al nonthe table. Use the following code:
out.println("<input type='hidden' name='version' value='" +
version + "'/>");
5. Modify CustomerController to use the version value.
a. After retrieving all other submitted form data add the following code to read the value of
the hidden version form input:
int version = 1;
if(request.getParameter("version") != null) {
version =
Integer.parseInt(request.getParameter("version"));
}
b. Find any calls to new Customer in the CustomerController and modify them to
pass the version value to the constructor created in Task 3, Step c.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Implementing a Transaction Policy


Page 6 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

6. Modify BrokerModelImpl to use versioning.


a. In BrokerModelImpl any methods that invoke merge operations to update entity
data can possibly cause an OptimisticLockException.
OptimisticLockException is a subclass of RuntimeException and should be
caught to avoid invalidation the BrokerModelImpl session bean in the web tier.
b. Handle all merge calls in a fashion similar to the following example:
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

try {
em.merge(cust);
} catch(OptimisticLockException ole) {
throw new BrokerException("Record for " + cust.getId() + "
has been modified since retrieval");
}
c. Add any required import statements.
s a
7. Deploy the application and test it.
) h a
a. Save any modified files. If “Build Automatically” is not enabled, then build the m
BrokerTool project manually. ฺ c o
b. Deploy the BrokerTool application. m ail ideฺ
@ g Gu
1) In the Project Explorer window, select BrokerTool and
o 8 efrom
then n t the Run menu,
select Run as > Run on Server. s
do Stud
a r
2) In the “Run on Server” dialog box, click
button and select the “GlassFish(a
nc the t“Choose
h is entry
3.1 at localhost”
an existing server” option
under the localhost node.
3) Click the Finish button. o s o u s e
a r d t o
c. Launch two web browsers
i s C (referred
e n se to as Browser A and Browser B).
d. In both browsers
o l aid A andl e lB,iclaunch the BrokerTool application using the URL
icBrowserraAband B, retrieve the same customers details.
http://localhost:8080/BrokerTool/.
N
e. Ineboth
d rIn Browsern s fe
x a n
f.
t r a A, change the customer’s name or address and click the Update button.
e -
Al g.nonBrowser B does not know that the customer being displayed has been changed. In
Browser B, change the name or address to something other then what was input in
Browser A, and click the Update button. The changes made in Browser B are no longer
accepted because the customer’s data has been modified by another client.
A production quality application would probably not store the version value in a hidden form
field because a knowledgeable user could forge any version value. A better method would
be to store the information in the web server using a HttpSession.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Implementing a Transaction Policy


Page 7 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice Solutions

Use the following information to verify your answers to the scenario questions.

Solution for Practice 10-1


Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Scenario 1
Consider the scenario of creating a new customer record and sending a notification to the
customer by email. Suppose that you have the following call stack:
1. No transaction Controller.addCustomer(...)
2. Customer cust = new Customer()
3. Required BankMgr.addCustomer(cust)
4. em.persist(cust)
5. RequiresNew DBLogBean.writeStatusToLog()
s a
6. NotSupported BankMgr.sendNotificationMessage()
) h a
c o m

ail ideฺ
1. Which methods get rolled back if a system exception is thrown from the method on line 5,
writeStatusToLog? m
g Gu
Only the method on line 5.
o @
8 ent
The transaction that was initiated on entry to the method
d s
ofails, its line
on
u d3 is suspended on entry
to the method on line 5. When the method on line r 5 t
a is S transaction is rolled back.
own
The original transaction is then resumed a n c Theth
should catch an EJBException, and o ( intact.
might choosee to
BankMgr.addCustomer method
s roll itself back if the logic dictates.
d o s of the RequiresNew
u
This example demonstrates the r use t o attribute to isolate non-critical
code from a transaction.Ca s e
2. Which methods get i d is backlicifeansystem
o l a rolled
l e
exception is thrown from method on line 6,
ic rab
sendNotificationMethod
N
?

n d re nsfe
None.
xa Ifsuspended.a any transaction in effect on entry to the method on line 6, it would be
theretrwas
-
l e n
A no Consequently, anything that happens in the method on line 6 is isolated from
the outer transaction. Like RequiresNew, the NotSupported attribute is often used to
isolate non-critical logic from a critical transaction.
3. If the transaction attribute for line 6 were Required, rather than NotSupported, which
methods would be rolled back if the method on line 6 failed?
Only line 6.
Lines 3 and 6 are called by the method Controller.addCustomer. Because
Controller.addCustomer has no transaction, lines 3 and 6 must be different transactions.
As a result, a failure in the method on line 6 cannot affect line 3. Because line 5 is called
from line 3, it is immune to a failure in line 6.

Scenario 2
Consider the scenario of transferring money between two customer accounts. Suppose that you
have the following call stack:
1.No transaction Controller.transferMoney()
2.Required BankMgr.transferMoney()
3. Customer cust1 = em.find(Customer.class, id1)
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Implementing a Transaction Policy


Page 8 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

4. Customer cust2 = em.find(Customer.class, id2)


5. cust1.setBalance()
6. cust2.setBalance()
1. Which methods would be rolled back if the method started on line 2 threw a system
exception after running lines 3, 4, 5, and 6 all successfully?
Lines 2-6.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

The transaction does not commit until the method on line 2 exits successfully. If a method
throws a system exception, the container rolls back the transaction rather than committing
it.
2. Which methods would be rolled back if the method on line 2 threw a BankException after
running lines 3, 4, 5, and 6 all completed successfully?
None.
BankException is an application exception. Throwing it does not cause the container to roll
back any transaction. s a
3. Which lines would be rolled back if a call was made between lines 5 and 6 to ) h a
setRollbackOnly? c o m

ail ideฺ
Lines 2-6. m
gto do itsGwork,
u even
Moreover, when setRollbackOnly is called, line 6 then proceeds @
o2 8completes, t
nthe container
though everything it does is rolled back later. When line
o s d e
d rollsSback
examines the rollbackOnly flag and, because it isrset,
a tu the transaction. The
c
an done
setRollbackOnly method not only affects work
also affects the entire transaction. o ( e thupisuntil the point it was called, but it
r d os to us
Solution for Practice 10-2Ca
i s e n se
l id forliPractice
asolutions c
You can find sampleo
ic rab l e 10-2 in the following directory:
N
D:\Labs\eclipse\solutions\Transactions\
re nsfe
n d
l e xa n-tra
A no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Implementing a Transaction Policy


Page 9 of 10
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Implementing a Transaction Policy


Page 10 of 10
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
Practices ofor@
8 ent 11:
Lesson
s
Developing
a r tud EE
do SJava
( a nc this Using
Applications
o s u se
o Messaging
a rd e to
i d is C licens Chapter 11
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Developing Java EE Applications Using Messaging


Page 1 of 2
Pontifícia Universidade Católica do Rio Grande do Sul

Practices for Lesson 11: Overview

Practices Overview
There are no practices associated with this lesson.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Developing Java EE Applications Using Messaging


Page 2 of 2
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
@
8 ent 12:
Practices ofor Lesson
s
Developing
a r tud
do SMessage-Driven
( a nc this
Beans
o s o use
a rd e toChapter 12
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Developing Message-Driven Beans


Page 1 of 6
Pontifícia Universidade Católica do Rio Grande do Sul

Practices for Lesson 12: Overview

Practices Overview

In these practices, you write a message-driven bean that accepts messages that list the current
price of stocks in the BrokerTool application. The contents of the message specify the stock
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

ID and the current price of the stock. This simulates the way in which an EJB application could
use messaging to interact with, for example, a legacy system. The message-driven bean
interacts with the BrokerModelImpl session bean to carry out the actual update operation.
The BrokerModelImpl bean, in turn, interacts with the Stock entity class to modify the
database.
To test the message-driven bean, you need a source of messages. Consequently, part of this
exercise is to deploy a JMS message producer that can send messages in the appropriate
format.
s a
You also need to configure a new queue and queue connection factory in the application
) a
hserver.
The message-driven bean is then assigned to the JNDI name of the queue. o m
a ilฺc eฺ
@ gm Guid
s o 8 ent
a r do Stud
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Developing Message-Driven Beans


Page 2 of 6
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 12-1: Implementing the Message-Driven Bean

Overview
In this practice, you create a message-driven bean in the BrokerTool application and test it.
Prerequisites
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• The application server and the Java DB database are installed, and the application
server is running.
• You have completed the previous BrokerTool practice.

Tasks
1. Create the managed resources. A JMS queue and connection factory must be created in
the application server. To create them, complete the following steps.
a. Open the GlassFish Admin Console at http://localhost:4848.
b. Under Common Tasks on the left, expand Resources. s a
) h a
c. Expand JMS Resources.
c o m
d. Click Destination Resources. ฺ
ail ideฺ
e. m
Click New to create a JMS Destination and enter the following information:
g Gu
• JNDI Name: jms/UpdateStock
o @
8 ent
s
• Physical Destination Name: UpdateStockdo
a r S tud
• Resource Type: javax.jms.Queue
( a nc this
f. Click OK.
o s o use
2. Complete the following steps to
a rdcreateea JMS
to connection factory:
i d i s C icens
a. Click Connection Factories.
b. Click New to
o l Factory and enter the following information:
lacreate laeJMS
• N c b
i Name:rajms/UpdateStockFactory
Pool
e
dr• rResourcef e
s Type: javax.jms.QueueConnectionFactory
a n a n
-t OK.
x c. nClick
Ale3. Copy
o
n the StockMessageProducerBean EJB.
a. The JMS message producer is provided to you in the form of a scheduled no-interface
local session EJB.
b. Copy the StockMessageProducerBean.java file from
D:\Labs\eclipsse\resources\brokertool.
c. Paste the StockMessageProducerBean.java file into the trader package of the
BrokerTool project.
View the source code for the StockMessageProducerBean EJB. The EJB tries to
update the ORCL stock price once per minute.
4. Create a new message-driven bean in the BrokerTool project.
a. Right-click the BrokerTool project, select New, and then select Other.
b. In the “Select a Wizard” dialog box, select the EJB category and Message-Driven Bean
(EJB 3.x) as the file type.
c. Click Next.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Developing Message-Driven Beans


Page 3 of 6
Pontifícia Universidade Católica do Rio Grande do Sul

d. Enter the following information in the “Create a EJB (3.x) Message Driven Bean” dialog
box.
• Project: BrokerTool
• Source Folder: \BrokerTool\src
• Java Package: trader
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Class Name: UpdateStockBean


• Destination Name: jms/UpdateStock
• JMS check box: selected
• Destination Type: queue
e. Click Finish.
f. Modify the @MessageDriven annotation to look like this:
@MessageDriven(mappedName = "jms/UpdateStock", activationConfig
= {
s a
@ActivationConfigProperty(propertyName = ) h a
"acknowledgeMode", propertyValue = "Auto-acknowledge"),
c o m
@ActivationConfigProperty(propertyName = ฺ
ail ideฺ
"destinationType", propertyValue = "javax.jms.Queue") m
g Gu
})
o @
8 ent
s
g. Add an annotated EJB reference variable for the
a r S tud
doBrokerModelImpl session bean to
c s
(an se thi
the UpdateStockBean.
@EJB private BrokerModel omodel;
h. The onMessage methodrshould d os receive
t o ua javax.jms.TextMessage object
a
containing a messageCin the format se of ORCL,200.75. Parse this message using the
i s
d split(",") e n
String class imethod
o l a l e lic and the Double.parseDouble("") method.
i. Use the
N icmodelrareference
b obtained in Step g to retrieve and update the current stock
d r e nsfe
price. Catch any exceptions that occur and print their stack trace. Do not throw any

e x an exception
- t r a from onMessage because the container will try to deliver the message
Al non
again.
5. Deploy the application and test it.
a. Save any modified files. If “Build Automatically” is not enabled, then build the
BrokerTool web application manually. Select BrokerTool project, click Run menu,
and select the Run as >Run on Server option.
b. View the stock prices by entering the following URL in a browser:
http://localhost:8080/BrokerTool/Stocks.xhtml
c. You should see the current stock prices. Wait more than one minute and refresh the
page. You should see a change in the stock price.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Developing Message-Driven Beans


Page 4 of 6
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 12-2: Describing Message-Driven Beans

Overview
In this practice, you answer check your understanding of message-driven beans.

Tasks
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

1. Answer the question or fill in the blanks of the following sentences with the missing word or
words:
a. Message-driven beans are: (Choose one of the following)
1) Synchronous message consumers
2) Asynchronous message consumers
b. The _________________ method in a JMS MDB is called by the server when a
message arrives.
c. To send a message to a queue, a JMS client would need to obtain a
s a
____________________ and a ____________________ using either JNDI or
) h a
dependence injection.
c o m

ail ideฺ
d. A message-driven bean must have an onMessage method. (True or false?)
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Developing Message-Driven Beans


Page 5 of 6
Pontifícia Universidade Católica do Rio Grande do Sul

Exercise Solutions
Use the following solutions to check your answers to the exercises.

Solutions for Practice 12-1


You can find solutions for this practice in the following directory:
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

D:\Labs\eclipse\solutions\MessageDriven.

Solution for Practice 12-2


Compare your responses with the following answers:
a. Message-driven beans are:
• Asynchronous message consumers
b. The onMessage(Message) method in a JMS MDB is called by the server when a
message arrives.
c. To send a message to a queue, a JMS client would need to obtain s a
javax.jms.QueueConnectionFactory and a javax.jms.Queue using either
) h a
JNDI or dependence injection.
c o m
d. False (Only JMS MDBs must have an onMessage method.) ฺ
ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Developing Message-Driven Beans


Page 6 of 6
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
Practices ofor @
8 ent 13: Web
Lesson
s
Service
a r doModelS tud
( nc
Chapter 13th
a is
so us e
r d o to
a e
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Web Service Model


Page 1 of 2
Pontifícia Universidade Católica do Rio Grande do Sul

Practices for Lesson 13: Overview

Practices Overview
There are no practices associated with this lesson.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Web Service Model


Page 2 of 2
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
Practices ofor@
8 ent 14:
Lesson
s
do StudJava EE Web
Implementing
a r
( a nc thiswith JAX-RS & JAX-
Services
o s o WS u se
a rd e to
i d is C licens Chapter 14
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Implementing Java EE Web Services with JAX-RS & JAX-WS
Page 1 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practices for Lesson 14: Overview

Practices Overview
In these practices, you create a JAX-WS web service, a JAX-RS web service, and a JAX-WS
web service client to check the price of a stock. There are two methods for making a web
service with JAX-WS: starting with a WSDL file or starting with a Java program. You create a
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

small Java class that the application server turns into a web service.
When the application server has created a web service from your Java code, a WSDL file will be
available on the server. You use this WSDL file to generate client-side Java code for use in a
test application.
Practices 14-1 and 14-2 focus on JAX-WS. Practice 14-3 implements the same functionality as
Practice 14-1 but uses JAX-RS. There is no JAX-RS client exercise because JAX-RS does not
include a client API.
s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Implementing Java EE Web Services with JAX-RS & JAX-WS
Page 2 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 14-1: Creating a JAX-WS Web Service

Overview

In this practice, you create a class called StockPrice that functions as a web service. The
StockPrice web service allows clients to retrieve the price of any stock in the BrokerTool
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

application.

Prerequisites
• The application server and the Java DB database are installed, and the application
server is running.
• You have completed the previous BrokerTool practice.

Tasks
1. Create the StockPrice web service in the BrokerTool project. s a
a. Right-click the BrokerTool project. ) h a
c o m
b. Select New and then select Class. ฺ
ail ideฺ
c. m
In the “New Class Wizard” dialog box, enter the following information:
g Gu
• Source Folder: BrokerTool/src
o @
8 ent
• Package: trader.web s
do Stud
a r
• Name: StockPrice
( a nc this
• Accept the defaults for the remaining
o s u se
o options.
d. Click Finish.
a rd e to
e. Add the getStockPrice
i d is C licmethod
e ns to the StockPrice class:
• Add a method
i c olaString with the following signature:
b legetStockPrice(String symbol) { .. }
N
public
er a
•re Add the
d s f to the StockPrice class. Add the @WebMethod annotation
a n t r a n @WebService

l e x n -to the getStockPrice(...) method.


A no• Add an annotated EJB reference variable for the BrokerModelImpl session bean
to the StockPrice class.
@EJB private BrokerModel model;
• Add any needed import statements.
• Use the BrokerModelImpl session bean to retrieve the current price of the
requested stock and return its value as a String.
• Wrap the code for the getStockPrice method in a try/catch block. Do not throw
an exception from the getStockPrice(...) method. Complex data types, such
as a BrokerException, returned or thrown from a web service method require
JAXB bindings. Return the String “Price unavailable” when an
Exception occurs.
2. Test the StockPrice web service.
a. View the XML output generated in WSDL by using this URL:
http://localhost:8080/BrokerTool/StockPriceService?WSDL.
b. Test the StockPrice web service by using the URL:
http://localhost:8080/BrokerTool/StockPriceService?Test
Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Implementing Java EE Web Services with JAX-RS & JAX-WS
Page 3 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 14-2: Creating a Web Service Client

Overview
In this practice, you create a standard command-line Java application that functions as a JAX-
WS client. This is a small application designed to test the StockPrice web service.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Prerequisites
• The application server and the Java DB database are installed, and the application
server is running.
• You have completed the previous BrokerTool practice.

Tasks
1. Create a web service client project.
a. Create a new Java Application Project named the WebServiceTester project by a
completing the following steps:
h a s
1) Select File and then select New > Project. m )
ฺ c o
2) Choose Java > Java Project.
m ail ideฺ
3) Click the Next button.
@ g Gu
s o 8 ent
4) In the “Create a Java Project“ dialog box, enter the following information.
o Project Name: WebServiceTester
a r do Stud
( a nc this
o Location: D:\Labs\eclipse\projects\WebServiceTester
o JRE: Use default JRE
o s o use
rd separate
o Project layout:aCreate
e to folders for sources and class files
is Ctolicworking
o Add projects
i d e ns sets (deselected)
5) Clicko
c laNext button.
the le
6) N
i
Accept the r a b
default values in the “Java Settings” dialog box and click Finish.
r e s f e
x a nd 7) trIfaandialog box asks if you want to open the Java Perspective, click Yes.
-developing a simple JAX-WS web service client, you use helper classes to perform
Ale2. When
non
all low-level SOAP and HTTP work. A JAX-WS reference implementation (for example,
Metro) can generate these helper classes after analyzing a WSDL, using the wsimport
tool. To generate these classes, complete the following steps:
a. Open Windows Explorer and browse to the
D:\Labs\eclipse\resources\brokertool folder. Right-click the build.xml file
and select copy.
b. In the Project Explorer window, right-click the WebServiceTester project and select
paste. Verify if the build.xml file has been copied to the project.
c. Open the build.xml file and examine the wsimport-bin target. Ensure that the
value of the wsdl property matches the following URL:
http://localhost:8080/BrokerTool/StockPriceService?WSDL
d. Save the file if you make any changes in it.
e. In the Projects Explorer window, right-click build.xml and select Run As > Ant Build.
You will see messages on the console window indicating successful generation of the
classes.
f. In the Project Explorer window, right-click WebServiceTester and select refresh.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Implementing Java EE Web Services with JAX-RS & JAX-WS
Page 4 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

g. Notice that a trader package node has appeared on the WebServiceTester > src
node. Expand the trader package and view the generated files. These class files are
used to communicate with the remote web service.
3. Create a new class.
a. In the Project Explorer window, select WebServiceTester and right-click. Select New
> Class.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

b. Provide the following information in the “New Java Class” dialog box:
• Source Folder: WebServiceTester/src
• Package: webservicetester
• Name: Main
• Select the “public static void main (String[] args)” check box.
• Click Finish.
4. Code the web service client application. Add the following to the main method in
s a
webservicetester.Main:
) h a
StockPriceService service = new StockPriceService();
c o m
StockPrice port = service.getStockPricePort(); ฺ
ail ideฺ
System.out.println("Stock price is: " + m
g Gu
port.getStockPrice("ORCL"));
o @
8 ent
s
5. Add an import statement: import trader.*; rdo
a S tud
( a nc tRun
6. Build and run the WebServiceTester application. histhe main method of the Main
s o us
class. Right-click the WebServiceTester project e
and click Run as > Java Application.
r d o
Because it is a standard command-line
t o
application, there is no need to deploy it. Correct
any errors. a
C nse
i s e stock price on an Eclipse output tab.
d theliccurrent
The application should idisplay
l a
N ico rable
n d re nsfe
l e xa n-tra
A no

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Implementing Java EE Web Services with JAX-RS & JAX-WS
Page 5 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 14-3: Create a JAX-RS Web Service

Overview

In this practice, you create a class called StockResource that functions as a web service. The
StockResource web service allows clients to retrieve the price of any stock in the
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

BrokerTool application.

Prerequisites
• The application server and the Java DB database are installed, and the application
server is running.
• You have completed the previous BrokerTool exercise.

Tasks
1. Remove the existing BrokerTool deployment from the server. s a
a. On the Servers tab of the Java EE Perspective, expand GlassFish 3.1 at localhost. ) h a
b. Right-click BrokerTool and click Remove. c o m

ail ideฺ
2. Edit the Project Facet. m
@ g Gu
a. In the Project window, select and right-click BrokerTool. Click the Properties option
from the shortcut menu. s o 8 ent
a r do Stud
b. In the “Properties for BrokerTool ” dialog box, click Project Facets on the left panel. On
( a nc this
the right panel, select the “JAX-RS (REST web services)” check box.
s o use
c. Click the “Further Configuration Required” link. In the “JAX-RS Capabilities” dialog box,
o
rd e to
examine the default entries. Ensure that the “Update Deployment Descriptor” check
a
i d is C licens
box is selected. Click the OK button.
d. Click OK to close the “Properties for BrokerTool” dialog box.
3. i c ola ble
Examine the deployment descriptor file.
r e N fera
a. In the Project Explorer window, expand BrokerTool > Web Content > WEB-INF
a n d rans
and click web.xml to open it on the editor window.
x -t
Ale non b. Examine the servlet entry for JAX-RS. Observe the URL pattern for the servlet under
the servlet-mapping element.
c. Close web.xml.
4. Create the StockResource web service.
a. Right-click the BrokerTool project.
b. Select New > RESTful Web Services from Patterns.
c. In the “RESTful Web Service from Pattern” dialog box, enter the following information:
• Project: BrokerTool
• Source Folder: \BrokerTool\src
• Java Package: trader.web
• Class name: StockResource
• Superclass: (blank)

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Implementing Java EE Web Services with JAX-RS & JAX-WS
Page 6 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

• Pattern Type: Simple Root Resource


• Path: stocks/{symbol}
• MIME Type: text/plain
• Representation Class: java.lang.String
d. Click Finish.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

5. In the Projects Explorer window, expand BrokerTool > src >trader.web. Click
StockResource.java to open it in the editor window.
a. This web service allows only the reading of a stock price. Remove the putText
method from the StockResource class.
e. Implement the getStockPrice method.
f. Add or remove import statements as needed.
g. Rename the getText method to getStockPrice. While the name of the method
does not matter to a RESTful web service client, it is a good practice.
s a
h. In the getStockPrice method use JNDI to obtain a reference variable for the
) h a
BrokerModelImpl session bean stub.
c o m
javax.naming.Context ctx = new InitialContext(); ฺ
ail ideฺ
BrokerModel model = m
g Gu
o @
8 ent
(BrokerModel)ctx.lookup("java:global/BrokerTool/BrokerModelImpl"
);
d o s ud
a r S t
i. Use the BrokerModelImpl session bean
requested stock and return its value (asa na cString.
t h is the current price of the
to retrieve

o s o umethodse in a try/catch block. Do not throw


ard se to
j. Wrap the code for the getStockPrice
an exception from theC getStockPrice(...) method. Return the String Price
unavailable when s
idian Exception n
ce occurs.
l a l i
6. Build and run
i a b le application.
cothe BrokerTool
Save e
r N
any modified
f erfiles.Run
Deploy the BrokerTool application to GlassFish. Right-click
d
n tran
BrokerTool ands select As > Run on Server.
x a - StockResource web service.
Ale7. Test
non
the
View the text output of the RESTful web service by pointing a web browser at:
http://localhost:8080/BrokerTool/jaxrs/stocks/ORCL.
For more complex RESTful web services that use methods such as PUT and DELETE,
there are many ways to test the service. Most IDEs provide some type of test client, and
RESTful web browser plugins are available.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Implementing Java EE Web Services with JAX-RS & JAX-WS
Page 7 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 14-4: Describing Web Services

Overview
In this practice, you check your understanding of Java web services.

Tasks
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

1. In the following sentences, fill in each blank with the missing word (or words):
1. The portable file used to define a web service interface is known as a ____________.
2. ___________ is the standard web service XML dialog that is typically transferred
through HTTP.
3. A ________ and ____________ EJB can be a web service endpoint.
4. The only other Java web service endpoint besides an EJB is a _____________
endpoint.
5. In JAX-WS both endpoint types use the __________________ class-level annotation
s a
to indicate a web service.
) h a
c o m
6. __________________ is the Java API to create web services that do not use SOAP.

ail ideฺ
7. Complex objects are return values of a web service method that requires the use of
_____________. m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Implementing Java EE Web Services with JAX-RS & JAX-WS
Page 8 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice Solutions

Solutions for Practices 14-1, 14-2, and 14-3


You can find example solutions for these practices in the following directories:
• Practices 14-1 and Practice 14-2: D:\Labs\eclipse\solutions\WebServices
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

• Practice 14-3: D:\Labs\eclipse\solutions\WebServices\exercise3

Solution for Practice 14-4: Describing Java Web Services


Compare your responses with the following answers:
1. The portable file used to define a web service interface is known as a WSDL.
2. SOAP is the standard web service XML dialog that is typically transferred through
HTTP.
3. A Stateless Session and Singleton Session EJB can be a web service endpoint. a
4. The only other Java web service endpoint besides an EJB is a Servlet|Web|POJO
h a s
endpoint. m )
ฺ c o
5.
ail ideฺ
In JAX-WS, both endpoint types use the @javax.jws.WebService class-level
annotation to indicate a web service. m
@ g Gu
6.
8 ent
JAX-RS is the Java API to create web services that do not use SOAP.
s o
7.
JAXB. a r do Stud
Complex objects are return values of a web service method that requires the use of

( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Implementing Java EE Web Services with JAX-RS & JAX-WS
Page 9 of 10
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Implementing Java EE Web Services with JAX-RS & JAX-WS
Page 10 of 10
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates. Pontifícia Universidade Católica do Rio Grande do Sul

s a
) h a
c o m

ail ideฺ
m
g Gu
@
8 ent 15:
Practices ofor Lesson
s
do Studa Security
Implementing
a r
( a nc this
Policy
o s o use
a rd e toChapter 15
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Implementing a Security Policy


Page 1 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practices for Lesson 15: Overview

Practices Overview

At present, your application has no access control, so it is completely open to all users. In this
lab, you implement an end-to-end security policy. That is, you implement a policy that
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

encompasses the business logic and all of its clients, including the PortfolioController
servlet, any JSP components, and standalone clients. This policy is defined in terms of two Java
EE roles, admin and customer:
Members of the admin role have complete access to all of the components of the application.
They can, therefore, view the portfolio of any customer.
Members of the customer role can only view their own portfolio details.

For ease of testing, you implement the security policy step-by-step, testing at each stage. The
s a
first step is to complete the PortfolioController servlet. At present, when the user clicks
) h a
the Show Portfolio link, it results in a call to getAllCustomerShares on the
c o m
BrokerModelImpl EJB component. The getAllCustomerShares method should use the ฺ
ail ideฺ
EJB security API to determine the current user. m
g Gu
@
8 soenthatt only authenticated
The next stage is to apply a security constraint to the web application,
o
o
users can invoke the application. Finally, you apply security
d s d to the methods of the
constraints
u
r t
S than can be
BrokerModelImpl EJB component, to give finer control
a n ca hover i s access
accomplished at the web tier.
o ( se t
s
a rdo e to u
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Implementing a Security Policy


Page 2 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 15-1: Using the EJB Security API to Get the User's
Identity in an EJB Component

Overview

In this practice, you add security to the BrokerModelImpl session bean. The
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

getAllCustomerShares method returns an array of CustomerShares. The method is


modified to use the EJB security API to determine who is logged in. If no user is logged in, it
throws an exception.

Prerequisites
• The application server and the Java DB database are installed, and the application
server is running.
• You have completed the previous BrokerTool practice.
s a
Tasks ) h a
c o m
1. ฺ
Add security features to the getAllCustomerShares method in the BrokerModelImpl
class: ail ideฺ
m
g Gu
a. Add the following import statements:
o @
8 ent
import java.security.Principal; s
do Stud
a r
nc this
import javax.annotation.Resource;
import javax.ejb.SessionContext; ( a
oclass: use
b. Declare a session context foro s
the
a rd e to ctx;
is C licens method to get a java.security.Principal
@Resource private SessionContext
i d
c. Use the getCallerPrincipal
object for
i c othelacurrent
b lelogged-in user. The getCallerPrincipal method is defined
on the
e N f e r a
SessionContext object that is injected by the container when it initializes the
r
nd EJB n s
component. In other words, make the call:
x a - t r a
Ale d.nonCall the getName method on the Principal object to get a String representation of
java.security.Principal p = context.getCallerPrincipal();

the user ID of the logged-in user.


Principal principal = ctx.getCallerPrincipal();
String name = principal.getName();
e. If the user ID is guest or anonymous (in any mixture of uppercase or lowercase) then
no user is logged in. In this case, throw a BrokerException with the text Not logged
in.
2. Deploy and test the session bean.
a. Save any modified files. If Build Automatically is not enabled, build the BrokerTool
web application manually.
b. Test the session bean by pointing your web browser at:
http://localhost:8080/BrokerTool/AllCustomers
c. Follow the link called View on the Portfolio column.
You should see the error message indicating that you are not logged in.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Implementing a Security Policy


Page 3 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 15-2: Creating Roles, Users, Groups, and a Web-Tier Security


Policy

Overview

So far, you have coded the application to the extent that it is able to determine the details of the
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

current user. However, you do not yet have a method to log in, or any user credentials against
which to verify a login attempt.
In this practice, you define the customer and admin security roles at the application level and
create two user groups in the application server. You then map the roles onto the user groups.
Next, you apply security constraints to the URL patterns that the web browser invokes. This has
two effects. First, it restricts access to those URLs to certain users. Second, it forces the web
server to prompt the user to authenticate.

Prerequisites s a
• The application server and the Java DB database are installed, and the application )h a
server is running. o m
• You have completed the previous BrokerTool practice. a ilฺc eฺ
@ gm Guid
Tasks
s o 8 ent
1. Create roles in the application. Make changes to the
a r d o t ud
BrokerModelImpl
S
class to add roles
to the application.
a n c his
a. Add an import statement for the DeclareRoles
o ( e t annotation.
s s
rdo e to u
import javax.annotation.security.DeclareRoles;
a
d
available user irolesis forCthis
b. Add a class-level annotation
li c e ns @DeclareRoles({"admin","customer"})
in BrokerModelImpl.
class:
The annotation defines the two

c o lagroupslein the
2. Create users
N i and
r a b application server. You add two users to a security realm.
e in tonthe
a. rLog
d s feGlassFish administration console using the default user name and
x n
a Admin
password
t r a (admin/adminadmin or admin/). Use the following URL to open the
e -
Al non
Console:
http://localhost:4848
b. On the left panel, under “Common Tasks” select Configurations > default-config >
Security > Realms > file.
c. Click the Manage Users button.
d. Click the new button to add the two users, 111-11-1111 and 123-45-6789. Click OK to
complete a user creation. If these users no longer exist in your application, you can use
alternative users. Put user 111-11-1111 in the level1 and level2 groups, and put user
123-45-6789 in the level1 group. Use the information in the following table to configure
these users.
User ID Password Group List
111-11-1111 Password level1,level2
123-45-6789 Password level1
Note: There is no space after the comma in the Group List.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Implementing a Security Policy


Page 4 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

3. Map roles to groups.


a. Edit the sun-web.xml deployment descriptor of the BrokerTool project. On the
Project Explorer window, expand BrokerTool > Web Content > WEB-INF and click
sun-web.xml to open it on the editor window.
b. Add the mapping inside the sun-web-app element after the context-root tags.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

<security-role-mapping>
<role-name>admin</role-name>
<group-name>level2</group-name>
</security-role-mapping>
<security-role-mapping>
<role-name>customer</role-name>
<group-name>level1</group-name>
</security-role-mapping>
s a
c. At the end of this task, the Java EE security role, customer, is mapped onto the
) h a
level1 server group, and the admin role is mapped onto the level2 group.
c o m
4. Create a security constraint. ฺ
ail ideฺ
m
g Gu
a. Complete the following steps to create a security constraint in the web module, so the
@
8 ent
/PortfolioController URL is accessible only to the customer and admin roles:
o
s
do Stud
b. Add the @ServletSecurity annotation to the PortfolioController class
a r
( a nc this
located at trader.web package of BrokerTool.

{"admin","customer"})) o s o use
@ServletSecurity(@HttpConstraint(rolesAllowed =

a d to tthe
raccess o /PortfolioController URL to users in
e
is C liroles.
c. These annotations restrict s the required import statements.
d
the admin or customer
i c e nAdd
ola bdeployment
d. Edit thecweb.xml
i le descriptor, located at BrokerTool > WebContent > WEB-
INF N
e node in the
f e r a
Project.Explorer window.
r s
ne.d Addtraalogin-config
n element inside the web-app element right before the closing
e x a -
Al non
web-app tag:
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>file</realm-name>
</login-config>
f. This login configuration instructs the server to use basic authentication to authenticate
users. The realm is a group of users configured in the application server. Different
realms can be configured to retrieve users from files, databases, LDAP, password files,
etc.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Implementing a Security Policy


Page 5 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

5. Build and run the application.


a. Save any modified files. If Build Automatically is not enabled then build the
BrokerTool web application manually. Resolve any errors before you continue.
If you get compilation errors in the Customer, CustomerShare, and Stock classes,
which says that these classes are not added to the persistent unit, then complete the
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

following steps:
− Open persistence.xml in the code editor.
− In the “Managed Classes” section, add trader.Customer,
trader.CustomerShare, and trader.Stock classes.
− Save the persistence.xml file.
− Build the BrokerTool project and verify that the above mentioned compilation
error does not appear now.
b. Point your web browser at:
s a
http://localhost:8080/BrokerTool/AllCustomers
) h a
c. Attempt to view a customer’s portfolio. The CustomerController URL now has ac o m

ail ideฺ
security constraint, and if you have not yet logged in, you should be prompted to log in.
d. Enter the user ID and password for user 123-45-6789.
m
g Gu
o @
8 entcalling the
e. You should see the customer portfolio. Because you s are no longer
domethod udthe guest or anonymous
BrokerModelImpl.getAllCustomerShares
a r S tas
user, you can see the portfolio data. If this
( a nctest isthsuccessful,
is it shows that the web tier
s o us
has authenticated the user and propagated e
the user credentials to the EJB tier.
f. View other customer portfolios. o
rd is This o also succeed regardless of what user you
tshould
logged in as. This is not a
C ns
what e
required by the application’s security, because only
i s e
members of the
Members o l
of
atheidcustomer
l e lic role,
admin role should be able to view other customers' portfolios.
such as user 123-45-6789, should only be able to
viewN
ic raccounts.
their own a b You fix this in the next practice.
r e s f e
x a nd tran
-
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Implementing a Security Policy


Page 6 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 15-3: Creating an EJB Tier Security Policy

Overview

In Practice 1, you restricted access to the BrokerModelImpl.getAllCustomerShares


method programmatically, allowing only logged-in users to execute the method. In Exercise 2,
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

you protected the web page that shows the results of the
BrokerModelImpl.getAllCustomerShares method, thereby causing the calls to the
BrokerModelImpl.getAllCustomerShares to have role and principal credentials.
If other pages are restricted with different roles, then any of those pages could execute the
BrokerModelImpl.getAllCustomerShares method. In this exercise, you restrict all
unallowed access to the BrokerModelImpl.getAllCustomerShares method both
declaratively and programmatically.
This exercise contains the following sections that describe the tasks to restrict the use of the s a
BrokerModelImpl.getAllCustomerShares method to members of the admin or customer
) h a
role.
c o m

ail ideฺ
Prerequisites m
g and the uapplication
• The application server and the Java DB database are installed, @ t G
server is running.
o s o8 den
• You have completed the previous BrokerTool a rdpractice.
S tu
a n c his
( e t
Task
d o so us
1. Restrict BrokerModelImplamethods. r e to
a. Verify the class-level
i d is C c e nsof BrokerModelImpl to:
annotation
c o la le li
i athebadmin and customer roles are used in this EJB.
@DeclareRoles({"admin","customer"})
e N f e r
a n drImport
This
r
states
a n s that

l e x b.
n - t the @RolesAllowed annotation. Import
A no javax.annotation.security.RolesAllowed;
c. Add a method-level annotation to the BrokerModelImpl.getAllCustomerShares
method of:
@RolesAllowed({"admin","customer"})
This prohibits anyone not in the admin or customer role from calling the
getAllCustomerShares method.
2. Customize the BrokerModelImpl methods by Role. In the previous task, you declared
that only the admin and customer roles are allowed to call the getAllCustomerShares
method. A customer should not be allowed to view other customer shares. There is no way
to define this restriction declaratively; it must be done programmatically.
a. Comment out the code at the beginning of the getAllCustomerShares method that
deals with anonymous or guest users.
b. Modify that getAllCustomerShares method so that a BrokerException is thrown
if one of the conditions does not pass:
c. The caller is not in the admin role. Use the ctx.isCallerInRole method.

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Implementing a Security Policy


Page 7 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

d. If you do not have a context reference you can obtain one by adding @Resource
private SessionContext ctx; as an instance-level variable.

e. The principal’s name does not match the ID passed as an argument to the
getAllCustomerShares method.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

3. Build and test the application.


a. Save any modified files. If Build Automatically is not enabled then build the
BrokerTool web application manually. Resolve any errors before you continue.
b. Point your browser at: http://localhost:8080/BrokerTool/AllCustomers
c. Select a customer’s portfolio to view. You should be prompted for a password. Enter
the user name and password for an account in the admin role. You should be able to
view all customer portfolios.
d. Close all instances of your web browser to log out.
e. Launch a new web browser and enter this URL: s a
http://localhost:8080/BrokerTool/AllCustomers ) h a
c o m
f. Select a customer’s portfolio to view. You should be prompted for a password. Enter

ail ideฺ
the user name and password for an account that is not in the admin role. You should
be able to view only that customer’s portfolio. m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Implementing a Security Policy


Page 8 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice 15-4: Describing Java EE Security

Overview
In this practice, you check your understanding of Java EE security.

Tasks
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

1. In the following sentences, fill in each blank with the missing word (or words):
a. To check the calling user, an EJB uses its _______________.
b. The web tier equivalent of isUserInRole(...) is ____________________.
c. Two common security annotations used in an EJB are ______________ and
______________.
d. Web-tier components configure their security settings in the _____________ file.
e. The ______________ version of enterprise Java first allowed the
@ServletSecurity annotation to be used in a servlet. s a
) h a
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Implementing a Security Policy


Page 9 of 10
Pontifícia Universidade Católica do Rio Grande do Sul

Practice Solutions
Use the following solutions to check your answers to these exercises.

Solutions for Practices 15-1, 15-2, and 15-3


You can find sample solutions for these practices in the following directory:
D:\Labs\eclipse\solutions\Security.
Unauthorized reproduction or distribution prohibited. Copyright© 2011, Oracle and/or its affiliates.

Solution for Practice 15-4


Compare your responses with the following answers:
a. To check the calling user, an EJB uses its EJBContext or SessionContext.
g. The web-tier equivalent of isUserInRole(...) is isCallerInRole(...).
h. Two common security annotations used in an EJB are @DeclareRoles and
@RolesAllowed.
i. Web-tier components configure their security settings in the web.xml file.
s a
j. The JavaEE6 version of enterprise Java first allowed the @ServletSecurity ) h a
annotation to be used in a servlet.
c o m

ail ideฺ
m
g Gu
o @
8 ent
s
do Stud
a r
( a nc this
o s o use
a rd e to
i d is C licens
i c ola ble
r e N fera
a n d rans
x -t
Ale non

Copyright © 2011, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: Implementing a Security Policy


Page 10 of 10

You might also like