前言:
最近老大让每周写一篇技术性的博客,想想也没啥写,就想着随便拿个以前的项目去研究研究五大框架的底层代码。本人水平有限,有不对的地方还望大家勿喷,指正!
开始之前先了解下strtus2的工作流程:
工作原理图:
(1) 客户端(Client)向Action发用一个请求(Request)
(2) Container通过web.xml映射请求,并获得控制器(Controller)的名字
(3) 容器(Container)调用控制器(StrutsPrepareAndExecuteFilter或FilterDispatcher)。在Struts2.1以前调用FilterDispatcher,Struts2.1以后调用StrutsPrepareAndExecuteFilter
(4) 控制器(Controller)通过ActionMapper获得Action的信息
(5) 控制器(Controller)调用ActionProxy
(6) ActionProxy读取struts.xml文件获取action和interceptor stack的信息。
(7) ActionProxy把request请求传递给ActionInvocation
(8) ActionInvocation依次调用action和interceptor
(9) 根据action的配置信息,产生result
(10) Result信息返回给ActionInvocation
(11) 产生一个HttpServletResponse响应
(12) 产生的响应行为发送给客服端。
拦截器所涉及的接口和类:
用struts2实现拦截器有三种方式:
1.实现Interceptor接口
```
publicinterfaceInterceptor
extendsSerializable
//继承Serializable
{
publicabstractvoiddestroy();
publicabstractvoidinit();
//ActionInvocation 是一个接口
publicabstractStringintercept(ActionInvocationactioninvocation)
throwsException;
}
```
2.继承AbstractInterceptor类
publicabstractclassAbstractInterceptor
implementsInterceptor
//并没有具体实现
{
publicAbstractInterceptor()
{
}
publicvoidinit()
{
}
publicvoiddestroy()
{
}
publicabstractStringintercept(ActionInvocationactioninvocation)
throwsException;
}
所以我们并不建议用上面那两种方法
继承MethodFilterInterceptor类
publicabstractclassMethodFilterInterceptorextendsAbstractInterceptor
{
publicMethodFilterInterceptor()
{
log=LoggerFactory.getLogger(getClass());
excludeMethods=Collections.emptySet();
includeMethods=Collections.emptySet();
}
publicvoidsetExcludeMethods(StringexcludeMethods)
{
this.excludeMethods=TextParseUtil.commaDelimitedStringToSet(excludeMethods);
}
publicSetgetExcludeMethodsSet()
{
returnexcludeMethods;
}
publicvoidsetIncludeMethods(StringincludeMethods)
{
this.includeMethods=TextParseUtil.commaDelimitedStringToSet(includeMethods);
}
publicSetgetIncludeMethodsSet()
{
returnincludeMethods;
}
publicStringintercept(ActionInvocationinvocation)
throwsException
{
if(applyInterceptor(invocation))
returndoIntercept(invocation);
else
returninvocation.invoke();
}
protectedbooleanapplyInterceptor(ActionInvocationinvocation)
{
Stringmethod=invocation.getProxy().getMethod();
booleanapplyMethod=MethodFilterInterceptorUtil.applyMethod(excludeMethods,includeMethods,method);
if(log.isDebugEnabled()&&!applyMethod)
log.debug((newStringBuilder()).append("Skipping Interceptor... Method [").append(method).append("] found in exclude list.").toString(),newString[0]);
returnapplyMethod;
}
protectedabstractStringdoIntercept(ActionInvocationactioninvocation)
throwsException;
protectedtransientLoggerlog;
//排除的方法集合
protectedSetexcludeMethods;
//包括的方法集合(就是要拦截的方法)
protectedSetincludeMethods;
}