Adding cookie to all responses in Jersey / JAX-RS (Scala)
<p>Thought this would be a common use case but I'm coming up short.  Also, I'm using Scala but a Java answer would be fine, too.</p>

<p>In Jersey I'd like to set a simple cookie on all responses coming out of my app.</p>

<p>A quick google shows that I can set cookies on a single response by performing the following:</p>

<p><code>return Response.ok(new Viewable("/index", model))
     .cookie(new NewCookie("name", "Hello, world!"))
     .build();</code></p>

<p>That's great if I just want to set a cookie on a per-response basis, but I want it on every response.  This seems like a job for middleware.  The <a href="https://jersey.java.net/documentation/latest/filters-and-interceptors.html#10.2.1" rel="nofollow">Jersey Docs recommend this</a> for setting up middleware:</p>

<pre><code>class MyResponseMiddleware ContainerResponseFilter {
  override def filter(req: ContainerRequestContext, res: ContainerResponseContext) = {
    // do stuff here
  }  
}
</code></pre>

<p>The problem is there's no way to set a cookie on the <code>ContainerResponseContext</code> as <code>.getCookies</code> returns a read-only map, unlike <code>.getHeaders()</code> which is mutable.  </p>

<p>I also tried to create a cookie by setting the headers:</p>

<p><code>containerResponseContext.getHeaders().add(HttpHeaders.SET_COOKIE, new NewCookie(...))</code> but this did not make it to the browser.</p>

<p>It seems like if I could get a reference to <code>ServletResponse</code> or <code>HttpServletResponse</code> this would <a href="https://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/http/HttpServletResponse.html#addCookie(javax.servlet.http.Cookie)" rel="nofollow">be simple</a> but that doesn't appear to be possible in Jersey's middleware (filters).</p>

<p>This seems like a pretty straightforward use-case so I feel like I'm missing something obvious.</p>