Getting Interceptor Parameters in Struts 2

早过忘川 提交于 2019-12-01 17:42:37
Dev Blanked

In your custom interceptor you can define a map like below

private final Map<String, String> interceptorConfigs = new HashMap<String, String>();

public Map<String, String> getInterceptorConfigs() {
    return interceptorConfigs;
}


public void addInterceptorConfig(final String configName, final String configValue) {
    interceptorConfigs.put(configName, configValue);
}

Then in your action mappings you can pass in parameters like below .. these will be stored in the map of the interceptor

    <action name="yourAction" class="your.actionClass">
        <result name="success">some.jsp</result>
        <interceptor-ref name="defaultStack">
            <param name="yourInterceptor.interceptorConfigs.key">value</param>
            <param name="yourInterceptor.interceptorConfigs.aParamName">paramValue</param>            </interceptor-ref>
    </action>

"yourInterceptor" refers to the name of the interceptor you have given when adding your interceptor to the struts.xml. When configured like above 'interceptorConfigs' map inside the interceptor will have , key/value pairs.

If you want to make these available to your action, you can just set the map as a context variable in the ActionContext. This can then be retrieved inside the action.

To be short I'll say no, you can't get interceptor parameters if you defined them in the interceptor-ref element. The parameters are set and applied to the interceptor during build time. However, if you put parameters to the interceptor element like

<interceptor name="theInterceptor" class="com.struts.interceptor.TheInterceptor">
  <param name="param1">one</param>
  <param name="param2">two</param>
</interceptor>

you could retrieve them on the fly

PackageConfig packageConfig = Dispatcher.getInstance().getConfigurationManager().getConfiguration().getPackageConfig("default");
Map<String, Object> interceptorConfigs = packageConfig.getInterceptorConfigs();
InterceptorConfig interceptorConfig =  (InterceptorConfig)interceptorConfigs.get("theInterceptor");
Map<String, String> params = interceptorConfig.getParams();  

If you don't want to define properties on the interceptor to hold the values then OGNL will not set the values but will try, so I don't see the reasons to not to define these properties, the xml configuration marked invalid if your interceptor bean doesn't contain these properties and builder might be throw an exception in this case. So, not defining properties for params I'm not recommending.

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