• 转Struts 权限控制


    权限最核心的是业务逻辑,具体用什么技术来实现就简单得多。 
    通常:用户与角色建立多对多关系,角色与业务模块构成多对多关系,权限管理在后者关系中。 
    对权限的拦截,如果系统请求量大,可以用Struts2拦截器来做,请求量小可以放在filter中。但一般单级拦截还不够,要做到更细粒度的权限控制,还需要多级拦截。
    
        不大理解filter(过滤器)和interceptor(拦截器)的区别,遂google之。
    
    1、拦截器是基于java的反射机制的,而过滤器是基于函数回调 。 
    2、过滤器依赖与servlet容器,而拦截器不依赖与servlet容器 。 
    3、拦截器只能对action请求起作用,而过滤器则可以对几乎所有的请求 起作用 。 
    4、拦截器可以访问action上下文、值栈里的对象,而过滤器不能 。 
    5、在action的生命周期中,拦截器可以多次被调用,而过滤器只能在容 器初始化时被调用一次 。
    
        为了学习决定把两种实现方式都试一下,然后再决定使用哪个。
    
    权限验证的Filter实现:
    
    web.xml代码片段
    
      <!-- authority filter 最好加在Struts2的Filter前面-->
      <filter>
        <filter-name>SessionInvalidate</filter-name>
        <filter-class>filter.SessionCheckFilter</filter-class>
        <init-param>
          <param-name>checkSessionKey</param-name>
          <param-value>loginName</param-value>
        </init-param>
        <init-param>
          <param-name>redirectURL</param-name>
          <param-value>/entpLogin.jsp</param-value>
        </init-param>
        <init-param>
          <param-name>notCheckURLList</param-name>
          <param-value>/entpLogin.jsp,/rois/loginEntp.action,/entpRegister.jsp,/test.jsp,/rois/registerEntp.action</param-value>
        </init-param>
      </filter>
      <!--过滤/rois命名空间下所有action  -->
      <filter-mapping>
        <filter-name>SessionInvalidate</filter-name>
        <url-pattern>/rois/*</url-pattern>
      </filter-mapping>
      <!--过滤/jsp文件夹下所有jsp  -->
      <filter-mapping>
        <filter-name>SessionInvalidate</filter-name>
        <url-pattern>/jsp/*</url-pattern>
      </filter-mapping>
    SessionCheckFilter.java代码
    
    package filter;
    import java.io.IOException;
    import java.util.HashSet;
    import java.util.Set;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    /**
     * 用于检测用户是否登陆的过滤器,如果未登录,则重定向到指的登录页面 配置参数 checkSessionKey 需检查的在 Session 中保存的关键字
     * redirectURL 如果用户未登录,则重定向到指定的页面,URL不包括 ContextPath notCheckURLList
     * 不做检查的URL列表,以分号分开,并且 URL 中不包括 ContextPath
     */
    public class SessionCheckFilter implements Filter {
      protected FilterConfig filterConfig = null;
      private String redirectURL = null;
      private Set<String> notCheckURLList = new HashSet<String>();
      private String sessionKey = null;
      @Override
      public void destroy() {
        notCheckURLList.clear();
      }
      @Override
      public void doFilter(ServletRequest servletRequest,
          ServletResponse servletResponse, FilterChain filterChain)
          throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        if (sessionKey == null) {
          filterChain.doFilter(request, response);
          return;
        }
        if ((!checkRequestURIIntNotFilterList(request))
            && session.getAttribute(sessionKey) == null) {
          response.sendRedirect(request.getContextPath() + redirectURL);
          return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
      }
      private boolean checkRequestURIIntNotFilterList(HttpServletRequest request) {
        String uri = request.getServletPath()
            + (request.getPathInfo() == null ? "" : request.getPathInfo());
        String temp = request.getRequestURI();
        temp = temp.substring(request.getContextPath().length() + 1);
        // System.out.println("是否包括:"+uri+";"+notCheckURLList+"=="+notCheckURLList.contains(uri));
        return notCheckURLList.contains(uri);
      }
      @Override
      public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        redirectURL = filterConfig.getInitParameter("redirectURL");
        sessionKey = filterConfig.getInitParameter("checkSessionKey");
        String notCheckURLListStr = filterConfig
            .getInitParameter("notCheckURLList");
        if (notCheckURLListStr != null) {
          System.out.println(notCheckURLListStr);
          String[] params = notCheckURLListStr.split(",");
          for (int i = 0; i < params.length; i++) {
            notCheckURLList.add(params[i].trim());
          }
        }
      }
    }
     
    
    权限验证的Interceptor实现:
    
       使用Interceptor不需要更改web.xml,只需要对struts.xml进行配置
    
    struts.xml片段
    
    <!-- 用户拦截器定义在该元素下 -->
        <interceptors>
          <!-- 定义了一个名为authority的拦截器 -->
          <interceptor name="authenticationInterceptor" class="interceptor.AuthInterceptor" />
          <interceptor-stack name="defualtSecurityStackWithAuthentication">
            <interceptor-ref name="defaultStack" />
            <interceptor-ref name="authenticationInterceptor" />
          </interceptor-stack>
        </interceptors>
        <default-interceptor-ref name="defualtSecurityStackWithAuthentication" />
        <!-- 全局Result -->
        <global-results>
          <result name="error">/error.jsp</result>
          <result name="login">/Login.jsp</result>
        </global-results>
        <action name="login" class="action.LoginAction">
          <param name="withoutAuthentication">true</param>
          <result name="success">/WEB-INF/jsp/welcome.jsp</result>
          <result name="input">/Login.jsp</result>
        </action>
        <action name="viewBook" class="action.ViewBookAction">
            <result name="sucess">/WEB-INF/viewBook.jsp</result>
        </action>
     
    
    AuthInterceptor.java代码
    
    package interceptor;
    import java.util.Map;
    import com.opensymphony.xwork2.Action;
    import com.opensymphony.xwork2.ActionContext;
    import com.opensymphony.xwork2.ActionInvocation;
    import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
    public class AuthInterceptor extends AbstractInterceptor {
      private static final long serialVersionUID = -5114658085937727056L;
      private String sessionKey="loginName";
      private String parmKey="withoutAuthentication";
      private boolean excluded;
      @Override
      public String intercept(ActionInvocation invocation) throws Exception {
        
        ActionContext ac=invocation.getInvocationContext();
        Map<?, ?> session =ac.getSession();
        String parm=(String) ac.getParameters().get(parmKey);
        
        if(parm!=null){
          excluded=parm.toUpperCase().equals("TRUE");
        }
        
        String user=(String)session.get(sessionKey);
        if(excluded || user!=null){
          return invocation.invoke();
        }
        ac.put("tip", "您还没有登录!");
        //直接返回 login 的逻辑视图  
            return Action.LOGIN; 
      }
    }
     
    
    使用自定义的default-interceptor的话有需要注意几点:
    
    1.一定要引用一下Sturts2自带defaultStack。否则会用不了Struts2自带的拦截器。
    
    2.一旦在某个包下定义了上面的默认拦截器栈,在该包下的所有 Action 都会自动增加权限检查功能。所以有可能会出现永远登录不了的情况。
    
    解决方案:
    
    1.像上面的代码一样,在action里面增加一个参数表明不需要验证,然后在interceptor实现类里面检查是否不需要验证
    
    2.将那些不需要使用权限控制的 Action 定义在另一个包中,这个新的包中依然使用 Struts 2 原有的默认拦截器栈,将不会有权限控制功能。
    
    3.Interceptor是针对action的拦截,如果知道jsp地址的话在URL栏直接输入JSP的地址,那么权限验证是没有效果滴!
    
    解决方案:把所有page代码(jsp)放到WEB-INF下面,这个目录下的东西是“看不见”的
    
    最后我项目里还是使用的filter实现方式,项目变动的少嘛~^_^
  • 相关阅读:
    nodejs gulp如何获取参数
    nodejs 获取当前路径的方法
    gulp 如何排除文件和文件夹
    小技巧css解决移动端ios不兼容position:fixed属性,无需插件
    代码协议相关
    zen-coding
    directive 实例讲解
    angular api 地址
    一步一步搭建hibernate4+ spring+ struts2
    华为荣耀6 H60-L02/L12(联通版)救砖包【适用于无限重启】
  • 原文地址:https://www.cnblogs.com/zuiyirenjian/p/4032101.html
Copyright © 2020-2023  润新知