Você está na página 1de 7

Creating Bookmarkable URLs

April 2006 [Revision number: V2-1]


Copyright 2006 Sun Microsystems, Inc.

If you have a page that you want users to be able to bookmark, and the page requires parameters, you can use the URL to pass the parameters. This tutorial shows how to dynamically create a URL that includes the parameters and how to access the parameters from the bookmarkable page. Contents About Bookmarkable URLs Designing the Start Page Creating the Bookmarkable URL Creating the Details Page Modifying the SQL Query Adding Code Running and Testing the Application Doing More With Bookmarkable URLs

About Bookmarkable URLs


The web applications that you build using the IDE use forward dispatching by default to switch from one page to another. This means that the web application's controller switches to the new page internally and sends the response (the new web page) to the browser. As far as the browser knows, it is still on the same page. This is why the URL that the browser shows for the current page is typically the URL for the previous page. One problem with forward dispatching is that users are not able to bookmark the pages. The only way to get back to a page at a later date is to navigate to the application's start page and navigate to the desired page. If you need a page to be bookmarkable, you can use redirect dispatching. With redirect dispatching, the web application's controller instructs the browser to fetch another URL. This solution works as long as the page does not depend upon parameters. For example, if your page shows the detail data for a specific person id, the page will not work when a user accesses it using the bookmarked URL, because it needs the person id. If you have a page that you want users to be able to bookmark, and the page requires parameters, you can use the URL to pass the parameters. This tutorial shows how to dynamically create a URL that includes the parameters and how to access the parameters from the bookmarkable page.

Designing the Start Page


You begin by creating a start page and adding a Table component to the page. You use the Table Layout dialog box to configure the Table to get items from the PERSON database table. You also configure the Table to include a Hyperlink component. 1. Open the Servers window and ensure that the bundled database is running. If the Bundled Database Server node does not have a green badge, right-click the node and choose Start Bundled Database. 2. Create a new web application and name it BookmarkableLinks. Figure 1 shows the page you create in this section.

Figure 1: Start Page Design 3. From the Basic section of the Palette, drag a Table component onto the page. Set its title property to Travelers. 4. Right-click the Table component and choose Table Layout from the pop-up menu. 5. In the Table Layout dialog box, click Add Data Provider. 6. In the Add Data Provider dialog box, expand Data Sources > Travel > Tables and then select PERSON. Click Add. The Selected column in the Table Layout box now shows all the table's columns. 7. Select PERSON.FREQUENTFLYER in the Selected column and click the < button to move it to the Available column. 8. Click New in the Table Layout dialog box to add a new column. 9. In the Columns Details section, make the following three changes for the new column. Use Figure 2 as a guide.
q q q

Delete tablecolumn4 from the Header Text field. Set the Component Type drop-down list to Hyperlink. Type Details in the Value Expression text field.

Figure 2: Table Layout Dialog Box

10. Click OK to close the Table Layout dialog box and update the Table component. The Visual Designer displays four columns in the Table component, the right-most of which includes the Details Hyperlink component.

Creating the Bookmarkable URL


Next you set the url property for the Hyperlink component so that it includes the person id parameter. 1. Click one of the Details Hyperlinks in the Table component. This action selects all Details Hyperlinks. 2. In the Properties window, set the url property to the following value:. /faces/Details.jsp?personId=#{currentRow.value['PERSON.PERSONID']}

The URL points to the Details page, which you create in the next section.

Creating the Details Page


Now you create the application's second page, called Details. You place a Table component on the page and connect the component to the TRIP database table. 1. In the Projects window, right-click BookmarkableLinks > Web Pages and choose New Page. Type Details for the File Name and click Finish. Figure 3 shows the page you design in this section.

Figure 3: Details Page Design 2. Drag a Table component onto the page. Set its title property to Trips. 3. Right-click the Table and choose Table Layout. 4. In the Table Layout dialog box, click Add Data Provider. 5. Expand Data Sources > Travel > Tables and then select TRIP. Click Add. The Tables Layout dialog box is populated with information from the TRIP database table. 6. Click OK to close the Table Layout dialog box and update the Table component.

Modifying the SQL Query


