Receiving unpredictable parameters in Struts2 interceptor

*爱你&永不变心* 提交于 2019-12-06 09:14:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!