问题
I am aiming to write an interceptor that add some headers in response. I currently have the following interceptor
public class CachingInterceptor extends AbstractInterceptor{
@Override
public String intercept(ActionInvocation ai) throws Exception {
HttpServletResponse response = (HttpServletResponse) getActionContext(ai).get(StrutsStatics.HTTP_RESPONSE);
if(null != response) {
response.setHeader("Cache-control","no-store,no-cache");
response.setHeader("Pragma","no-cache");
response.setHeader("Expires","-1");
}
return ai.invoke();
}
}
I need to enhance it in such a way that headers can be defined in configuration file (struts.xml
)
....
<!-- Define and add following interceptor in default interceptor stack -->
<interceptor name="CachingInterceptor" class="demo.CachingInterceptor">
....
<action name="myAction" class="demo.myAction">
....
<param name="Cache-control">no-store,no-cache</param>
<param name="Pragma">no-cache</param>
<param name="Expires">-1</param>
....
</action>
Now I have to define properties in my interceptor class to get values for headers
private String pragma; //with getter, setter
private String expires; //with getter, setter
Here I have two problems.
1• I cannot define property "Cache-control" in java.
2• Header names are unpredictable, i.e. Any header can be defined in configuration as
<param name="other-header">some-value</param>
I have two questions:
- How can I receive any header in interceptor defined in Struts2 configuration.
- Is there any better way to do this thing?
回答1:
With the action configuration you have defined several static parameters that are processed via the staticParams
interceptor. This interceptor should proceed first in the stack. Then you have simply retrieve them from the action context.
Map<String, Object> params = ActionContext.getContext().getParameters();
response.setHeader("Cache-control", ((String[])params.get("Cache-control"))[0]);
response.setHeader("Pragma", ((String[])params.get("Pragma"))[0]);
response.setHeader("Expires", ((String[])params.get("Expires"))[0]);
来源:https://stackoverflow.com/questions/15826918/receiving-unpredictable-parameters-in-struts2-interceptor