读书人

Struts2应用开发详解-15、自定义拦截器

发布时间: 2012-09-22 21:54:54 作者: rapoo

Struts2应用开发详解--15、自定义拦截器

??? 拦截器在实际开发中经常用到,典型的应用如对全局环境的权限验证。拦截器实现可以体现非常好的封装性,代码也容易维护。

拦截器实现需要如下步骤。

一、实现一个拦截器类

Struts2的拦截器必须实现com.opensymphony.xwork2.interceptor.Interceptor接口和对于方法,如下所示:

1、拦截器实现类

package filter;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class TestInterceptor 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 {
??// TODO Auto-generated method stub

? ??return invocation.invoke();
?}

}

2、 拦截器栈设置

a、创建拦截器堆栈

?????<interceptors>
??? ??<interceptor name="testInter" class="test.HelloWorldAction">
??? ??<interceptor-ref name="testInter"></interceptor-ref>

??????<result name="success">/page/hello.jsp</result>
</action>

c、设置拦截所有包中的action

<default-interceptor-ref name="testStack"></default-interceptor-ref>

?

拦截器的生命周期类似于Servlet的Filter。init()负责创建实例,destroy()负责销毁,而intercept()则类似于doFilter()所有逻辑在该方法中执行。Struts拦截器的内部实现并非基于Servlet的Filter。所以运行机制跟Filter并不相同。

return invocation.invoke();返回一个字符串,该字符串默认返回action方法返回的字符,随后跳转到对应字符串的页面视图。

?

读书人网 >软件架构设计

热点推荐