Question

I'm helping maintain an app where we use DropWizard, which is nice.

I'd like to set a cookie, and return the view still.

I see people mentioning this approach:

Response r = javax.ws.rs.core.Response.ok().cookie(COOKIE_HERE).entity(view).build();

return r;

but to get that to work you have to return the "Response" object, and not the view.

Is there anyway to do this and be able to return a view instead of a response? I know I can use the HttpServletResponse to set the cookie, but I'd prefer to do it with the view or response object if possible to avoid extra context.

Was it helpful?

Solution

Does this fits your requirements (with io.dropwizard 0.7.1):

@GET
@ExceptionMetered
@Path("/path")
@Produces(MediaType.TEXT_HTML)
public Response demoSetCookie()
{
    Cookie cookie = new Cookie("testNameCookie", "testValueCookie");
    NewCookie cookies = new NewCookie(cookie);
    return Response.status(Status.OK).type(MediaType.TEXT_HTML).entity(view).cookie(cookies)
                    .build();
}

OTHER TIPS

Just thought I'd add another option to the list - as I think it's slightly cleaner...

@GET
@ExceptionMetered
@Path("/path")
@Produces(MediaType.TEXT_HTML)
public Response demoSetCookie(@Context HttpServletResponse response)
{
    Cookie cookie = new Cookie("cookiemonster", "wannacookie");
    response.addCookie(cookie);
    return new MyViewResource();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top