在Struts2拦截器中接收不可预测的参数 [英] Receiving unpredictable parameters in Struts2 interceptor

查看:174
本文介绍了在Struts2拦截器中接收不可预测的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是编写一个拦截器,在响应中添加一些头文件。我目前有以下拦截器

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();
    }
}

我需要以标题的方式增强它可以在配置文件中定义( struts.xml

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

这里有两个问题。

1•我无法在java中定义属性Cache-control。

1• I cannot define property "Cache-control" in java.

2•标题名称是不可预测的,即可以在配置中定义任何标题as

2• Header names are unpredictable, i.e. Any header can be defined in configuration as

    <param name="other-header">some-value</param>

我有两个问题:


  • 如何在Struts2配置中定义的拦截器中接收任何标头。

  • 有没有更好的方法来做这件事?

推荐答案

使用操作配置,您已定义了几个通过<$处理的静态参数c $ c> staticParams 拦截器。此拦截器应首先在堆栈中进行。然后你只需从动作上下文中检索它们。

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]); 

这篇关于在Struts2拦截器中接收不可预测的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