简体   繁体   中英

Adding cookie to all responses in Jersey / JAX-RS (Scala)

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.

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

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

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

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 Jersey Docs recommend this for setting up middleware:

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

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

I also tried to create a cookie by setting the headers:

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

It seems like if I could get a reference to ServletResponse or HttpServletResponse this would be simple but that doesn't appear to be possible in Jersey's middleware (filters).

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

You can simply Inject HttpServletResponse into the filter. Use @Context annotation as follows.

@Provider
public class ResponseHTTPStatusFilter implements ContainerResponseFilter{
@Context HttpServletResponse resp;
    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
       resp.addCookie(cookie);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM