1.拦截器的重要性
Struts2中的很多功能都是由拦截器完成的。比如:servletConfig,staticParam,params,modelDriven等等。
是AOP编程思想的一种应用形式。
2.拦截器的执行时机
时机.png3.自定义拦截器
3.1、拦截器的类试图
自定义拦截器.png3.2编写步骤
- a.编写一个类,继承AbstractInterceptor类或者实现Interceptor接口。重写intercept方法
public class Demo1Interceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
System.out.println("拦截前");
//放行
String invoke = actionInvocation.invoke();
System.out.println("拦截后");
return invoke;
}
}
- b.配置拦截器:注意拦截器必须先声明再使用
<package name="pp1" extends="struts-default">
<!--使用自定义拦截器-->
<interceptors>
<interceptor name="demo1Interceptor" class="com.ljb.interceptor.Demo1Interceptor"></interceptor>
</interceptors>
<action name="action1" class="com.ljb.web.Demo1Action" method="save">
<interceptor-ref name="demo1Interceptor"></interceptor-ref>
<result>/success.jsp</result>
</action>
</package>
3.3.执行顺序
public class Demo1Action extends ActionSupport {
public String save() throws Exception {
System.out.println("doAction");
return "success";
}
}
拦截前
doAction
拦截后
3.4.多个拦截器
<package name="pp1" extends="struts-default">
<!--使用自定义拦截器-->
<interceptors>
<interceptor name="demo1Interceptor" class="com.ljb.interceptor.Demo1Interceptor"></interceptor>
<interceptor name="demo2Interceptor" class="com.ljb.interceptor.Demo1Interceptor2"></interceptor>
</interceptors>
<action name="action1" class="com.ljb.web.Demo1Action" method="save">
<interceptor-ref name="demo1Interceptor"></interceptor-ref>
<interceptor-ref name="demo2Interceptor"></interceptor-ref>
<result>/success.jsp</result>
</action>
</package>
4.拦截器的应用
public class Demo1Interceptor extends MethodFilterInterceptor {
@Override
protected String doIntercept(ActionInvocation actionInvocation) throws Exception {
System.out.println("拦截前");
//放行
String invoke = actionInvocation.invoke();
System.out.println("拦截后");
return invoke;
}
}
<constant name="struts.devMode" value="true"> </constant>
<package name="pp1" extends="struts-default" >
<!--使用自定义拦截器-->
<interceptors>
<interceptor name="demo1Interceptor" class="com.ljb.interceptor.Demo1Interceptor"/>
<interceptor-stack name="myInterceptor">
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="demo1Interceptor"></interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="myInterceptor"></default-interceptor-ref>
<global-results>
<result name="input">/success.jsp</result>
</global-results>
<action name="action1" class="com.ljb.web.Demo1Action" method="save">
<interceptor-ref name="myInterceptor">
<param name="demo1Interceptor.excludeMethods">save</param>
</interceptor-ref>
<result>/success.jsp</result>
</action>
</package>
网友评论