...
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 var="url" action="HelloWorldWelcome"> <s:param name="request_locale">en</s:param> </s:url> <s:a href="%{url}">English</s:a> </li> <li> <s:url var="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 link to inject a reference to an 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 var="url" action="HelloWorldWelcome"> <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 an action URI. If we link only to actions, and never to pages, then it's easy to add an Action class later.
...