strust2自定义拦截器

1.建立一个拦截器类,继承MethodFilterInterceptor类,实现doIntercept方法java

package com.yqg.bos.web.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
import com.yqg.bos.entity.User;
import com.yqg.bos.utils.CommonUtils;

public class BosInterceptor extends MethodFilterInterceptor{

    //该拦截器功能为若是session中的用户为空,跳转到登陆界面。
    protected String doIntercept(ActionInvocation invocation) throws Exception {
       User user =  CommonUtils.getLoginUser();
       if(user == null) {
//若是user为空,跳回login.jsp界面,不然放行
return "login"; }else { return invocation.invoke(); } } }

package com.yqg.bos.utils;

import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;

import com.yqg.bos.entity.User;

public class CommonUtils {
      public static HttpSession getSession() {
          return ServletActionContext.getRequest().getSession();
      }
      
      public static User getLoginUser() {
          return (User) getSession().getAttribute("loginUser");
      }
}

2.在struts.xml中配置该拦截器,并设置一个自定义拦截器栈做为默认拦截器栈。web

  <interceptors>
<!--将自定义的拦截器注册到struts中--> <interceptor name="bosInterceptor" class="com.yqg.bos.web.interceptor.BosInterceptor">
<!--除login方法以外的全部方法都被拦截--> <param name = "excludeMethods">login</param> </interceptor>
<!--自定义拦截器栈,并将自定义拦截器加入到栈中,还将struts默认的拦截器栈加入到自定义拦截器栈中--> <interceptor-stack name="myStack"> <interceptor-ref name="bosInterceptor"></interceptor-ref> <interceptor-ref name="defaultStack"></interceptor-ref> </interceptor-stack> </interceptors>
<!--设置自定义拦截器栈为默认拦截器栈取代struts的默认拦截器栈defaultStack--> <default-interceptor-ref name="myStack" /> <!--定义拦截结果--> <global-results> <result name="login">/login.jsp</result> </global-results>
相关文章
相关标签/搜索