Spring Mvc 在非controller层 实现获取request对象

一般我们在Controller层,会编写类似这样的方法

 


  @Controller
  @RequestMapping(value="/detail")

  public class GetURIDetailController {

    @SystemControllerLog(description = "id")    
    @RequestMapping(value="/{id}",method={RequestMethod.GET})
    public ModelAndView getDetailID(
    @PathVariable("id")
    Integer id
   ,HttpServletRequest request){ ModelAndView modelAndView
= new ModelAndView();
    //someting request对象方法的调用 modelAndView.addObject(
"id",id); modelAndView.setViewName("detail"); return modelAndView; } }

本质上Controller就是一个spring 组件,所以在我的请求方法 getDetailID中,可以添加一个HttpServletRequest获得当前请求的request对象,

request对象中包含了 用户ID session 以及等等信息

-------------------------------------------------------------

假设我们要编写一个AOP拦截Controller实现我们的切点事务时候,这个时候 

RequestContextHolder这个静态类就派上用处了,
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();  

 


private static final ThreadLocal<RequestAttributes> requestAttributesHolder =
  new NamedThreadLocal<RequestAttributes>("Request attributes");//NamedThreadLocal 线程本地



public
static RequestAttributes getRequestAttributes() { RequestAttributes attributes = requestAttributesHolder.get();//获得线程本地request对象 if (attributes == null) { attributes = inheritableRequestAttributesHolder.get();// } return attributes; }
我阅读了一下Spring的源代码,它获得的是当前请求的request对象

这样设计LOG系统的时候,可以直接从Request对象当中读取用户的Cookies跟Session,完成LOG的记录。

这里有一个 小问题要补充的是,
<listener>
  <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
 </listener>

web.xml中要加入这个listen,这样在发起请求的时候 才会在线程本地中绑定 request对象

 

posted on 2016-09-19 07:33  winters86  阅读(941)  评论(0编辑  收藏  举报