2020年5月14日
项目里面Interceptor的使用
先上代码
StandardOutJsonSaveInterceptor extends MethodFilterInterceptor
interceptor有不同的实现,这里继承MethodFilterInterceptor,可以设置需要拦截的方法。actionInvocation.invoke();为实际的方法调用语句。根据response里面的内容不同,可以处理方法结束后的事项,比如支付成功了,要通知发货方。失败或者异常,则做其他处理。
@Override
protected String doIntercept(ActionInvocation actionInvocation){
String result = null;
try {
System.out.println("进入StandardOutJsonSaveInterceptor拦截器");
//1.执行action方法
result = actionInvocation.invoke();
//2.获取action的response
ActionContext actionContext = actionInvocation.getInvocationContext();
Object value = getResponseValue(actionContext);//value是action中responseWrite(json.toString());里面json.toString()的值
//3.根据response处理
handle(value.toString());
} catch (Exception e) {
//不执行发消息的操作
e.printStackTrace();
}
return result;
}
/**
* 获取action里面的responseWrite的值
* @param actionContext
* @return
* @throws IOException
*/
private Object getResponseValue(ActionContext actionContext) throws IOException {
HttpServletResponse response = (HttpServletResponse) actionContext.get(StrutsStatics.HTTP_RESPONSE);
PrintWriter writer = response.getWriter();
Field ob = ReflectionUtils.findField(writer.getClass(),"ob");
ob.setAccessible(true);
Object obValue = ReflectionUtils.getField(ob, writer);
Field cb = ReflectionUtils.findField(obValue.getClass(),"cb");
cb.setAccessible(true);
Object value = ReflectionUtils.getField(cb, obValue);
return value;
}
/**
* 处理发消息等过程
* @param result
*/
private void handle(String result) {
//简单打印
System.out.println("response:"+result);
}
关于配置
<interceptors>
<!-- 先定义拦截器自己写的拦截器类 name随便写 class为全限定名 -->
<interceptor name="standardOutJsonSaveInterceptor" class="com.yuqiaotech.scm.interceptor.StandardOutJsonSaveInterceptor"/>
<!-- 加到自己设置的拦截器栈里边去 -->
<interceptor-stack name="myStack">
<!-- name为上面interceptor标签里面定义的name-->
<interceptor-ref name="standardOutJsonSaveInterceptor">
<param name="includeMethods">outJsonSaveStandard</param>
</interceptor-ref>
<!-- 在自己配置的拦截器基础上,必须有struts2默认的拦截器,不然出错 -->
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<!-- 应用拦截器不写拦截器不生效 -->
<default-interceptor-ref name="myStack"/>
这个要放到struts.xml文件的package节点下面。