2017-01-06 7 views
2

私は、単純なクッキーをvertexを使って作成したいと思っています。vertxでクッキーを作成する

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

しかし、私はブラウザをチェックするとき、私は、値「bar」を持つ、「foo」という名前でスタンプクッキーを見ていません。私は間違って何をしていますか?

また、どのようにスタンプされているすべてのCookieにアクセスできますか?

答えて

3

これは、CookieがVertxで設定される方法です。

@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(); 
} 

ありがとうございます。

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"); 
関連する問題