十年網(wǎng)站開發(fā)經(jīng)驗 + 多家企業(yè)客戶 + 靠譜的建站團隊
量身定制 + 運營維護+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
最近在學(xué)習(xí)ssh框架時,照著網(wǎng)上做了一個商城系統(tǒng),之前在一些需要用戶存在的操作中,都是在每一個action中寫重復(fù)的代碼,這樣做現(xiàn)在想起來并不好,想起了spring的aop,于是想通過aop來給每個需要用戶操作的Action驗證用戶登錄狀態(tài)。
想法是這樣的:
1. 用戶登錄時把userId放入session中
2. 通過spring 寫一個advice來獲取session中的userId,判斷用戶登錄狀態(tài),如果userId不符合,則拋出自定義異常
3. 通過struts中配置來捕獲異常,跳轉(zhuǎn)界面
以下是代碼:
advice代碼:
public class IsUserLoginAdvice{ public void isUserLogin() throws UserNotFoundException{ // TODO Auto-generated method stub int id=0; Map sessionMap=ActionContext.getContext().getSession(); System.out.println(sessionMap); try { //這里在一開始時userId是不存在的可能會拋出NullPointException,catch起來 id=(int) sessionMap.get("userId"); //在用戶注銷時我把session中的userId設(shè)為0 if(id==0){ throw new UserNotFoundException(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); throw new UserNotFoundException(); } } }