strut2学习笔记6-拦截器

来源:互联网 发布:大通医药软件 编辑:程序博客网 时间:2024/06/05 15:13
拦截器

添加新拦截器

<package name="myPackage" extends="struts-default"><interceptors><interceptor-stack name="myInterceptor"><interceptor-ref name="timer"></interceptor-ref><interceptor-ref name="defaultStack"></interceptor-ref></interceptor-stack></interceptors><default-interceptor-ref name="myInterceptor“/><action name="hello" class="com.kaishengit.web.HelloAction"><result>hello.jsp</result></action>…


给Action添加拦截器
<package name="myPackage" extends="struts-default"><interceptors><interceptor-stack name="myInterceptor"><interceptor-ref name="timer"></interceptor-ref><interceptor-ref name="defaultStack"></interceptor-ref></interceptor-stack></interceptors><action name="hello" class="com.kaishengit.web.HelloAction"><interceptor-ref name="myInterceptor"></interceptor-ref><result>hello.jsp</result></action>


构建自己的拦截器
public class MyInterceptor implements Interceptor {@Overridepublic void destroy() {  System.out.println("interceptor销毁");}@Overridepublic void init() {  System.out.println("interceptor初始化");}@Overridepublic String intercept(ActionInvocation invocation)   throws Exception {  return null;}}


配置自定义拦截器

<interceptors><interceptor name="myTimer" class="com.kaishengit.  interceptor.MyInterceptor"></interceptor><interceptor-stack name="myInterceptor"><interceptor-ref name="myTimer"></interceptor-ref><interceptor-ref name="defaultStack"></interceptor-ref></interceptor-stack></interceptors>AbstractInterceptorpublic class LoginInterceptor extends AbstractInterceptor {@Overridepublic String intercept(ActionInvocation invocation)   throws Exception {  return null;}} 

1.拦截器只拦截Action
2.在配置一个Action时添加了一个新的拦截器,会导致默认的defaultStack不可用,所以每添加一个新的拦截器,也要将默认的defaultStack加入

拦截器的两种分类:
1.普通拦截器
2.方法拦截器

使用拦截器的步骤
1.写一个拦截器类,实现com.opensymphony.xwork2.interceptor.Interceptor接口
     1.1 init方法用于初始化时调用 (容器启动时调用)
     1.2 destroy方法用于销毁时调用
     1.3 interceptor方法为核心拦截方法
2.配置拦截器

AbstructInterceptor类使用的是适配器模式



                                             
0 0
原创粉丝点击