转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实现方式,项目变更的少嘛~^_^
相关文章
相关标签/搜索