strust2自定义interceptor的基本方法及操作

需求:制作一个网站需要用户登陆后才能查看,即一个权限的问题

  1.首先明确在用户没登陆前有两个Action请求是可以通过的,即注册和登陆。

  2.创建拦截器,如UserLoginInterceptor.java,如下

public class UserLoginInterceptor extends AbstractInterceptor {

    @Override
    public String intercept(ActionInvocation arg0) throws Exception {
        Action action = (Action) arg0.getAction() ;
        //放行这两种Action请求
        if(action instanceof RegisterAction||action instanceof LoginAction){
            return arg0.invoke() ;
        }else{
            //获取session有没有用户?
            User user = (User) arg0.getInvocationContext().getSession().get("user") ;
            if(user==null){
                //若没有,则想页面传达错误的消息
                arg0.getInvocationContext().getSession().put("noLand", "您没有权限,请先注册或登录!");
                return "input" ;
            }else{
                //若有则放行
                return arg0.invoke() ;
            }
        }
    }

}

  3.拦截器写好后要在struts.xml中配置

     <interceptors>
       <!-- 配置已写好的拦截器 -->
            <interceptor name="userLogin" class="com.blog.interceptor.UserLoginInterceptor"/>
       <!-- 定义自己的拦截器栈,由struts2自己的拦截器栈和前面的拦截器组成 -->
            <interceptor-stack name="blogStack">
                <interceptor-ref name="userLogin"/>
                <interceptor-ref name="defaultStack"/>
            </interceptor-stack>
        </interceptors>
     <!-- 将自定义的拦截器栈设为默认栈 -->
        <default-interceptor-ref name="blogStack"/>

  4.在无权限跳转页面上显示session中自己放入的提醒信息。

原文地址:https://www.cnblogs.com/hfblogs/p/5347573.html