在顶点创建 Cookie



我想使用 vertx 创建一个简单的 cookie。

import io.vertx.core.AbstractVerticle;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.Cookie;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import java.util.Date;
public class HttpVerticle extends AbstractVerticle {
    @Override
    public void start() throws Exception {
        HttpServer server = vertx.createHttpServer();
        Router router = Router.router(vertx);
        router.route("/opt-out").handler(this::optOut);
        System.out.println("Server started @ 3000");
        server.requestHandler(router::accept).listen(3000);
    }
    public void optOut(RoutingContext context) {
        HttpServerRequest request = context.request();
        HttpServerResponse response = context.response();
        response.putHeader("content-type", "text-plain");
        response.setChunked(true);
        response.write("hellow world");
        Cookie cookie = Cookie.cookie("foo", "bar");
        context.addCookie(cookie);
        response.end();
    }
}

但是当我检查浏览器时,我没有看到带有名称"foo"的cookie,具有值"bar"。我做错了什么?

另外,我如何访问所有标记的 cookie?

这就是 Vertx 中 cookie 的设置方式。

@Override
public void start(Future<Void> future) {
    Router router = Router.router(vertx);
    router.route().handler(CookieHandler.create());
    router.get("/set-cookie").handler(this::setCookieHandler);
}

public void setCookieHandler(RoutingContext context) {
    String name = "foo";
    String value = "bar";
    long age = 158132000l; //5 years in seconds
    Cookie cookie = Cookie.cookie(name,value);
    String path = "/"; //give any suitable path
    cookie.setPath(path);
    cookie.setMaxAge(age); //if this is not there, then a session cookie is set
    context.addCookie(cookie);
    context.response().setChunked(true);
    context.response().putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
    context.response().putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET");
    context.response().write("Cookie Stamped -> " + name + " : " +value);
    context.response().end();
}

谢谢。

首先,您需要在路由器中添加一个 CookieHandler。

这是 JavaDoc for addCookie 方法:

router.route().handler(CookieHandler.create());

 

/**
* Add a cookie. This will be sent back to the client in the response. The context must have first been 
* to a {@link io.vertx.ext.web.handler.CookieHandler} for this to work.
*
* @param cookie  the cookie
* @return a reference to this, so the API can be used 
因此,使用".end()"

方法作为响应,而不是".write()"

response.end("hellow world");

最新更新