很多人都想,在一个普通类里如何才能获取系统的request或session,我也找了,但没有,就自己实现了一下,期待需要的有缘人,希望能帮到一点点。
具体如下:
实现步骤:
1.定义一个线程类,普通的:
类里最主要的就是定义了一个参数:
private static ThreadLocal<HttpServletRequest> httpRequest = new ThreadLocal<HttpServletRequest>();
另外给了set? get? remove和线程相关的三个方法;
具体如下:
Java代码??
class="star">
- public?class?SystemRequestContext?{??
- private?static?ThreadLocal<HttpServletRequest>?httpRequest?=?new?ThreadLocal<HttpServletRequest>();??
- private?static?ThreadLocal<HttpSession>?session?=?new?ThreadLocal<HttpSession>();??
- public?static?void?removeHttpSession()??
- {??
- session.remove();??
- }??
- public?static?HttpSession?getSession()?{??
- return?session.get();??
- }??
- public?static?void?setSession(HttpSession?_session)?{??
- session.set(_session);??
- }??
?2.定义一个filter,拦截所有的请求,把request装入
? SystemRequestContext
Java代码??
- public?void?doFilter(ServletRequest?req,?ServletResponse?response,??
- FilterChain?chain)?throws?IOException,?ServletException?{??
- ???? HttpServletRequest?request?=?(HttpServletRequest)req;??
- ????SystemRequestContext.setHttpRequest(request);??
- ????SystemRequestContext.setSession(request.getSession());??
- try{??
- ????? chain.doFilter(request,?response);??
- }finally{??
- ?????SystemRequestContext.removeHttpRequest();??
- ?????SystemRequestContext.removeHttpSession();??
- }??
- }??
?3.如何使用:
Java代码??
- public?class?UserModuleValidateTag?{??
- public?static?boolean?validateModule(String?module){??
- ??????? HttpServletRequest?request?=????SystemRequestContext.getHttpRequest();??
- ??????if(null!=request)??
- ????System.out.println("^_^"+request);??
- ????}??
- }??
?