简体   繁体   English

如何在JAX-RS(Jersey)中读取cookie

[英]How to read a cookie in JAX-RS (Jersey)

I followed this guide to read and create cookies but I can only read cookie that I create from the same subdomain. 我按照本指南阅读和创建cookie,但只能读取从相同子域创建的cookie。

For example if I create a cookie in http://localhost:8080/x/y/test/create I can read it from: http://localhost:8080/x/y/test/read but I cannot read it from http://localhost:8080/x/y/test2/read (Note the difference between test and test2 ) 例如,如果我在http://localhost:8080/x/y/test/create创建一个cookie,我可以从以下地址读取它: http://localhost:8080/x/y/test/read但我不能从中读取它http://localhost:8080/x/y/test2/read (请注意testtest2之间的区别)

Where is the problem? 问题出在哪儿? How could I read the cookie everywhere in my domain? 如何在我的域中到处读取Cookie?

Here is the code: 这是代码:

CLASS 1 1类

@Path("test")
public class Test {

    @GET
    @Path("/create")
    @Produces(MediaType.TEXT_PLAIN)
    public Response login() {
        NewCookie cookie = new NewCookie("name", "123");
        return Response.ok("OK").cookie(cookie).build();
    }

    @GET
    @Path("/read")
    @Produces(MediaType.TEXT_PLAIN)
    public Response foo(@CookieParam("name") String value) {
        System.out.println(value);
        if (value == null) {
            return Response.serverError().entity("ERROR").build();
        } else {
            return Response.ok(value).build();
        }
    }

}

CLASS 2 2类

@Path("test2")
public class Test2 {

    @GET
    @Path("/read")
    @Produces(MediaType.TEXT_PLAIN)
    public Response foo(@CookieParam("name") String value) {
        System.out.println(value);
        if (value == null) {
            return Response.serverError().entity("ERROR").build();
        } else {
            return Response.ok(value).build();
        }
    }
}

EDIT 编辑

The problem was at creation time. 问题出在创建时。 Now I create the cookie in this way: 现在,我以这种方式创建cookie:

NewCookie cookie = new NewCookie("name", "123", "/", "", "comment", 100, false);

It's a default behavior. 这是默认行为。 To set cookie to your domain, use another constructor for cookie, and set empty domain and root path: 要将cookie设置为您的域,请对cookie使用另一个构造函数,并设置空的域和根路径:

domain = ""
path = "/"

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

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