Quantcast
Channel: IT社区推荐资讯 - ITIndex.net
Viewing all articles
Browse latest Browse all 11804

使用spring AOP获得session的思路

$
0
0

由于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("您没有该权限");
    } 
}

Viewing all articles
Browse latest Browse all 11804

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>