您的位置:首页 > 编程语言 > Java开发

struts2 角色权限 filter(过滤器)和interceptor(拦截器)

2012-12-15 20:09 453 查看
之前的Struts2项目通过再Sitemesh的母版页中使用Struts的if标签进行了session判断,使得未登录的用户不能看到页面,但是这 种现仅仅在view层进行,如果未登录用户直接在地址栏输入登录用户才能访问的地址,那么相应的action还是会执行,仅仅是不让用户看到罢了。这样显 然是不好的,所以研究了一下Struts2的权限验证。Here i quote

权限最核心的是业务逻辑,具体用什么技术来实现就简单得多。 

通常:用户与角色建立多对多关系,角色与业务模块构成多对多关系,权限管理在后者关系中。 

对权限的拦截,如果系统请求量大,可以用Struts2拦截器来做,请求量小可以放在filter中。但一般单级拦截还不够,要做到更细粒度的权限控制,还需要多级拦截。

    不大理解filter(过滤器)和interceptor(拦截器)的区别,遂google之。[2]博文中有介绍:

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下面,这个目录下的东西是“看不见”的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: