Search code examples
javaroutesspark-javaspark-framework

Spark Framework: Match with or without trailing slash


I have noticed something in the Spark Framework. It does not match trailing slashes with a mapped route. So it considers /api/test and /api/test/ as different URIs.

That's fine if there is a way to wildcard them together, but there doesn't seem to be. Am I missing anything?

I want this route:

Spark.get("/api/test", (req, res) -> {
            return "TEST OK";
        });

To match /api/test OR /api/test/. As it stands, it only matches /api/test, and if I switch it to:

Spark.get("/api/test/", (req, res) -> {
            return "TEST OK";
        });

It only matches /api/test/


Solution

  • You can setup a before filter with a redirect, such as:

    Spark.before((req, res) -> {
        String path = req.pathInfo();
        if (path.endsWith("/"))
            res.redirect(path.substring(0, path.length() - 1));
    });
    

    This is probably better than mapping duplicate routes.