|
Recipe 3.15. Generating URLsProblemYou want to generate a hyperlink URL for use in a JavaScript function, using the same mechanisms available to the Struts html:link tag. SolutionUse the Struts html:rewrite tag to generate the URL in the function as needed: <script language="JavaScript"> function popupHelp( ) { window.open('<html:rewrite forward="showHelp"/>'); } </script> DiscussionThe Struts html:link tag can be used to generate hyperlinks that are based on a Struts action (Struts 1.2), a global forward, the name of a JSP page, or any other URL. Sometimes, however, you need to generate a URL for uses other than as the value of the HRef attribute of an HTML anchor (a) element. The Struts html:rewrite tag addresses this issue. A common example of this usage occurs when a URL is needed within JavaScript. In the Solution, the html:rewrite tag generates the URL for the JavaScript window.open() function. This function opens a new browser window using the URLthe first argument of the functionas the browser location. Without the html:rewrite tag, you would have to hardcode the real path for the URL. Furthermore, if you needed to use URL rewriting to maintain the session ID, you would have to hardcode this as well. The html:rewrite tag properly handles URL rewriting just like the html:link tag. Like the Struts html:link tag, the html:rewrite tag can refer to a global forward, an action, a context-relative page, or an absolute URL. Exactly one of the following attributes must be specified:
Request parameters can be added to the query string of the URL using the paramId, paramName, and paramProperty elements as with the html:link tag. If you need to add more than one parameter, use the technique shown in Recipe 3.16. See AlsoThe Struts documentation for the rewrite tag can be found at http://jakarta.apache.org/struts/userGuide/struts-html.html#rewrite. Recipe 3.7 shows some other techniques for generating dynamic JavaScript using the Struts tags. |
|