(转载)spring AOP获得session

由于Spring 的AOP面向切面编程,与Servlet容器没有任何关联,所以想要获得Session会话比较麻烦。
当然Struts2同样不依赖Servlet容器,可以在Spring AOP中可以使用com.opensymphony.xwork2.ActionContext,就可以获得Session。
但是在Servlet中或struts1中,可以通过ThreadLocal方式将session保存,Spring AOP中获得Session对象。

//这个是保存request和session的类
public class SysContent {
private static ThreadLocal<HttpServletRequest> requestLocal = new ThreadLocal<HttpServletRequest>();
private static ThreadLocal<HttpServletResponse> responseLocal = new ThreadLocal<HttpServletResponse>();

public static HttpServletRequest getRequest() {
return (HttpServletRequest) requestLocal.get();
}

public static void setRequest(HttpServletRequest request) {
requestLocal.set(request);
}

public static HttpServletResponse getResponse() {
return (HttpServletResponse) responseLocal.get();
}

public static void setResponse(HttpServletResponse response) {
responseLocal.set(response);
}

public static HttpSession getSession() {
return (HttpSession) ((HttpServletRequest) requestLocal.get())
.getSession();
}
}

//这个是配置的过滤器
public class GetContent implements Filter {
@Override
public void destroy() {
// TODO Auto-generated method stub
}

@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
SysContent.setRequest((HttpServletRequest) arg0);
SysContent.setResponse((HttpServletResponse) arg1);
arg2.doFilter(arg0, arg1);
}

@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}

//使用AOP进行环绕通知切入所有com.aptech.service包下的所有类的方法
@Aspect
public Class AopTest{
@Around(value="execution(* com.aptech.service.*.*(..))")
public void aroundTest(ProceedingJoinPoint pj) throws Exception {
HttpServletRequest request = SysContent.getRequest();
HttpServletResponse response = SysContent.getResponse();
HttpSession session = SysContent.getSession();
//其他操作
if(true){
pj.proceed();
}
throw new Exception("您没有该权限");
}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值