`
cppmayi
  • 浏览: 24881 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

Struts2学习笔记8(Intercepter)

阅读更多
2. 拦截器栈(Interceptor Stack)。Struts2拦截器栈就是将拦截器按一定的顺序联结成一条链。在访问被拦截的方法或字段时,Struts2拦截器链中的拦截器就会按其之前定义的顺序被调用。

Struts2拦截器的实现原理相对简单,当请求struts2的action时,Struts 2会查找配置文件,并根据其配置实例化相对的    拦截器对象,然后串成一个列表,最后一个一个地调用列表中的拦截器

Struts2规定用户自定义拦截器必须实现com.opensymphony.xwork2.interceptor.Interceptor接口。该接口声明了3个方法,


void init();
void destroy();
String intercept(ActionInvocation invocation) throws Exception;


intercept方法就是拦截的主体了,每次拦截器生效时都会执行其中的逻辑。


public abstract class AbstractInterceptor implements Interceptor;
public abstract class MethodFilterInterceptor extends AbstractInterceptor;

其中AbstractInterceptor提供了init()和destroy()的空实现,使用时只需要覆盖intercept()方法;

一般来说,拦截器的写法都差不多。看下面的示例:


import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class MyInterceptor implements Interceptor {
public void destroy() {
// TODO Auto-generated method stub
}
public void init() {
// TODO Auto-generated method stub
}
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("Action执行前插入 代码");    
//执行目标方法 (调用下一个拦截器, 或执行Action)  
final String res = invocation.invoke();  
System.out.println("Action执行后插入 代码");  
return res;  
}
}

Struts2拦截器需要在struts.xml中声明,如下struts.xml配置文件


/span>
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

/index.jsp
/success.jsp

名字
Alias Interceptor

在不同请求之间将请求参数在不同名字件转换,请求内容不变
chain
Checkbox Interceptor
添加了checkbox自动处理代码,将没有选中的checkbox的内容设定为false,而html默认情况下不提交没有选中的checkbox。
cookies
Conversion Error Interceptor

将错误从ActionContext中添加到Action的属性字段中。
createSession
Debugging Interceptor
提供不同的调试用的页面来展现内部的数据状况。
execAndWait
Exception Interceptor
将异常定位到一个画面
fileUpload
I18n Interceptor
记录用户选择的locale
logger
Message Store Interceptor
存储或者访问实现ValidationAware接口的Action类出现的消息,错误,字段错误等。
model-driven
Scoped Model Driven
如果一个Action实现了ScopedModelDriven,则这个拦截器会从相应的Scope中取出model调用Action的setModel方法将其放入Action内部。
params
Prepare Interceptor
如果Acton实现了Preparable,则该拦截器调用Action类的prepare方法。
scope
Servlet Config Interceptor
提供访问HttpServletRequest和HttpServletResponse的方法,以Map的方式访问。
staticParams
Roles Interceptor
确定用户是否具有JAAS指定的Role,否则不予执行。
timer
Token Interceptor
通过Token来避免双击
tokenSession
Validation Interceptor
使用action-validation.xml文件中定义的内容校验提交的数据。
workflow
Parameter Filter Interceptor

从参数列表中删除不必要的参数

profiling
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics