gwt + spring通过aop记录日志获取request、session
由于Spring的AOP面向切面编程,与Servlet容器没有任何关联,所以想要获得Session会话比较麻烦。
当然Struts2同样不依赖Servlet容器,可以在SpringAOP中可以使用com.opensymphony.xwork2.ActionContext,就可以获得Session。
但是在Servlet中或struts1中,可以通过ThreadLocal方式将session保存,SpringAOP中获得Session对象。
具体思路和代码:
这个是保存request和session的类
/**
*
*@author株洲健坤北大青鸟周钢
*
*/
publicclassSysContent{
privatestaticThreadLocal<HttpServletRequest>requestLocal=newThreadLocal<HttpServletRequest>();
privatestaticThreadLocal<HttpServletResponse>responseLocal=newThreadLocal<HttpServletResponse>();
publicstaticHttpServletRequestgetRequest(){
return(HttpServletRequest)requestLocal.get();
}
publicstaticvoidsetRequest(HttpServletRequestrequest){
requestLocal.set(request);
}
publicstaticHttpServletResponsegetResponse(){
return(HttpServletResponse)responseLocal.get();
}
publicstaticvoidsetResponse(HttpServletResponseresponse){
responseLocal.set(response);
}
publicstaticHttpSessiongetSession(){
return(HttpSession)((HttpServletRequest)requestLocal.get()).getSession();
}
}
这个是配置的过滤器
/**
*
*@author株洲健坤北大青鸟周钢
*
*/
publicclassGetContentimplementsFilter{
@Override
publicvoiddestroy(){
//TODOAuto-generatedmethodstub
}
@Override
publicvoiddoFilter(ServletRequestarg0,ServletResponsearg1,
FilterChainarg2)throwsIOException,ServletException{
SysContent.setRequest((HttpServletRequest)arg0);
SysContent.setResponse((HttpServletResponse)arg1);
arg2.doFilter(arg0,arg1);
}
@Override
publicvoidinit(FilterConfigarg0)throwsServletException{
//TODOAuto-generatedmethodstub
}
}
使用AOP进行环绕通知切入所有com.aptech.service包下的所有类的方法
/**
*@author株洲健坤北大青鸟周钢
*/
@Aspect
publicClassAopTest{
@Around(value="execution(*com.aptech.service.*.*(..))")
publicvoidaroundTest(ProceedingJoinPointpj)throwsException{
HttpServletRequestrequest=SysContent.getRequest();
HttpServletResponseresponse=SysContent.getResponse();
HttpSessionsession=SysContent.getSession();
//其他操作
if(true){
pj.proceed();
}
thrownewException("您没有该权限");
}
}
//原文地址:http://zg770423.blog.163.com/blog/static/13826688820112275259181/