Web applications differ from conventional websites in that web applications can create a dynamic response. To make it easier to reference dynamic data from a page, the framework offers a set of tags. Some of the tags mimic standard HTML tag, but provided added value. Other tags create non-standard, but useful controls.
A very common use cases in web applications is linking to other pages. Now that we know Struts is up and running, let's add a Welcome page with links to other actions.
Code
<%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>Welcome</title> <link href="<s:url value="/css/tutorial.css"/>" rel="stylesheet" type="text/css"/> </head> <body> <h3>Commands</h3> <ul> <li><a href="<s:url action="Register"/>">Register</a></li> <li><a href="<s:url action="Logon"/>">Sign On</a></li> </ul> <h3>Languages</h3> <ul> <li> <s:url id="url" action="Welcome"> <s:param name="request_locale">en</s:param> </s:url> <s:a href="%{url}">English</s:a> </li> <li> <s:url id="url" action="Welcome"> <s:param name="request_locale">ja</s:param> </s:url> <s:a href="%{url}">Japanese</s:a> </li> </ul> </body> </html>
On the Welcome page, we use two different Struts tags to create links.
Resource links
First, in the head element, we use the url
tag to inject a page reference into the HTML link
tag.
<link href="<s:url value="/css/tutorial.css"/>" rel="stylesheet" type="text/css"/>
Note that the reference is absolute. We can move the page around without worrying about resolving relative references.
Direct links
In the "Commands" section, we use the url
link again, to inject a reference to an Action.
<li><a href="<s:url action="Register"/>">Register</a></li>
When the link is rendered, the tag will automatically append the appropriate extension, so that we do not need to embed that fact all over the application.
The tag will also URL-encode the link with the Java session ID, if needed, so that the Java session can be retained accross requests.
Links with parameters
Finally, in the Languages section, we use the url
tag along with the param
and a
tags to create a link with request parameters.
<s:url id="url" action="Welcome"> <s:param name="request_locale">en</s:param> </s:url> <s:a href="%{url}">English</s:a>
The param tag will add the parameter "?request_locale=en" to the Welcome Action URL, and store it under the name "url". The a
tag then injects the "url" reference into the hyperlink.
Any number of parameters can be added to the URI by adding more
param
etags.
The framework provides an array of tags, ranging from the mundane to the insane. See the Tag Developers Guide for details.
Next |
Onward to Coding Actions |
---|---|
Prev |
Return to Hello World |