對於網站的後臺,沒有經過用戶登錄是不允許直接訪問頁面的,即使直接把訪問地址寫全,也會因爲沒有登錄,而跳轉到登錄頁面。這就是簡單的權限校驗,如何通過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來訪問了。