简体   繁体   English

我如何从启用pox的jax-rs / rest-easy启用方法返回cookie

[英]How do I return a cookie from a jax-rs / rest-easy enabled method that returns a pojo

I have to make a change to a javax-rs web app written by someone else. 我必须更改其他人编写的javax-rs网络应用程序。 I am used to doing things the long winded way, and the javax-rs is new to me.The function currently looks like this: 我习惯于长久以来做事,而javax-rs对我来说是新手。该函数当前如下所示:

@POST
@Path("mypath1/mypath2")
@Consumes("application/json")
@Produces("application/json")
public A myMethod(B myB, @Context final HttpServletResponse response)
{
    A myA = new A();
    ...
    return myA;
}

A is just a pojo, but I guess it is getting converted to JSON at some point in the process. A只是一个pojo,但我想它会在过程中的某个时刻转换为JSON。

One thing I should add is that rest-easy framework is involved. 我要补充的一件事是涉及到轻松框架。 I guess that is what's doing the pojo to JSON conversion. 我想这就是从pojo到JSON转换的过程。

I need to check for a cookie and take a certain action if it is found. 我需要检查cookie,如果找到它,请采取某种措施。 I also want to return a cookie if the request did not have one. 如果请求中没有一个cookie,我也想返回一个cookie。 Reading of the cookie seems easy enough - just add this to the method signature: 读取cookie似乎很容易-只需将其添加到方法签名中即可:

@CookieParam("mycookiekey") String mycookieValue

My confusion is that the examples I see on the web show methods returning a Response, but this one returns a pojo - so how do I get the cookie into the response? 我的困惑是,我在网络上看到的示例显示方法返回一个Response,但是此示例返回一个pojo-那么如何将cookie放入响应中? I thought I could just do response.addCookie(...) [where response is the HttpServletResponse passed to the method] as I would do in my normal long-winded way, but I also see on the web that the way to return a cookie in javax-rs is a little different, so I thought I should maybe be doing something like this: 我以为我可以像通常的long回方式那样做response.addCookie(...)[其中,响应是传递给该方法的HttpServletResponse],但我在网上也看到返回a的方法javax-rs中的cookie有点不同,所以我认为我应该做这样的事情:

NewCookie newCookie = new NewCookie("mycookiekey", "mycookieValue");
ResponseBuilder builder = Response.ok(myA, MediaType.APPLICATION_JSON);
Response r = builder.cookie(newCookie).build();
return r;

but that is returning a Response, and whatever invokes the method is clearly expecting an object of type A to be returned. 但这将返回一个Response,并且无论调用哪种方法,显然都希望返回类型为A的对象。

So I guess my question is, can I still return an object of type A from the method and yet have the cookie returned to the client? 所以我想我的问题是,我是否仍可以从方法中返回类型A的对象,但仍将cookie返回给客户端?

Thanks, 谢谢,

Paul 保罗

It's OK to return Response instead of actual entity, because the JSON it's converted to will be the same in both cases in the HTTP response, although in first case it is converted implicitly, while in 2nd you do it manually. 可以返回Response而不是实际实体,这是可以的,因为在两种情况下,转换为JSON的JSON在HTTP响应中都是相同的,尽管在第一种情况下,它是隐式转换的,而在第二种情况下,您需要手动进行转换。 So your snippet is correct, I believe. 我相信您的摘要是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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