Get the HttpServletRequest (request) object from Java code

后端 未结 5 682
一生所求
一生所求 2020-12-31 07:14

I need to get hold of the request object in Java code. I can\'t pass this object down to my code for certain reasons. Is there any way I can say something like: getCur

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-31 08:11

    Jon Skeet said practically everything, but one clarification to his advice "just the bits that you need" - if you need your request parameters passed down, but you don't need a dependency on HttpServletRequest, pass request.getParameterMap().

    And extending a bit on the ThreadLocal option - you can have a Filter which handles all incoming requests, and sets the request in a

    public final static ThreadLocal httpServletRequestTL =
          new ThreadLocal();
    

    Because you are setting it on each request (careful with the filter mapping), you won't have to worry about the servlet-container thread pool - you will always have the current request.

    P.S. this is the logic behind the spring utility proposed by skaffman - I join him recommending the stable component, rather than making your own.

提交回复
热议问题