...
Tip |
---|
While HTML provides a simple |
Linking
A very common use cases case 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.
...
Another common use case is using a link to change locales. On the HelloWorld page, let's add links to change the user's locale and to display a message from the application resources.
Panel |
---|
Code Block | ||||||||
---|---|---|---|---|---|---|---|---|
| ||||||||
<body> <h2><s:property value="message"/></h2> <h3>Languages</h3> <ul> <li> <s:url idvar="url" action="HelloWorldWelcome"> <s:param name="request_locale">en</s:param> </s:url> <s:a href="%{url}">English</s:a> </li> <li> <s:url idvar="url" action="HelloWorldWelcome"> <s:param name="request_locale">es</s:param> </s:url> <s:a href="%{url}">Espanol</s:a> </li> </ul> </body> |
Note |
---|
The |
How the Code Works
"%{url}" will be evaluated to the url defined with the s:url tag. On the Welcome and HelloWorld pages, we use two different Struts tags to create links. We create
...
Note that the reference is absolute. We can move the page containing the link around without worrying about resolving relative references.
The url
tag will also inject the web application context name.
Direct links
In the "Commands" section, we use the url
link tag again, to inject a reference to an link to a Struts 2 Action.
Code Block | ||
---|---|---|
| ||
<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 information across 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 across requests.
...
Code Block | ||
---|---|---|
| ||
<s:url idvar="url" action="Welcome"> <s:param name="request_locale">en</s:param> </s:url> <s:a href="%{url}">English</s:a> |
The This 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. This request_locale parameter will be picked up by the I18n Interceptor, and change your Locale accordingly.
...
Since the Welcome page is nothing but links, we don't need an Action class. But, we should still add We'll still use a mapping, however, so that we can use use an action URI. If we link only to actions, and never to pages, then it's easy to add an Action class later.
Code Block |
---|
<action name="Welcome" >
<result>/tutorial/Welcome.jsp</result>
</action>
|
...
Code Block | ||||||||
---|---|---|---|---|---|---|---|---|
| ||||||||
<action name="*" >
<result>/tutorial/{1}.jsp</result>
</action>
|
...