英文:
SparkJava - Case sensitive endpoints
问题
我有一段使用 SparkJava(http://sparkjava.com/)的 Java 代码,用于提供 HTTP 端点。
端点的生成方式如下:
get("/xxx/yyy", (request, response) -> {
...
return SOMETHING_TO_RETURN;
});
采用这种方式,我遇到了一个问题:
假设我定义了一个端点:'/api/status/car',
但是用户有时会调用 '/api/status/**CAR**'。问题出在这种情况下 URL 的大小写敏感性上。
现在我必须解决这个问题:**使其不区分大小写。**
我已经查看了过滤器(例如 'before'),但我不能修改请求的 URL(转换为小写),我相信。
所以主要问题是:使用这种方法定义端点后,我如何修改请求的 URL 为小写,或者告诉 SparkJava 以不区分大小写的模式映射 URL。
英文:
I have a java code which serves http endpoints using SparkJava (http://sparkjava.com/).
Endpoints are generated like that:
get("/xxx/yyy", (request, response) -> {
...
return SOMETHING_TO_RETURN
});
With that approach I have a problem:
let's say I have an endpoint defined: '/api/status/car' ,
but users sometimes invoke '/api/status/CAR' instead. So the problem is with case sensitive of url defined like that.
Now I have to fix it somehow: make that case insensitive.
I had take a look on filters (e.g. 'before'), but I can't modify request url (toLowerCase) I believe.
So the main question is: With defining endpoints using that approach, how can I modify request url to be lowercase, or to say sparkjava that urls should be mapped with case insensitive mode.
答案1
得分: 1
URL(除了域名部分)可能始终区分大小写。服务器有权决定,因此用户永远无法知道。您可以在W3.org上了解更多相关信息。
解决您的问题的一种方法是使用请求参数:
get("/api/status/:carParam", (request, response) -> {
if (request.params(":carParam").equalsIgnoreCase("car")) {
return SOMETHING_TO_RETURN;
}
});
如果您在/api/status/
下有更多的路由,除了car
之外,那么您应该将 :carParam
重命名为更通用的名称,例如 :param
,然后在处理程序主体内,您将检查此查询参数并根据需要返回正确的返回值。例如:
get("/api/status/:param", (request, response) -> {
if (request.params(":param").equalsIgnoreCase("car")) {
return SOMETHING_TO_RETURN_CAR;
} else if (request.params(":param").equalsIgnoreCase("passenger")) {
return SOMETHING_TO_RETURN_PASSENGER;
}
});
英文:
URLs (except the domain name part) might always be case-sensitive. It's up to the server to decide and therefore the user can never know. You can read about it more in W3.org.
One approach to solve your problem could be using request params:
get("/api/status/:carParam", (request, response) -> {
if (request.params(":carParam").equalsIgnoreCase("car")) {
return SOMETHING_TO_RETURN;
}
});
If you have more routes under /api/status/
except car
then you should rename :carParam
to a more generic name like :param
and then inside the handler body, you'd check this query param and return the right return value accordingly. For example:
get("/api/status/:param", (request, response) -> {
if (request.params(":param").equalsIgnoreCase("car")) {
return SOMETHING_TO_RETURN_CAR;
} else if (request.params(":param").equalsIgnoreCase("passenger")) {
return SOMETHING_TO_RETURN_PASSENGER;
}
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论