Sie sind auf Seite 1von 14

Understanding Scope and Managed Beans

March 2006 [Revision number: V2-5]


Copyright 2006 Sun Microsystems, Inc.

In this tutorial, you use the Sun Java Studio Creator integrated development environment (IDE) to create an application that demonstrates how to use the application, session, and request scopes to manage your application's objects. Scope is the availability (or context) of an object and its intended life span in a web application. The web application that you create in this tutorial uses an object in application scope to tally votes, and uses an object in session scope to ensure that a user votes only once per session. The application uses a request scope object to display the time that the user submitted the vote. The time is stored in request scope, because the application does not need the value after the response is sent to the client browser. Contents - About Scopes - Adding Properties to Managed Beans - Creating the Start Page - Creating the Results Page - Specifying Page Navigation - Running the Application - Doing More To complete this tutorial, you need to know how to create a project and build a web application in the IDE. For more information, see the Getting Started With Java Studio Creator and Developing a Web Application tutorials.

About Scopes
As long as a user stays on a page, the component values and page bean property values are remembered even when the page redisplays, such as when the user clicks a button that returns null. However, when the user leaves the page, the component and page property values disappear. To make values available to other pages, or to make values available to the same page, should the user return to it, you need to store the values. When you create a project from the IDE, the IDE creates three managed beans for storing values:
q q q

RequestBean1 SessionBean1 ApplicationBean1

The following figure shows the Outline window with the default managed beans.

Figure 1: Default Managed Beans A managed bean is a JavaBeans object that a JavaServer Faces web application instantiates and stores in either request scope, session scope, or application scope. As you can guess, the web application stores RequestBean1 in request scope, SessionBean1 in session scope, and ApplicationBean1 in application scope. To add a property to one of these managed beans, right-click the bean in the Outline window or the Projects window and choose Add > Property from the pop-up menu. After you complete the dialog and click OK, the IDE adds the property and its appropriate

getter and setter methods to the source code. You can access a bean property's values by binding a component's property to it, or by calling the bean property's getter and setter methods. You use both access methods in this tutorial. Before you create a bean property to store a value, you must decide what scope to put the property in. Because several users can access a web application at the same time, you want to use the smallest scope possible so that you don't waste valuable space. The following figure illustrates the duration of each type of scope.
q

Application scope lasts until the server stops the application. Values that you store in an application bean are available to every session and every request that uses the same application map. Session scope begins when a user first accesses a page in the web application and ends when the session times out due to inactivity, or when the web application invalidates the session, such as, for example, by calling session.invalidate (). Request scope begins when the user submits the page and ends when the response is fully rendered, whatever page that is.

Figure 2: Web Application Scopes Say that your web application has a drop-down list of measurement types (pixels, centimeters, and inches). You might want to store the list of choices in ApplicationBean1, so that it is shared by all concurrent user sessions. On the other hand, you might store the user's login name in SessionBean1, so that it is available for all the pages that the user accesses in that session. If you don't need the information beyond the lifetime of the current request, you can save space by putting the property in RequestBean1. Warning: You cannot use a request bean if you have included the <redirect> element inside the <navigation-case> element of a navigation rule. (You see these rules when you click the Source button in the Page Navigation editor.) When the page is submitted, the <redirect> element redirects the page and ends the request before a subsequent page can use any of the values stored in the Request Bean. You also cannot use request beans in portlets. When you create a page from the IDE, the Java source for the page bean contains methods for accessing the RequestBean1, SessionBean1, and ApplicationBean1 objects. To access properties on these managed beans, you use code similar to the statements in the following code snippet.

Code Sample 1: Accessing an Application Bean Property ApplicationBean1 appBean = getApplicationBean1(); Option[] choices = appBean.BallotOptions();

The web application instantiates a managed bean the first time, within that bean's scope, that a page accesses a property in the managed bean. For example, an instance of a SessionBean1 object does not exist for the user's session until the user accesses a page that references a SessionBean1 property. Tip: To add additional managed beans, right-click the Source Packages node in the Projects window, choose New > Files/Folders, select the Managed Beans category, select the scope, and complete the remaining wizard steps.

Adding Properties to the Managed Beans


