[英]HttpServer Request get date range from query string
I am new to Java and Vertx and I have a query string with the following format:我是 Java 和 Vertx 的新手,我有一个具有以下格式的查询字符串:
GET /examples/1/data?date_1[gt]=2021-09-28&date_1[lt]=2021-10-28
Here I have this date_1
parameter which is within a certain range.这里我有这个
date_1
参数,它在一定范围内。 I have been using HttpServerRequest
class to extract simple parameters like integers but not sure how to proceed with these kind of range parameters.我一直在使用
HttpServerRequest
类来提取像整数这样的简单参数,但不确定如何处理这些范围参数。
With the simple parameters, I can do something like:使用简单的参数,我可以执行以下操作:
String param = request.getParam(paramName);
paramAsInteger = Integer.valueOf(paramAsString);
However, confused as to how to deal with the gt
and lt
options and the fact that we have same parameter twice.但是,对于如何处理
gt
和lt
选项以及我们两次使用相同参数的事实感到困惑。
You say that you have difficulties parsing out these tokens.你说你很难解析这些令牌。 Here's how you can handle this.
这是您可以处理的方法。
The first thing to understand is that the parameter name is NOT "date1"首先要理解的是参数名称不是“date1”
There are actually two parameters here 2.1. 2.1这里其实有两个参数。 "date_1[gt]" with a value of "2021-09-28" 2.2.
“date_1[gt]”,值为“2021-09-28” 2.2。 "date_1[lt]" with a value of "2021-10-28"
“date_1[lt]”,值为“2021-10-28”
This is because in the URI parameter definition everything before the "=" sign is the parameter name and everything after is the parameter value.这是因为在 URI 参数定义中,“=”符号之前的所有内容都是参数名称,之后的所有内容都是参数值。
You can just do你可以做
String dateAsString = request.getParam("date1[gt]");
paramAsInteger = toDate(dateAsString)
Vert.x will treat these parameters as two separate ones. Vert.x 会将这些参数视为两个独立的参数。 So
RoutingContext#queryParam("date_1[gt]")
will only give you the value for [gt]
.所以
RoutingContext#queryParam("date_1[gt]")
只会给你[gt]
的值。 If you want the value for [lt]
you need to get that separately.如果您想要
[lt]
的值,则需要单独获取。
That being said, you can move this tedious logic into an extra handler and store the values in the RoutingContext
.话虽如此,您可以将这个乏味的逻辑移到额外的处理程序中,并将值存储在
RoutingContext
。 Something like this might be easier:像这样的事情可能更容易:
private void extractDates(RoutingContext ctx) {
var startDate = ctx.queryParam("date_1[gt]");
var endDate = ctx.queryParam("date_1[lt]");
var parsedStartDate = DateTimeFormatter.ISO_LOCAL_DATE.parse(startDate.get(0));
var parsedEndDate = DateTimeFormatter.ISO_LOCAL_DATE.parse(endDate.get(0));
// things we put in the context here can be retrieved by later handlers
ctx.put("startDate", parsedStartDate);
ctx.put("endDate", parsedEndDate);
ctx.next();
}
Then, in your actual handler you can access the two dates as follows:然后,在您的实际处理程序中,您可以按如下方式访问这两个日期:
router.get("/date")
.handler(this::extractDates)
.handler(ctx -> {
var responseBody = ctx.get("startDate") + " - " + ctx.get("endDate");
ctx.end(responseBody);
});
This allows you to keep your actual business logic concise.这允许您保持实际业务逻辑简洁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.