Struts 2 URL tag example

The Struts 2 url tag can be useful if you need to use a url in many places and don’t want to repeat the code again and again. You need to specify an id attribute for your url and you can also use actions instead of simple links in this tag. Adding parameters to the url can be done by using the param tag.
** UPDATE: Struts 2 Complete tutorial now available here.
Url tag example
Here are some examples to show the use of Struts 2 “url” tag.
1. Create an image url.
<img src="<s:url value="/image/android.jpg"/>" />
Output (assume the root context name is “URLtag”)
<img src="/URLtag/image/android.jpg" />
2. Create a “Yahoo” text and link it to http://www.yahoo.com.
<a href="<s:url value="http://www.yahoo.com"/> >Yahoo</a>
Output
<a href="http://www.yahoo.com">Yahoo</a>
Note :
When you define the URL value with starting of “www” or “http”, Struts 2 will not add extra root context, instead it will display as it is.
3. Adding parameters to the url using param tag
<s:url id="urlValue" action="urlTag.action"> <s:param name="age">25</s:param> </s:url> <s:a href="%{urlValue}">urlTag With Parameter</s:a>
On clicking the above <s:a> tag, the following url is generated in the browser
http://localhost:8089/URLtag/urlTag.action?age=25
Complete jsp page
<%@ page contentType="text/html; charset=UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <html> <head> <title>URL Tag</title> </head> <body> <h2>Struts 2 URL tag</h2> <ol> <li><img src="<s:url value="/image/struts.jpg"/>" /></li> <li><a href="<s:url value="http://www.yahoo.com" />">Yahoo</a></li> <li> <s:url id="urlValue" action="urlTag.action"> <s:param name="age">25</s:param> </s:url> <s:a href="%{urlValue}">urlTag With Parameter</s:a> </li> </ol> </body> </html>
Demo
http://localhost:8080/URLtag/urlTag.action
Articles To Read Next
Advertisements