Struts2 拦截器修改request传入Action参数

 拦截器代码:
 

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.dispatcher.HttpParameters;
import org.apache.struts2.dispatcher.Parameter;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class BussysInterceptor implements Interceptor {

    @Override
    public void destroy() {
    }

    @Override
    public void init() {
    }

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {

        ActionContext action = invocation.getInvocationContext();
        HttpServletRequest request = (HttpServletRequest) action.get(StrutsStatics.HTTP_REQUEST);
        HttpSession session = request.getSession();
        String xxx= (String) session.getAttribute("xxxx");
        if (StringUtils.isNotBlank(xxx)) {
            HttpParameters httpParameters = action.getParameters();
            Map<String, Parameter> newParams = new HashMap<String, Parameter>();
            for (String key : httpParameters.keySet()) {
                Parameter p = httpParameters.get(key);
                if (p instanceof Parameter.Request) {
                    newParams.put(key, new Parameter.Request(key, new String[] { p.getValue() }));
                }
            }
            newParams.put("xxxx", new Parameter.Request("xxxx", new String[] { xxx}));
            request.setAttribute("xxxx", xxx);
            httpParameters.appendAll(newParams);
            action.setParameters(httpParameters);
        }

        return invocation.invoke();
    }

}

struts2的拦截器xml文件相关部分配置:

<!-- 用于CRUD Action的parent package -->
	<package name="crud-default" extends="convention-default" strict-method-invocation="false">
		<!-- 基于paramsPrepareParamsStack,增加store interceptor保证actionMessage在redirect后不会丢失 -->
		<interceptors>
			<interceptor name="aaa" class="com.xxx.web.interceptor.BussysInterceptor" />
			<interceptor-stack name="crudStack">
				<interceptor-ref name="store">
					<param name="operationMode">AUTOMATIC</param>		
				</interceptor-ref>
				<interceptor-ref name="aaa"/>
				<interceptor-ref name="paramsPrepareParamsStack" />
			</interceptor-stack>
		</interceptors>
		<default-interceptor-ref name="crudStack" />
		<global-allowed-methods>regex:.*</global-allowed-methods>
	</package>

注:之前测试时,怎么也不成功,后来发现是拦截器顺序有问题,应该把修改参数内容的拦截器放到paramsPrepareParamsStack之前。


 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值