码迷,mamicode.com
首页 > 其他好文 > 详细

Struts2开发自定义拦截器

时间:2015-05-24 14:17:28      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:interceptor   自定义   自定义拦截器   struts2   

引言

在上一篇中已经讲了一下拦截器的基本概念(http://blog.csdn.net/xlgen157387/article/details/45951163),下边咱们一起实现一个自定义的拦截器。

Interceptor接口

public interface Interceptor extends Serializable {

    /**
     * Called to let an interceptor clean up any resources it has allocated.
     */
    void destroy();

    /**
     * Called after an interceptor is created, but before any requests are processed using
     * {@link #intercept(com.opensymphony.xwork2.ActionInvocation) intercept} , giving
     * the Interceptor a chance to initialize any needed resources.
     */
    void init();

    /**
     * Allows the Interceptor to do some processing on the request before and/or after the rest of the processing of the
     * request by the {@link ActionInvocation} or to short-circuit the processing and just return a String return code.
     *
     * @param invocation the action invocation
     * @return the return code, either returned from {@link ActionInvocation#invoke()}, or from the interceptor itself.
     * @throws Exception any system-level error, as defined in {@link com.opensymphony.xwork2.Action#execute()}.
     */
    String intercept(ActionInvocation invocation) throws Exception;
}

可以看出接口中只有三个方法需要实现。

实现Interceptor接口

public class MyInterceptor implements Interceptor {
    public void destroy() {
        System.out.println("destroy()----");
    }
    public void init() {
        System.out.println("init()----");
    }
    public String intercept(ActionInvocation invocation) throws Exception {
        System.out.println("在Action执行之前");
        String result = invocation.invoke();
        System.out.println("在Result执行之后");
        return result;
    }
}

我们需要在struts.xml文件中进行配置:

<package name="helloworld" extends="struts-default">
        <interceptors>
            <interceptor name="MyInterceptor" class="com.lc.action.MyInterceptor" />
        </interceptors>
        <action name="loginAction" class="com.lc.action.LoginAction">
            <param name="account">test</param>
            <result>/welcome.jsp</result>
            <interceptor-ref name="MyInterceptor" />
            <interceptor-ref name="defaultStack" />
        </action>
    </package>

首先声明一个自定义的拦截器:

<interceptors>
            <interceptor name="MyInterceptor" class="com.lc.action.MyInterceptor" />
        </interceptors>

然后在action中引用:

<interceptor-ref name="MyInterceptor" />

执行的结果可想而知:

在Action执行之前
account=test,password=test,submitFlag=login
在Result执行之后

Struts2开发自定义拦截器

标签:interceptor   自定义   自定义拦截器   struts2   

原文地址:http://blog.csdn.net/xlgen157387/article/details/45951517

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!