【问题标题】:can sparkjava routes contain spaces?sparkjava 路由可以包含空格吗?
【发布时间】:2020-07-21 23:07:56
【问题描述】:

我正在将一个包含一些包含空格的路由的码头服务器 API 移植到 sparkjava 框架。但无论我如何转义或引用包含空格的 url,sparkjava 服务器总是返回“404 Not found”。

最简单的代码,基于 sparkjava HelloWorld:

import static spark.Spark.*;

public class Hi {
    public static void main(String[] args) {
        get("/hello", (req, res) -> "Hello World");
        get("/hi there", (req, res) -> "Hi There World");
    }
}

我也尝试过使用重定向,如下所示:

import static spark.Spark.*;

public class Hi {
    public static void main(String[] args) {
        get("/hello", (req, res) -> "Hello World");
        get("/hi_there", (req, res) -> "Hi There World");
        // have tried with and without a get("/hi there", ...) here also
        redirect.get("/hi there", "/hi_there");
    }
}

这仍然只是给出 404。 我试过 curl,比如

curl 'localhost:4567/hi there' (curl itself doesn't like this bare space)
curl 'localhost:4567/hi+there'
curl 'localhost:4567/hi%20there'

我直接在浏览器中使用相同的 404 相同的 url。我看不到 sparkjava 代码或文档中的任何特殊处理或忽略空格。也许 url 中的空格不受欢迎,但我不希望我们当前的用户不得不更改他们正在使用的 url。

那么有没有办法让 sparkjava 处理包含空格的路由?

谢谢!

【问题讨论】:

    标签: spark-java


    【解决方案1】:

    看起来 sparkjava 在查找路由时会进行非常文字的字符串匹配,没有 urlencoding 或特殊字符的转义。因此,由于 curl 可以使用 '+' 或 '%20' 作为空格,而浏览器可能使用 '%20',因此需要添加每个路由。

    import static spark.Spark.*;
    
    public class Hi {
        public static void main(String[] args) {
            get("/hello", (req, res) -> "Hello World");
            get("/hi there", (req, res) -> "Hi There World 1");
            get("/hi+there", (req, res) -> "Hi There World 2");
            get("/hi%20there", (req, res) -> "Hi There World 3");
        }
    }
    

    很高兴得知有不同或更好的方法,但现在这对我有用。所以curl 'localhost:4567/hi+there' 现在按预期返回Hi There World 2

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多