Recipe3.15.Generating URLs


Recipe 3.15. Generating URLs

Problem

You want to generate a hyperlink URL for use in a JavaScript function, using the same mechanisms available to the Struts html:link tag.

Solution

Use 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>

Discussion

The 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:


forward

The value of this attribute is the name of a global ActionForward specified as a forward element in the Struts configuration file .


action

The value of this attribute is the name of an action element in the Struts configuration file. This attribute is only available in Struts 1.2.


page

The value of this attribute, taken as a module-relative path, is used to generate a server-relative URI, including the context path and module prefix.


href

The value of this attribute is passed through unchanged.

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 Also

The 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.



    Jakarta Struts Cookbook
    Jakarta Struts Cookbook
    ISBN: 059600771X
    EAN: 2147483647
    Year: 2005
    Pages: 200

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net