strut2 拦截器 使用
拦截器是strut2里一个很振奋人心的应用。通过配置拦截器可以在action执行之前进行一些初始化或者是其他的操作,但是在action执行之后,返回结果就已经确定,结果是很难改变了(目前我还不知道怎么改变结果),只能获取结果值。
如果想改变action中属性的值,就要在invoke之前进行改变。
package org.sh.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import org.apache.struts2.StrutsStatics; import org.sh.action.UserAction; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor; public class MyInterceptor extends MethodFilterInterceptor{ @Override protected String doIntercept(ActionInvocation invocation) throws Exception { //获取参数 ActionContext ac = invocation.getInvocationContext(); HttpServletRequest request = (HttpServletRequest)ac.get(StrutsStatics.HTTP_REQUEST); String name = request.getParameter("name"); String pwd = ""; System.out.println("parm:"+name+"::"+pwd+";"); if(invocation.getAction() instanceof UserAction){ ((UserAction)invocation.getAction()).getJsonResult().put("update", "error"); } ServletActionContext.getRequest(); //同上面的request String r = invocation.invoke(); HttpServletResponse response = (HttpServletResponse) ac.get(StrutsStatics.HTTP_RESPONSE); //注意 ----------------------------------- //下面的代码虽然可以改变action中属性的值,但是返回结果已经在invoke()时就已经确定了, //不会再次使用action的值进行结果的生成,所以在这里改变是没有什么意义的 if(invocation.getAction() instanceof UserAction){ System.out.println("-------------------------------"); ((UserAction)invocation.getAction()).setName("哈哈哈S"); ((UserAction)invocation.getAction()).getJsonResult().put("upd", "success"); } return r; } }
配置文件
<package name="mypackage" extends="json-default"> <interceptors> <interceptor name="myInter" class="org.sh.interceptor.MyInterceptor"></interceptor> <interceptor-stack name="mydefalut"> <interceptor-ref name="defaultStack"></interceptor-ref> <interceptor-ref name="myInter"></interceptor-ref> </interceptor-stack> </interceptors> <action name="uact" class="org.sh.action.UserAction"> <result type="json" name="success" > <param name="root">jsonBean</param> <param name="excludeNullProperties">false</param> </result> <interceptor-ref name="mydefalut"></interceptor-ref> </action> </package>