首页 /  技术专区  /  Vert.x 宽屏模式 >

Vert.x获取请求参数——body参数

1、application/x-www-form-urlencoded和application/json的区别

        application/x-www-form-urlencoded方式是Jquery的Ajax请求默认方式,这种方式的好处就是浏览器都支持,在请求发送过程中会对数据进行序列化处理,以键值对形式。

        另外浏览器的原生 form 表单,如果不设置 enctype 属性,那么最终就会以 application/x-www-form-urlencoded 方式提交数据。

        application/json这种方式,后台发送数据的格式必须为json字符串。


2、编写BodyVerticle类

package vertx;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;

public class BodyVerticle extends AbstractVerticle {

  //第一步 声明Router
  Router router;

  @Override
  public void start(Promise<Void> startPromise) throws Exception {

    //第二步 初始化Router
    router = Router.router(vertx);

    //获取body参数,得先添加这句
    router.route().handler(BodyHandler.create());

    //第三步 配置Router解析url
    /**
     * application/x-www-form-urlencoded格式
     * 请求头中的  content-type: application/x-www-form-urlencoded
     */
    router.route("/test/form").handler(
      req -> {
        var page = req.request().getFormAttribute("page");
        req.response()
          .putHeader("content-type", "text/plain")
          .end(page);
      }
    );

    /**
     * application/json格式
     * 请求头中的 content-type: application/json
     */
    router.route("/test/json").handler(
      req -> {
        var page = req.getBodyAsJson();
        req.response()
          .putHeader("content-type", "text/plain")
          .end(page.toString());
      }
    );

    //第四步 将Router与vertx HttpServer 绑定
    vertx.createHttpServer().requestHandler(router).listen(8888, http -> {
      if (http.succeeded()) {
        startPromise.complete();
        System.out.println("HTTP server started on port 8888");
      } else {
        startPromise.fail(http.cause());
      }
    });
  }
}

3、启动并测试

application/x-www-form-urlencoded格式

image.png

application/json格式

image.png

获取json中的某一个值

/**
 * json格式
 * content-type: application/json
 */
router.route("/test/json").handler(
  req -> {
    var page = req.getBodyAsJson();
    req.response()
      .putHeader("content-type", "text/plain")
      .end(page.getValue("page").toString());
  }
);

image.png



头像
0/200
图片验证码