The pages in this web application require access to the following values:
q

ballotOptions. This array contains the ballot choices. Because the list remains the same for all sessions, this property goes in application scope. tally. Because the tally accumulates all the session votes, it must be in application scope. hasVoted. This boolean property tracks whether the user has voted. Because the application needs to persist the value across several requests, the application stores the value in session scope. timestamp. When the user submits a vote, the application records the time for use by the next page. Because the application does not need the value after the next page is rendered, the application stores the value in request scope.

Complete the following steps to add the properties to the managed beans. 1. Create a new project and name it Scopes. 2. In the Outline window, right-click ApplicationBean1 and choose Add > Property from the pop-up menu. A New Property Pattern dialog box appears as shown in the following figure.

Figure 3: New Property Pattern Dialog Box

3. Set the property's Name and Type as follows, and click OK. Text Field Name Type Value ballotOptions Option[]

4. Use similar steps to add another property to the application bean. Set the property's Name and Type as follows, and click OK. Text Field Name Type Value tally HashMap

5. In the Outline window, double-click ApplicationBean1 to open its Java source file. 6. Right-click in the source and choose Fix Imports from the pop-up menu. Because there is more than one package that contains the Option class, the Fix Imports dialog appears. 7. Select com.sun.rave.web.ui.model.Option from the Fully Qualified Name drop-down list, and click OK. The IDE adds import statements for the following classes to the source:
r r

com.sun.rave.web.ui.model.Option java.util.HashMap

8. Scroll to the init method and add the following code at the bottom of the method. Code Sample 2: Code to Add to the Application Bean's init Method // populate ballot items ballotOptions = new Option[] { new Option("java", "Java Programming Language"), new Option("cpp", "C++"), new Option("fortran", "Fortran") }; // initialize counters for ballot choices tally = new HashMap(); for (int i=0; i < ballotOptions.length; i++) { this.tally.put(ballotOptions[i].getValue(), "0"); }

9. Add the following methods at the end of the file, just before the last end brace.

Code Sample 3: Application Bean Vote Counting Methods /** * Vote counter for property tally. */ public void incrementTallyFor(String category) { int count = getTallyFor(category); count++; this.tally.put(category, Integer.toString(count)); } /** * Getter for value in property tally. * @param category HashMap key * @return Value to which the specified key is mapped */ public int getTallyFor(String category) { String stringCount = (String) this.tally.get(category); if (stringCount == null) { return 0; } else { int count = Integer.valueOf(stringCount).intValue(); return count; } }

10. Press Ctrl-S to save your changes, and press Ctrl-F4 to close the file. 11. In the Outline window, right-click SessionBean1 and choose Add > Property from the pop-up menu. If the Outline window is not open, click the Page1 tab in the editing area and click Design in the editing toolbar. The Outline window appears when the IDE is in design mode. 12. Set the property's Name and Type as follows, and click OK. Text Field Name Type Value hasVoted boolean

13. In the Outline window, double-click SessionBean1 to open its Java source file. 14. Scroll to the init method and add the following code at the bottom of the method. Code Sample 4: Code to Add to the Session Bean's init Method setHasVoted(false);

15. Press Ctrl-S to save your changes, and press Ctrl-F4 to close the file. 16. In the Outline window, right-click RequestBean1 and choose Add > Property from the pop-up menu. 17. Set the property's Name and Type as follows, and click OK. Text Field Name Type Value timestamp java.util.Date

18. Check the Outline window to ensure that the properties in the request bean, session bean, and application bean match the following figure. You might need to right-click RequestBean1 and choose Refresh from the pop-up menu to make the timestamp property appear.

Figure 4: Request, Session, and Application Bean Properties

Creating the Start Page


Follow these steps to create the page shown in the following figure. This page submits the user's vote. Once the user has voted, the button becomes disabled so that the user cannot vote again in that session.

Figure 5: Page1

