在简单的 vertx 路由器实现中获取空指针异常

我在Java中学习Vert.x框架。我正在尝试使用 和 创建一个简单的 API。以下是我的代码:RouterVert.x web


我的主类 - (顶点):MainVerticle.java


public class MainVerticle extends AbstractVerticle{


    final int VA_PORT = 7535;


    @Override

    public void start() throws Exception {


        // URL routers

        IController controller = new RequestController();


        Router router = Router.router(vertx);


        router.post("/vassist").handler(

                routingContext -> controller.opController(routingContext) 

        );


        vertx.createHttpServer().requestHandler(router::accept).listen(VA_PORT, asyncResult -> {


            if(asyncResult.succeeded()) {

                LOGGER.info("Verticle deployed successfully. Listening on port: " + VA_PORT);

            }

            else {

                LOGGER.error("Could not start a HTTP server", asyncResult.cause());

            }


        });

    }


    @Override

    public void stop() throws Exception {

    }


    public static void main(String[] args) {

        Vertx vertx = Vertx.vertx();


        // Deploy main verticle

        vertx.deployVerticle(new MainVerticle());

    }


}

接口 - :IController.java


public interface IController {

    public void opController(RoutingContext routingContext);

}

RequestController.java实现上述接口:


public class RequestController implements IController {


    @Override

    public void opController(RoutingContext routingContext) {

        JsonObject jso = routingContext.getBodyAsJson();

        System.out.println("Received json body as : " + jso.encodePrettily());

    }


}

上面的代码成功部署了顶点并创建了一个http服务器,但是,每当我发送带有示例体的HTTP POST时,我都会在.jsonSystem.out.println("Received json body as : " + jso.encodePrettily());RequestController.java


我的 HttpServer 实现不正确吗?请注意,我不想将 http 请求处理程序编写为 方法中的匿名函数。creatHttpServer()vertx


浮云间
浏览 197回答 3
3回答

jeck猫

问题现已修复。问题是我没有在opController方法中为收到的请求提供身体处理程序。正确的实现如下:public void opController(RoutingContext routingContext) {        routingContext.request().bodyHandler(bodyHandler -> {            JsonObject jso = bodyHandler.toJsonObject();            System.out.println("Received json body as : " + jso.encodePrettily());        });        // Complete request        routingContext.response().setStatusCode(200).end("Done!");    }

泛舟湖上清波郎朗

您可以通过定义一次BodyHandler来简化,并将body作为缓冲区,字符串,json或json数组(如波纹管)获取:public class HttpServer extends AbstractVerticle {&nbsp; &nbsp;@Override&nbsp; &nbsp;public void start(Future<Void> startFuture) {&nbsp; &nbsp; &nbsp; var router = Router.router(vertx);&nbsp; &nbsp; &nbsp; //notice here&nbsp; &nbsp; &nbsp; router.route().handler(BodyHandler.create());&nbsp; &nbsp; &nbsp; // a bonus :)&nbsp;&nbsp; &nbsp; &nbsp; router.route().handler(LoggerHandler.create(LoggerFormat.DEFAULT));&nbsp; &nbsp; &nbsp; router.post("/api/books").handler(this::getAllBooks);&nbsp; &nbsp; &nbsp; vertx.createHttpServer()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .requestHandler(router)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .listen(config().getInteger("server.port", 9000), lh -> startFuture.complete());&nbsp; &nbsp;}&nbsp; &nbsp;private void getAllBooks(RoutingContext rc) {&nbsp; &nbsp; &nbsp; // do something with the body&nbsp; &nbsp; &nbsp; JsonObject jso = rc.getBodyAsJson(); // or String body = getBodyAsString();&nbsp; &nbsp; &nbsp; System.out.println("Received json body as : " + jso.encodePrettily());&nbsp; &nbsp; &nbsp; //respond&nbsp; &nbsp; &nbsp; rc.response().setStatusCode(HttpResponseStatus.OK.code()).end("Done!");&nbsp; &nbsp;}}

动漫人物

Vertx HttpServer 将捕获路由处理程序中发生的所有异常,然后返回状态代码 = 500 的 http 响应(=“内部服务器错误”)。因此,http服务器不会因任何异常而停止。使用“try catch”来捕获异常,例如:String abc = null;try {&nbsp; &nbsp; // add your code here&nbsp; &nbsp; abc.charAt(0);&nbsp;&nbsp;} catch (Exception e) {&nbsp; &nbsp; e.printStackTrace();}处理异常的其他方法:router.route("/*").failureHandler(rc->{&nbsp; &nbsp; int statusCode = rc.statusCode();&nbsp; &nbsp; System.out.println("status code = " + statusCode );&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; rc.response().setStatusCode(statusCode).end("failureHandler here");&nbsp;&nbsp;});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java