对于网站的后台,没有经过用户登录是不允许直接访问页面的,即使直接把访问地址写全,也会因为没有登录,而跳转到登录页面。这就是简单的权限校验,如何通过struts2来实现权限的校验呢?
首先编写拦截器:
<span style="font-size:18px;">public class PrivilegeInterceptor extends MethodFilterInterceptor {
//执行拦截的方法
@Override
protected String doIntercept(ActionInvocation actionInvocation) throws Exception {
// 判断session中是否保存了后台用户的信息
AdminUser existAdminUser=(AdminUser) ServletActionContext.getRequest().getSession().getAttribute("existAdminUser");
if(existAdminUser==null){
//没有登录进行访问
ActionSupport actionSupport= (ActionSupport) actionInvocation.getAction();
actionSupport.addActionError("亲!您好没有登录,没有访问权限");
return "loginFail";
}else{
//已经登陆过
return actionInvocation.invoke();
}
}
}</span>
再配置拦截器:在struts-xml文件中进行配置,添加interceptors标签
<span style="font-size:18px;"><interceptors>
<interceptor name="PrivilegeInterceptor" class="cn.itcast.shop.interceptor.PrivilegeInterceptor"></interceptor>
</interceptors></span>
再在需要拦截的action中添加以下代码:
<span style="font-size:18px;"><interceptor-ref name="PrivilegeInterceptor"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref></span>
通过这样的配置,就可以防止后台被通过URL来访问了。