Struts2的拦截器

时间:2023-01-05 11:18:15

拦截器的作用:

  拦截器可以动态地拦截发送到指定Action的请求,通过拦截器机制,可以载Action执行的前后插入某些代码,植入我们的逻辑思维。

拦截器的实现原理:

  拦截器通过代理的方式来调用,通过动态代理我们的Action,在Action的执行前后植入我们的拦截代码。这种拦截器的思想就是一种AOP,取得业务处理过程的切面,在特定切面

通过系统自动插入特定方法。

                Struts2的拦截器

Struts2中的拦截器:

  在平常的项目中,我们经常需要解析上传表单中的文件域,防止表单多次提交……,这些操作不是所有Action都需要实现的动作,需要以动态的方式*组合。拦截器策略就

很好解决了这个问题,拦截器方法在目标方法执行之前或者执行之后自动执行,从而完成通用操作的动态插入。

            Struts2的拦截器

拦截器的配置:

  定义一个拦截器:

<interceptor name="拦截器名字" class="拦截器实现类">
<param name="参数名">参数值</param>
</interceptor>

  也可以定义一个拦截器栈,这个拦截器栈是包含了多个拦截器的。

<interceptor-stack name="拦截器栈名">
<interceptor-ref name="拦截器一"/>
<interceptor-ref name="拦截器二"/>
</interceptor-stack>

自定义拦截器:

  开发自己的拦截器类,首先我们来看看Interceptor是怎么样。

public interface Interceptor extends Serializable {
void destroy();
void init();
String intercept(ActionInvocation invocation) throws Exception;
}

  从上面的代码可以知道,init方法初始化类,destroy方法就是销毁类,intercept方法就是你实际的拦截内容了。除此之外,Struts2为我们提供了一个AbstractInterceptor类,我们可以通过继承这个类来减少代码量,下面开始实现自己的拦截器。

@SuppressWarnings("serial")
public class ShowTimeInterceptor extends AbstractInterceptor {
private String name; @Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
System.out.println("I am " + name);
System.out.println(name + " : " + new Date());
String result = actionInvocation.invoke();
System.out.println(name + " : " + new Date());
return result;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}

  然后在struts.xml中配置信息:

<interceptors>
<interceptor name="showTime" class="com.xujianguo.action.interceptor.ShowTimeInterceptor">
<param name="name">ShowTimeInterceptor</param>
</interceptor>
</interceptors>
<action name="login" class="com.xujianguo.action.LoginAction">
<result name="success">/login-success.html</result>
<result name="error">/login.html</result>
        <!-- 默认的拦截器defaultStack -->
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="showTime"></interceptor-ref>
</action>