struts2自定义拦截器与过滤器

1、struts.xml
<struts>
    <!--重置属性 -->
    <constant name="struts.devMode" value="true" />

    <constant name="struts.i18n.encoding" value="utf-8" />
    <!-- 拦截器 -->
    <package name="intercept"  extends="struts-default">
        <interceptors>
            <interceptor name="permission" class="com.mysoft.base.interceptor.PermissionInterceptor" />
            <interceptor-stack name="permissionStack">
                <interceptor-ref name="defaultStack" /><!-- 默认拦截器栈 -->
                <interceptor-ref name="permission" />
            </interceptor-stack>
        </interceptors>
        <!-- 局部使用拦截器 -->
        <!-- <action name="login" class="com.mysoft.base.action.HelloWorldAction" method="login">
            <interceptor-ref name="permissionStack" />
        </action> -->
        <!-- 全局拦截器 -->
        <default-interceptor-ref name="permissionStack"/>
        <global-results>
            <result name="success">/WEB-INF/jsp/login.jsp</result>
        </global-results>
    </package>

</struts>

2、自定义拦截器
package com.mysoft.base.interceptor;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

@SuppressWarnings("serial")
public class PermissionInterceptor implements Interceptor {

    public void destroy() {
    }

    public void init() {
    }

    public String intercept(ActionInvocation invocation) throws Exception {
        Object user = ActionContext.getContext().getSession().get("user");
        if(user!=null) return invocation.invoke();
        ActionContext.getContext().put("message", "您还未登录");
        return "success";
    }

}

引用
拦截器和过滤器的区别:

1、拦截器是基于java的反射机制的,而过滤器是基于函数回调

2、过滤器依赖与servlet容器,而拦截器不依赖与servlet容器

3、拦截器只能对action请求起作用,而过滤器则可以对几乎所有的请求起作用

4、拦截器可以访问action上下文、值栈里的对象,而过滤器不能

5、在action的生命周期中,拦截器可以多次被调用,而过滤器只能在容器初始化时被调用一次



拦截器 :是在面向切面编程的就是在你的service或者一个方法前调用一个方法,或者在方法后调用一个方法比如动态代理就是拦截器的简单实现,在你调用方法前打印出字符串(或者做其它业务逻辑的操作),也可以在你调用方法后打印出字符串,甚至在你抛出异常的时候做业务逻辑的操作。

猜你喜欢

转载自weinan.iteye.com/blog/2248991