2017-01-06 6 views
2

vertx를 사용하여 간단한 쿠키를 만들고 싶습니다.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"라는 이름으로 쿠키가 찍히지 않습니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?

또한 스탬프 처리 된 모든 쿠키에 액세스하려면 어떻게해야합니까?

답변

3

쿠키가 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");