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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With