在vertx中创建cookie

时间:2017-01-06 08:30:05

标签: java cookies vert.x

我想使用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?

2 个答案:

答案 0 :(得分:4)

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

感谢。

答案 1 :(得分:0)

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

这是addCookie方法的JavaDoc:

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");