Reputation: 33
In struts2 we use
<action name="anAction">
<result name="success">xx.jsp</result>
</action>
to define action, and use s:url to generate a link to the action
<s:url action="anAction"></s:url>
The above s:url will output "/anAction.do".
I wonder if it's possible to let s:url
generate a default URL parameter (i.e. /anAction.do?p=xxx
for all links), without modifying the existing s:url
tags (there are many and they are scattered). The goal is to let the parameter appear in the link for SEO purpose.
Available options can be: changing any action config, changing any struts config, even rewrite the s:url
generation class.
Edit: I found that adding this to struts.xml
<constant name="struts.url.includeParams" value="get" />
partially solves my problem (as long as the initial page has ?p=xxx, all subsequent links will have it). The short-comings are obvious: the parameter will not follow a redirect action. I am still searching for more sophisticated solution.
Upvotes: 3
Views: 2855
Reputation: 1128
I did figure out how this can be done. The steps are:
1) create a class which implements org.apache.struts2.components.UrlRenderer 2) register that class with struts object factory and it will be injected as necessary
Details? Ok.
1) For example, a subclass of ServletUrlRender might look like this:
package com.example;
import java.util.Map;
import org.apache.struts2.components.ServletUrlRenderer;
import org.apache.struts2.components.UrlProvider;
public class ParameterInjectingUrlRenderer extends ServletUrlRenderer {
@Override
protected void mergeRequestParameters(String value, Map<String, Object> parameters, Map<String, Object> contextParameters) {
super.mergeRequestParameters(value, parameters, contextParameters);
parameters.put("myParameter", "secretvalue");
}
}
2) In struts.xml, set this class as the renderer implementation, with a line like this:
<constant name="struts.urlRenderer" value="parameterInjectingUrlRenderer" />
(In this example I'm using a Spring object factory, and value references a spring bean id. If you are not, I believe you put the fully-qualified class name).
That's it!
Upvotes: 1
Reputation: 10458
Global Search and replace (All IDE's should have this feature)
<s:url action="anAction"></s:url>
With
<s:url action="anAction"><s:param name="p" value="'xxx'"/></s:url>
Now every "anAction" will have a parameter p with value xxx.
It generally a good idea to specify the namespace.
<s:url namespace="/" action="anAction"><s:param name="p" value="'xxx'"/></s:url>
Upvotes: 0