Struts2基础——自定义拦截器

一、自定义拦截器

默认的拦截器能实现的功能是有限的,Struts2 支持自定义拦截器。

二、拦截器类

1.实现 Interceptor 接口

2.继承 AbstractInterceptor 抽象类,需要实现 public String intercept(ActionInvocation actionInvocation) 方法,其中通过 actionInvocation.invoke() 继续调用后续拦截器 和 Action 方法。

Struts2 会自动跳转到自定义拦截器的 interceptor 方法返回值对应的 result,如果直接返回一个 String,那么会将控制器交给目标 action 对应的 result。

3.注册自定义拦截器与使用

(1)Action 级

<package name="default" namespace="/" extends="struts-default">
  <interceptor name="myInterceptor" class="com.nucsoft.struts.interceptor.MyInterceptor"/>
  <action name="interceptor" class="com.nucsoft.struts.token.InterceptorAction">
    <interceptor-ref name="myInterceptor"/>
    <interceptor-ref name="defaultStack"/>
      <result>/success.jsp</result>
      <result name="input">/error.jsp</result>
  </action>
</package>

(2)package 级

<package name="default" namespace="/" extends="struts-default">
  <interceptors>
    <interceptor name="myInterceptor" class="com.nucsoft.struts.interceptor.MyInterceptor"/>
    <interceptor-stack name="myInterceptorStack">
      <interceptor-ref name="myInterceptor"/>
      <interceptor-ref name="defaultStack"/>
    </interceptor-stack>
  </interceptors>
  <default-interceptor-ref name="myInterceptorStack"/>
  <action name="myInterceptor" class="com.nucsoft.struts.token.InterceptorAction" method="myInterceptor">
    <result>/success.jsp</result>
    <result name="input">/error.jsp</result>
  </action>
</package>

推荐阅读:

Struts 的详细介绍请点这里
Struts 的下载地址请点这里

猜你喜欢

转载自www.linuxidc.com/Linux/2016-07/133114.htm