1. Drag a Label component from the Basic section of the Palette, drop it onto the top center of the page, and set the label's text to Reader's Poll: What Is Your Favorite Programming Language?. 2. Drop a Radio Button Group component beneath the Label component. 3. In the Properties window, set the component's id to voteRBGroup. 4. Right-click the Radio Button Group component and choose Bind to Data from the pop-up menu. A Bind to Data dialog box appears. 5. In the Bind to an Object tab of the dialog box, select ApplicationBean1 > ballotOptions, and click OK. 6. Drop a Button under the Radio Button Group component, and set its text to View Results. 7. In the Properties window, set the id to viewButton. 8. Click the ellipsis (...) button for the action property, select viewButton_action from the drop-down list, and click OK.

The IDE adds the viewButton_action event handler, which returns null. 9. Drop a Button component to the right of the View Results button, and set its text to Submit Vote. 10. In the Properties window, set the id to voteButton. 11. Click the ellipsis (...) button for the disabled property. A dialog box appears. 12. In the dialog box, select Use Binding, click Bind to an Object, and select SessionBean1 > hasVoted, as shown in the following figure.

Figure 6: Binding the disabled Property 13. Double-click the Submit Vote button. The IDE adds the voteButton_action action handler, opens the Java source for the page, and displays the method. 14. Replace the body of the method with the following code that is shown in bold.

