Search from Struts2 Library

Monday, September 22, 2008

URL Tag

When you’re building web applications, URL management is a central task. Struts 2 provides a URL tag to help you do this. The tag supports everything you might want to do with a URL, from controlling parameters to automatically persisting sessions in the absence of cookies. Table below lists its attributes.



Here are a couple of examples. First we look at a simple case:

URL = <s:url value="IteratorTag.action"/> <a href='<s:url value="IteratorTag.action" />'> Click Me </a>

And here’s the output markup:
URL = IteratorTag.action

The URL tag just outputs the generated URL as a string. First we display it for reference. Then we use the same markup to generate the href attribute of a standard anchor tag. Note that we set the target of the URL with the value attribute. This means we must include the .action extension ourselves. If we want to target an action, we should probably use the action attribute, as seen in the next example:

URL = <s:url action="IteratorTag" var="myUrl"> <s:param name="id" value="2"/> </s:url> <a href='<s:property value="#myUrl" />'> Click Me </a>

Now, let’s see the markup generated by these tags:
URL =

<a href='/manningHelloWorld/chapterSix/IteratorTag.action?id=2'> Click Me </a>

As you can see, the URL tag didn’t generate any output in this example. This happened because we used the var attribute to assign the generated URL string to a reference in the ActionContext. This helps improve the readability of the code. In this example, our URL tag, with its param tags, has become unwieldy to embed directly in the anchor tag. Now we can just pull the URL from the ActionContext with a property tag and some OGNL. This is also useful when we need to put the URL in more than one place on the page.
The param tag used in this example specifies querystring parameters to be added to the generated URL. You can see generated querystring in the output. Note that you can use the includeParams attribute to specify whether parameters from the current request are carried over into the new URL. By default this attribute is set to get, which means only querystring params are carried over. You can also set it to post, which causes the posted form parameters to also be carried over. Or you can specify none.
<a href='IteratorTag.action'> Click Me </a>

No comments: