09 拦截器的使用

来源:互联网 发布:js水泥基怎么使用方法 编辑:程序博客网 时间:2024/06/02 04:42

1.   什么是拦截器

拦截器用于访问某个方法前、后加入开发者想实现的某些操作,拦截器是aop思想的一种具体实现方式。

 

2.   新增java

       package interceptor;

 

import    com.opensymphony.xwork2.ActionInvocation;

import    com.opensymphony.xwork2.interceptor.Interceptor;

 

public class LogInterceptor implements Interceptor

{

    public String intercept(ActionInvocation invocation)

            throws Exception

        {

            System.out.println("enteraction [" +invocation.getAction().getClass() + "],method["

            + invocation.getProxy().getMethod()+"]");

       

            long beginTime = System.currentTimeMillis();

            String result = invocation.invoke();

            long endTime = System.currentTimeMillis();

      

System.out.println("exit action [" + invocation.getAction().getClass() + "], method["

            + invocation.getProxy().getMethod()+ "], costTime[" + (endTime - beginTime) + ']');

        return result;

    }

 

    public void destroy()

    {

    }

 

    public void init()

    {

    }

}

 

3.   修改struts.xml

<package name="struts"namespace="/struts"extends="struts-default">

        <interceptors>

            <interceptorname="log" class="interceptor.LogInterceptor"></interceptor>

         </interceptors>

        …

         <action name="user*"class="action.UserAction"method="{1}">

            <result>/user{1}_success.jsp</result>

             <result name="error">/error.jsp</result>

             <interceptor-ref name="log"></interceptor-ref>

             <interceptor-ref name="defaultStack"></interceptor-ref>

        </action>

</package>

4.   运行

启动tomcat

访问: http://localhost:2000/Gao_struts2/struts/useradd.action?user.userName=gaoxiang&user.age=26&userName=aaaa

页面显示:

user addsuccess! 
aaaa
gaoxiang
a
userDao
addUser
8

 

控制台打印:

enter action [class action.UserAction],method[add]

exit action [class action.UserAction],method[add], costTime[2]

 

 

5.   总结

1)        实现struts2的拦截器,需要继承Interceptor接口,实现intercept(ActionInvocation invocation)方法

2)        intercept方法中需要添加invocation.invoke(),这样客户端的action请求才能继续执行struts默认的拦截器,最终访问对应服务器端的action

3)        intercept方法中invocation.invoke()的前后,我们可以添加我们需要实现的切面方法,如打印开始和结束访问对应action的对应的方法和action执行的耗时、记录访问action请求的流量等。

4)        实现的拦截器的java类后,需要在struts.xml配置拦截器,这样struts才能识别需要拦截请求,struts.xml中的拦截器关键字:interceptor

5)        配置的interceptors需要放在action上面,否则应用启动会识别。

6)        Struts2默认拦截器中实现了对执行action的耗时拦截,只需要修改struts.xml

           <action name="user*" class="action.UserAction" method="{1}">

                <result>/user{1}_success.jsp</result>

                <interceptor-ref name="timer"></interceptor-ref>

            </action>

                       即可,控制台显示:Executed action[/struts/useradd!add] took 101 ms.

原创粉丝点击