Code Sample 5: voteButton_action Method public String voteButton_action() { if (voteRBGroup.getSelected() == null) { return null; } // Tallies are kept across all user sessions String votedFor = voteRBGroup.getSelected().toString(); getApplicationBean1().incrementTallyFor(votedFor); // User can only vote one time per session getSessionBean1().setHasVoted(true); // Don't need the timestamp after the next request ends Date now = new Date(); getRequestBean1().setTimestamp(now); return null; }

15. Right-click in the source and choose Fix Imports from the pop-up menu. 16. Select java.util.Date from the Fully Qualified Name drop-down list, and click OK.

Creating the Results Page


Follow these steps to create the page shown in the following figure. This page displays the current tally. The user can click the Refresh Results button to get the latest tally, which includes the votes that have been submitted by other users since the page was last displayed.

Figure 7: Results

1. Create a new page and name it Results. 2. Drop a Label component on the top center of the Results page, and set the text to Results. 3. Drag a Grid Panel component from the Layout section of the Palette and drop it under the Label Component.

4. In the Properties window, set the columns property to 2. 5. Drag a Static Text component inside the Grid Layout component. When the outline of the Grid Layout component becomes a solid blue line, drop the Static Text component, as shown in the following figure.

Figure 8: Dropping a Component Into a Grid Panel Component 6. In the Properties window, set the id to descST0. Note that the last character in the id is a zero, and not the letter O. 7. Drag another Static Text component onto the Grid Panel component, and, when the outline of the Grid Layout component becomes a solid blue line, drop the Static Text component. 8. In the Properties window, set the id to countST0. 9. Add four more Static Text components and set their id properties to the following values:
r r r r

descST1 countST1 descST2 countST2

The Outline window should look like the following figure. If not, drag and drop the Static Text nodes in the Outline window to rearrange them in the correct order.

Figure 9: Static Text Components in the Grid Panel Component 10. Drop a Button component under the Grid Panel component and set its text to Home. 11. Set the Button component's id to homeButton. 12. Click the ellipsis (...) button for the action property, select homeButton_action from the drop-down list, and click OK. 13. Drop a Button component to the right of the Home component and set its text to Refresh Results.

14. Set the Button component's id to refreshButton. 15. Click the ellipsis (...) button for the action property, select refreshButton_action from the drop-down list, and click OK. 16. Drop a Static Text component under the Button components. 17. Set the Static Text component's id to messageST. Leave its text property blank. 18. Click Java in the editing toolbar to view the Java source for the page. 19. Scroll to the prerender method and add the following code shown in bold. Code Sample 6: prerender Method public void prerender() { // Display latest poll results ApplicationBean1 appBean = getApplicationBean1(); Option[] choices = appBean.getBallotOptions(); descST0.setText(choices[0].getLabel()); descST1.setText(choices[1].getLabel()); descST2.setText(choices[2].getLabel()); int i; i = appBean.getTallyFor(choices[0].getValue().toString()); countST0.setText(Integer.toString(i)); i = getApplicationBean1().getTallyFor(choices[1].getValue().toString()); countST1.setText(Integer.toString(i)); i = getApplicationBean1().getTallyFor(choices[2].getValue().toString()); countST2.setText(Integer.toString(i)); RequestBean1 reqBean = getRequestBean1(); Date timestamp = (Date) reqBean.getTimestamp(); if (timestamp != null) { messageST.setText("Your vote was recorded at " + (String)DateFormat.getTimeInstance(DateFormat.LONG).format( timestamp)); } }

20. Right-click in the source and choose Fix Imports from the pop-up menu. 21. Select com.sun.rave.web.ui.model.Option from the Fully Qualified Name drop-down list for Class Name Option, select java. util.Date for Class Name Date, and click OK.

Specifying Page Navigation


Follow these steps to specify the page navigation for the buttons, as shown in the following figure.

10

Figure 10: Navigation Window

1. In the editing area, click the Results tab and click Design to view the page in the Visual Designer. 2. Right-click on a blank spot in the page and choose Page Navigation from the pop-up menu. 3. Click the Page1.jsp icon to enlarge the icon. 4. Click voteButton and drag to Results.jsp. 5. Type vote and press Enter to name the link. 6. Click viewButton in Page1.jsp and drag to Results.jsp. 7. Type view results and press Enter to name the link. 8. Click the Results.jsp icon to enlarge the icon. 9. Click homeButton and drag to Page1.jsp. 10. Type home and press Enter to name the link.

Running the Application


To enable multiple sessions from the same browser, configure the application to end each session after one minute of inactivity. Then deploy and run the application. 1. In the Files window, expand Scopes, expand web, and expand WEB-INF, as shown in the following figure.

11

Figure 11: Files Window 2. Right-click web.xml and choose Edit from the pop-up menu. 3. Add the following tags at the end of the file, just before the </web-app> end tag. Code Sample 7: Configuring Session Timeout <session-config> <session-timeout>1</session-timeout> </session-config>

4. Click the Run Main Project button in the main toolbar. 5. When the start page appears, select a radio button and click Submit Vote. The browser displays the results page. Note that the results page shows the time that you submitted your vote. 6. Click Home to return to the start page. The Submit Vote is disabled because you have voted. 7. Click View Results. Note that the results page no longer shows the time that you voted. This is because the previous request bean is out of scope and a new request bean has been instantiated. 8. Wait one minute for the session to time out. Then type the following URL into the browser's address text box, and press Enter to start a new session: http://localhost:28080/Scopes. You might need to change 28080 to a different port if you are not using the default server configuration. 9. Vote again and check the results. The results should include your first vote. 10. If you have a different browser application, start that browser, type http://localhost:28080/Scopes into the browser's address text box, and press Enter. Submit another vote. 11. In the first browser, click Refresh Results from the results page. The results should include the vote that you submitted from the second browser.

12

Doing More
Using what you have learned in this tutorial, build an application that prompts for a login name. Add a page that displays the number of unique users who have accessed the web application.

Summary
You use the application bean, the session bean, and the request bean to store information for use by other pages.
q

Use the application bean for information that applies to all user sessions, such as a static option list for a Drop Down List component. Use the session bean to store information for use by other pages throughout the user's session, such as the user's login name. If you only need the information for use by the next page, use the request bean.

Warning: You cannot use request beans in portlets. You also cannot use the request bean if you have included the <redirect> element inside the <navigation-case> element of a navigation rule. A request bean, session bean, or application bean is instantiated as soon as a page accesses one of its properties. The bean is destroyed when its scope ends. To add a property to the Session Bean, right-click the Session Bean node in the Outline window or the Projects window and choose Add > Property. Use similar steps to add a property to the Request Bean or the Application Bean. See Also:
q q

Sharing Data Between Two Pages Binding Values and Working With Data Tables

More Developer Resources: For more tutorials, articles, tips, forums, updates, and expert advice for developers, visit the Java Studio Creator developer resources on the Sun Developer Network (SDN) at http://developers.sun.com/jscreator/.

This page was last modified: April 12, 2006

Sun and Third-party Trademarked Terminology


The following Sun trademarked terms might be used in the Sun Java(tm) Studio Creator tutorials:
q q q q q q q q q

Sun Java Studio Creator integrated development environment (IDE) Sun Java System Application Server version number (Application Server) Java Platform, Standard Edition technology (Java SE(tm) platform) JavaServer(tm) Faces technology JavaServer Pages(tm) technology (JSP(tm) technology) Sun Java System Web Server version number (Web Server) Java Database Connectivity software (JDBC software) Enterprise JavaBeans(tm) specification (EJB(tm) specification) Solaris(tm) Operating System software (Solaris OS software)

The following third-party trademarked terms might be used in the Sun Java Studio Creator tutorials:
q

UNIX(R) software

13

SPARC(R) processor

Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A. All rights reserved. Sun Microsystems, Inc. has intellectual property rights relating to technology embodied in the product that is described in this document. In particular, and without limitation, these intellectual property rights may include one or more of the U.S. patents listed at http://www.sun.com/patents and one or more additional patents or pending patent applications in the U.S. and in other countries. U.S. Government Rights - Commercial software. Government users are subject to the Sun Microsystems, Inc. standard license agreement and applicable provisions of the FAR and its supplements. Use is subject to license terms. Sun, Sun Microsystems, the Sun logo, Java and the Java Coffee Cup logo are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries.This product is covered and controlled by U.S. Export Control laws and may be subject to the export or import laws in other countries. Nuclear, missile, chemical biological weapons or nuclear maritime end uses or end users, whether direct or indirect, are strictly prohibited. Export or reexport to countries subject to U. S. embargo or to entities identified on U.S. export exclusion lists, including, but not limited to, the denied persons and specially designated nationals lists is strictly prohibited. Note: Sun is not responsible for the availability of third-party web sites mentioned in this document and does not endorse and is not responsible or liable for any content, advertising, products, or other materials on or available from such sites or resources. Sun will not be responsible or liable for any damage or loss caused or alleged to be caused by or in connection with use of or reliance on any such content, goods, or services available on or through any such sites or resources.

Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, tats-Unis. Tous droits rservs. Sun Microsystems, Inc. dtient les droits de proprit intellectuels relatifs la technologie incorpore dans le produit qui est dcrit dans ce document. En particulier, et ce sans limitation, ces droits de proprit intellectuelle peuvent inclure un ou plus des brevets amricains lists l'adresse http://www.sun.com/patents et un ou les brevets supplmentaires ou les applications de brevet en attente aux tatsUnis et dans les autres pays. L'utilisation est soumise aux termes de la Licence. Sun, Sun Microsystems, le logo Sun, Java et le logo Java Coffee Cup sont des marques de fabrique ou des marques dposes de Sun Microsystems, Inc. aux tats-Unis et dans d'autres pays. Ce produit est soumis la lgislation amricaine en matire de contrle des exportations et peut tre soumis la rglementation en vigueur dans d'autres pays dans le domaine des exportations et importations. Les utilisations, ou utilisateurs finaux, pour des armes nuclaires,des missiles, des armes biologiques et chimiques ou du nuclaire maritime, directement ou indirectement, sont strictement interdites. Les exportations ou rexportations vers les pays sous embargo amricain, ou vers des entits figurant sur les listes d'exclusion d'exportation amricaines, y compris, mais de manire non exhaustive, la liste de personnes qui font objet d'un ordre de ne pas participer, d'une faon directe ou indirecte, aux exportations des produits ou des services qui sont rgis par la lgislation amricaine en matire de contrle des exportations et la liste de ressortissants spcifiquement dsigns, sont rigoureusement interdites. Sun Microsystems n'est pas responsable de la disponibilit de tiers emplacements d'enchanement mentionns dans ce document et n'approuve pas et n'est pas responsable ou iresponsable d'aucun contenu, de la publicit, de produits, ou d'autres matriaux dessus ou fournis par de tels emplacements ou ressources. Sun ne sera pas responsable ou iresponsable d'aucuns dommages ou perte causs ou allgus pour tre caus par ou en liaison avec l'utilisation de ce produit ou la confiance dans des tels contenu, marchandises, ou services disponibles sur ou par des tels emplacements ou ressources.

14

Das könnte Ihnen auch gefallen