Is there any way to read cookies from the response object in Java?

后端 未结 4 1874
梦谈多话
梦谈多话 2020-12-29 05:55

It doesn\'t seem that HttpServletResponse exposes any methods to do this.

Right now, I\'m adding a bunch of logging code to a crufty and ill-understood servlet, in

4条回答
  •  独厮守ぢ
    2020-12-29 06:41

    I had the same problem where I was using a 3rd party library which accepts an HttpServletResponse and I needed to read back the cookies that it set on my response object. To solve that I created an HttpServletResponseWrapper extension which exposes these cookies for me after I make the call:

    public class CookieAwareHttpServletResponse extends HttpServletResponseWrapper {
    
        private List cookies = new ArrayList();
    
        public CookieAwareHttpServletResponse (HttpServletResponse aResponse) {
            super (aResponse);
        }
    
        @Override
        public void addCookie (Cookie aCookie) {
            cookies.add (aCookie);
            super.addCookie(aCookie);
        }
    
        public List getCookies () {
            return Collections.unmodifiableList (cookies);
        }
    
    } 
    

    And the way I use it:

    // wrap the response object
    CookieAwareHttpServletResponse response = new CookieAwareHttpServletResponse(aResponse);
    
    // make the call to the 3rd party library 
    String order = orderService.getOrder (aRequest, response, String.class);
    
    // get the list of cookies set
    List cookies = response.getCookies();
    

提交回复
热议问题