質問

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.

役に立ちましたか?

解決

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();
}

他のヒント

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();
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top