首页 > 其他 > 详细

Struts2开发自定义拦截器

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

引言

在上一篇中已经讲了一下拦截器的基本概念(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开发自定义拦截器

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!