拦截器代码:
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之前。