Next, you modify the SQL query in the tripRowSet object so that the query returns just the trips for the specified person. 1. In the Outline window, expand SessionBean1. Right-click the tripRowSet node and choose Edit SQL Statement. The Query Editor appears in the editing area, with a tripRowSet tab. 2. In the Design Grid of the Query Editor, right-click in the PERSONID cell and choose Add Query Criteria. 3. Set the Comparison drop-down list to =Equals and select the Parameter radio button. 4. Click OK. You see =? in the Criteria column for PERSONID, which adds the following WHERE clause in the SQL query: Code Sample 1: WHERE Clause in the SQL Query WHERE TRAVEL.TRIP.PERSONID = ?

Adding Code
For this application, the Table component in the Details page must display only the trip information for the person whose name is selected in the Table component in Page 1. To create this master-detail relationship, you modify the Detail page's prerender method to get the person id from the request parameters. 1. Click the Details tab to open the page. 2. Click the Java button to view the source code for the Details page. 3. Scroll to the prerender() method and add the following code shown in bold. Code Sample 2: Get the Person id From the Request Parameter public void prerender() { // Get the person id from the request parameters String personId = (String) getExternalContext().getRequestParameterMap().get("personId"); if (personId != null) { try { getSessionBean1().getTripRowSet().setObject(1, personId); tripDataProvider.refresh(); } catch (Exception e) { error("Cannot select trips for " + personId); log("Cannot select trips for " + personId, e); } } }

4. Press Ctrl-Shift-F to reformat the code.

Running and Testing the Application


1. Deploy and run the application by clicking the Run Main Project button. The browser renders Page 1, as shown in Figure 4.

Figure 4: Completed Start Page 2. Click a Details link to switch to the Details page, which shows the trips for that traveler. 3. Use your browser menu to create a bookmark for the page. 4. Open a new browser window and then use the bookmark you just created to open the page. As long as the application and database servers are running, you are able to display the bookmarked page. NOTE: Some browsers include the session id parameter in the URL for the Details page. This does not cause problems with creating the bookmark and recreating it, because the session id will be invalid later and a new session will be created. You can prevent this by making sure that cookies are enabled for your browser.

Doing More With Bookmarkable URLs


Here are some additional tips for creating bookmarkable URLs:
q

To include a bookmarkable URL, you must use a Hyperlink component instead of an action component. If you would rather have the user click on a button, use an Image Hyperlink component and use an image that looks like a button. The internal navigation mechanism maps http://localhost:28080/Bookmarks/ to /faces, which, in turn, maps to the web directory in your deployed project. If your page is in a subdirectory under web, add the subdirectory to the URL that you specify in the url property, such as /faces/foo/bar/Details.jsp. Be sure to precede the URL with /faces and not faces. This tutorial calculates the URL directly in the url property. Alternatively, you can add a property to a managed bean, such as the page bean, or the session bean, with a getter method that returns the calculated URL. You would then bind the url property to this bean property.

Try It. In this tutorial, you used the getRequestParameterMap method to obtain the request parameters. Another way to obtain request parameters is through managed bean property settings. Try the following steps to see how this works. 1. In the Java source for the Details page, add the following code to create a personId property: Code Sample 3: Create personId Property private String personId; public void setPersonId(String personId) { this.personId = personId; } public String getPersonId() { return this.personId; }

2. In the Projects window, double-click the Managed Beans node to open the file in the XML editor. Modify the managed-beans.xml entry for the details bean to to include the code shown in bold. Code Sample 4: Managed-bean xml Entry <managed-bean> <managed-bean-name>Details</managed-bean-name> <managed-bean-class>bookmarkablelinks.Details</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> <managed-property> <property-name>personId</property-name> <value>#{param.personId}</value> </managed-property> </managed-bean>

Note that the variable name param corresponds to a map of the request parameters for this request. 3. Edit the prerender method in the Details page and comment out the following line: String personId = (String) getExternalContext().getRequestParameterMap().get("personId");

You remove the logic that looks up the personId request parameter because its value is already injected by virtue of the fact that the # {param.personId} expression was evaluated when the bean was created. You want the code in the try/catch block to execute, but you want it to use the value from the instance variable personId, not a variable local to the prerender() method. Be sure to use a String property when pulling in request parameters, even if the value might naturally be considered an integer (as might be done for a person's id). Even though the expression evaluation attempts to do the right conversions, it throws exception if the incoming value doesn't convert successfully. It is better to handle the conversion problems in the prerender method.

See Also:
q q q

Working with Data Providers Using Databound Components to Access Databases Sharing Data Between Two Pages

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 14, 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 q

UNIX(R) software 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 tats-Unis 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.

Você também pode gostar