运用Spring AOP验证用户权限实例
来源: 框架 Spring | 作者: ITeduer | 发布: 2008-12-26 00:00
5.建登陆与注销管理类SecurityManager:
package aop.secure;
public class SecurityManager {
private static ThreadLocal local = new ThreadLocal();
public void login(String userName, String password){
local.set(new UserInfo(userName,password));
}
public void logout(){
local.set(null);
}
public UserInfo getLoggedOnUser(){
return (UserInfo)local.get();
}
}
6.最后建测试类SecurityExample:
package aop.secure;
import org.springframework.aop.framework.ProxyFactory;
public class SecurityExample {
private static SecureBean getSecureBean(){
SecureBean sbean = new SecureBean();
SecurityAdvice sadvice = new SecurityAdvice();
ProxyFactory pf = new ProxyFactory();
pf.setTarget(sbean);
pf.addAdvice(sadvice);
SecureBean factory = (SecureBean)pf.getProxy();
return factory;
}
public static void main(String[] args) {
SecurityManager mgr = new SecurityManager();
SecureBean sbean = getSecureBean();
mgr.login("chigo","chigo");
sbean.writeSecureMessage();
mgr.logout();
try{
mgr.login("kkk","");
sbean.writeSecureMessage();
}catch(SecurityException ex){
System.out.println("Exception caught: " + ex.getMessage());
}finally{
mgr.logout();
}
try{
sbean.writeSecureMessage();
}catch(SecurityException ex){
System.out.println("Exception caught: " + ex.getMessage());
}
}
}
