用过acegi的都知道acegi的用户登陆信息(用户id 角色)等放在threadLocal中
下面是自己土制的threadLocal 比acegi的简单很多,更容易明白它的原理
用过OpenSessionInView的就不用看了,原理完全一样
下面给出关键代码
//安全上下文,保存用户登陆数据
public class SecurityContext {
public final static String SECURITY_CONTEXT_KEY = "cn.lottery.sale.security.securityContext";
private Long userId;
private String username;
private List<String> roles = new ArrayList<String>();
}
LoginAction中的login方法
public String login(){
SecurityContext sc = new SecurityContext();
sc.setUsername(username);
getRequest().getSession().setAttribute(SecurityContext.SECURITY_CONTEXT_KEY, sc);
return SUCCESS;
}
//安全过滤器。绑定session中用户信息到threadLocal
public class SecurityFilter implements Filter {
private final static Logger logger = LoggerFactory.getLogger(SecurityFilter.class);
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request;
HttpSession session = req.getSession();
if(session != null){
SecurityContext context = (SecurityContext)session.getAttribute(SecurityContext.SECURITY_CONTEXT_KEY);
logger.debug("绑定用户信息到线程" + Thread.currentThread().getId());
SecurityContextHolder.set(context);
}
try{
chain.doFilter(request, response);
}finally{
logger.debug("删除绑定到当前线程的用户信息" + Thread.currentThread().getId());
SecurityContextHolder.remove();
}
}
}
//逻辑类
public class LotteryManager {
private final static Logger logger = LoggerFactory.getLogger(LotteryManager.class);
private LotteryDAO lotteryDAO;
@Transactional(readOnly = true)
public List<Lottery> findLotteryByName(String lotteryName){
logger.debug( SecurityContextHolder.get().getUsername() ); //看这儿啦 获取用户名。省去传递参数哪么麻烦
return lotteryDAO.findByProperty("shortName", lotteryName);
}
}