這個問題很深刻啊,假如你還沒登陸,就從購物網站提交訂單,這個時候購物網站會提醒你:親,你還沒有登陸!
這個時候我們需要做的就是這麼個功能,我們怎麼實現這個代碼呢!我以SSH爲例啊。
首先我們得寫一個校驗類去檢驗session中是否有用戶的信息,我一般是把用戶信息保存到session,這樣方便後面調用。這裏其實有兩種方法,一種就是直接在需要用到用戶信息的類中,從session中取數據,進而進行一定的邏輯判斷,第二種在後面說明
第一種:
User existUser = (User) ServletActionContext.getRequest().getSession()
.getAttribute("existUser");
if(existUser == null){
addActionError("親!您還沒有登陸!請先登陸");
return "login";
}
這個是比較簡單的,邏輯也是比較清楚的,但是要是針對某一類都得進行登陸校驗,怎麼辦,每個代碼塊都加這個嘛,肯定不行,所以有了第二種
public class PrivilegeInterceptor extends MethodFilterInterceptor{
@Override
//執行攔截的方法
protected String doIntercept(ActionInvocation arg0) throws Exception {
//判斷session中是否有後臺用戶的信息
AdminUser existAdminUser = (AdminUser) ServletActionContext.getRequest().getSession()
.getAttribute("existAdminUser");
if(existAdminUser == null){
//沒有登陸
ActionSupport actionSupport = (ActionSupport) arg0.getAction();
actionSupport.addActionError("親,您還沒有他媽的登陸");
return "loginFail";
}else{
//已經登陸
return arg0.invoke();
}
}
}
這個類繼承MethodFilterInterceptor這個類,主要用於每次校驗,自行百度吧。然後吧這個配置到struts.xml文件中就可以了
<interceptors>
<interceptor name="PrivilegeInterceptor" class="校驗類的路徑地址"/>
</interceptors>
<!-- 配置首頁訪問的Action -->
<action name="index" class="indexAction">
<result name="index">/WEB-INF/jsp/index.jsp</result>
<interceptor-ref name="PrivilegeInterceptor"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</action>
正如上面代碼所示,必須在struts.xml文件中配置,這樣你每次使用到這個action的時候就會進行一次PrivilegeInterceptor類中所寫的校驗,這個說方便也方便,說不方便也不方便,關鍵看應用場景,對,適合才合適