struts2 学习笔记- 传智播客 2010-9-17

来源:互联网 发布:power dvd mac 编辑:程序博客网 时间:2024/06/05 07:33

1.自定义拦截器

非常实用

场景:用户登录后可以使用action所有方法,否则不可以使用并给出提示。同样也可以应用才权限控制场合。

为了保持struts2自带的拦截器,使用拦截器栈

配置文件:

<package name="intercepters" namespace="/intercepter" extends="base"> 
        <interceptors>
            <interceptor name="premission" class="com.clannan.interceptor.PermissionInterceptor"/>
            <interceptor-stack name="premissionStack">
                <interceptor-ref name="defaultStack"></interceptor-ref>
                <interceptor-ref name="premission"></interceptor-ref>
            </interceptor-stack>
        </interceptors>
        <action name="intercepter_*" class="com.clannan.action.IntercepterAction" method="{1}">
           <interceptor-ref name="premissionStack"/>
           <result name="success">/WEB-INF/pages/Message.jsp</result>
       </action>
    </package>

这个拦截器的代码:

import com.opensymphony.xwork2.interceptor.Interceptor;

public class PermissionInterceptor implements Interceptor {

实现Interceptor接口

@Override
    public String intercept(ActionInvocation invocation) throws Exception {
        String user = (String)ActionContext.getContext().getSession().get("user");
        if(user!=null&&!user.equals("")){
            return invocation.invoke();
        }else{
            ActionContext.getContext().put("message", "您没有权限执行此操作!请先登录!");
        }
        return "message";
    }

return的字符串即为action中返回的字符串

 

2.包全局拦截器<default-interceptor-ref name="jsonDefaultStack"/>

包中所有action全部会被拦截,在json实现中已经被使用

 

原创粉丝点击