最近在学习ssh框架时,照着网上做了一个商城系统,之前在一些需要用户存在的操作中,都是在每一个action中写重复的代码,这样做现在想起来并不好,想起了spring的aop,于是想通过aop来给每个需要用户操作的Action验证用户登录状态。

想法是这样的:
1. 用户登录时把userId放入session中
2. 通过spring 写一个advice来获取session中的userId,判断用户登录状态,如果userId不符合,则抛出自定义异常
3. 通过struts中配置来捕获异常,跳转界面
以下是代码:
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设为0
if(id==0){
throw new UserNotFoundException();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new UserNotFoundException();
}
}
}