gpt4 book ai didi

java - 在 vertx 中创建 cookie

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:04:29 26 4
gpt4 key购买 nike

我想使用 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”且值为“bar”的 cookie。我做错了什么?

另外,我怎样才能访问所有标记的 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();
}

谢谢。

关于java - 在 vertx 中创建 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41501765/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com