zoukankan      html  css  js  c++  java
  • strust2自定义拦截器

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

    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中配置该拦截器,并设置一个自定义拦截器栈作为默认拦截器栈。

      <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>
  • 相关阅读:
    18寒假第一测
    P1932 A+B A-B A*B A/B A%B Problem
    POJ 2823 Sliding Window
    堆排序
    [LeetCode] Candy
    [LeetCode] Single Number II
    [LeetCode] Single Number
    [LeetCode] Binary Tree Postorder Traversal
    [LeetCode] Binary Tree Preorder Traversal
    [LeetCode] Insertion Sort List
  • 原文地址:https://www.cnblogs.com/yanqingguo/p/9827158.html
Copyright © 2011-2022 走看看