我是Vert.x的新手,但是作为Java开发人员(非常努力),与NodeJS或其他任何基于Reactor的框架/库相比,我觉得它更加有趣并且很有前途。 因此,我正在使用Vert.x实现一个非常简单的Restful API。
今天的问题是我想在大多数(所有)响应中包含某些HttpHeaders。 例如,将Content-type设置为“ application / json”。 将来可能还会添加其他一些。
我有点想知道自己是Vert.x的新手,然后我才意识到, 本博客文章 (请参见BodyHandler的使用)最终提出的建议实际上对我有用 。
所以我有我的主要VertxMain
java应用程序,在其中注册了MyWebVerticleApp
。
package com.javapapo.vertxweb;import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;/*** Created by <a href="mailto:javapapo@mac.com">javapapo</a> on 15/11/15.*/
public class VertxEngineMain {public static void main(String[] args) {VertxOptions opts = new VertxOptions();Vertx vertx = Vertx.vertx(opts);vertx.deployVerticle(new MyWebVerticleApp());}}
然后,我创建了一个小的处理程序,称为BaseResponseHandler
,该处理程序最终在响应中添加了HttpHeader
。
package com.javapapo.vertxweb.handlers;import io.netty.handler.codec.http.HttpResponse;
import io.vertx.core.Handler;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.RoutingContext;/*** Created by <a href="mailto:javapapo@mac.com">javapapo</a> on 27/11/15.*/
public class BaseResponseHandler implements Handler<RoutingContext>{@Overridepublic void handle(RoutingContext context) {HttpServerResponse response = context.response();response.putHeader(HttpHeaders.CONTENT_TYPE.toString(), "application/json");//other stuff!response.setChunked(true);context.next();}}
然后,在MyWebVerticle
我只是在路由器链接中注册要一直调用的处理程序。
package com.javapapo.vertxweb;import com.javapapo.vertxweb.handlers.BaseResponseHandler;
import com.javapapo.vertxweb.handlers.StatusHandler;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.ext.web.Route;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;/*** Created by <a href="mailto:javapapo@mac.com">javapapo</a> on 16/11/15.*/
public class MyWebVerticleApp extends AbstractVerticle {@Overridepublic void start(Future<Void> fut) {HttpServer server = vertx.createHttpServer();Router router = Router.router(vertx);//enable the base response handler overall!router.route().handler(new BaseResponseHandler());router.route("/status/").handler(new StatusHandler());server.requestHandler(router::accept).listen(8080);}
}
翻译自: https://www.javacodegeeks.com/2015/11/setting-basic-response-http-headers-rest-resources-simple-vertx-rest-based-app.html