Search code examples
javaspark-java

Spark-Java: Different Path Strings Map to Same Get Method


I am running into a problem where two distinct paths are mapping to the same resource. Please let me know why the following 2 paths are mapping to the same path:

get("/test/:idtest/:idsimple", (request, response) -> "");
get("/test/all/:idtest", (request, response) -> "");

Following two call map to the same:

curl -X GET -i http://localhost:4567/test/2/3

curl -X GET -i http://localhost:4567/test/all/5

Thanks


Solution

  • The reason for these two requests to be mapped to the first route is the order you defined them. Spark Java documentation mentions here that:

    Routes are matched in the order they are defined. The first route that matches the request is invoked.

    When you call http://localhost:4567/test/2/3 Java Spark would try to match it first with the first route you defined "/test/:idtest/:idsimple":

    • The variable idtest would be matched to 2
    • The variable idsimple would be matched to 3

    When you call http://localhost:4567/test/all/5 Java Spark would try to match it first with the first route you defined again:

    • The variable idtest would be matched to all
    • The variable idsimple would be matched to 5

    So both of them match and therefore mapped to this route.

    If you change the order of the routes definitions, then "/test/all/:idtest" will be the first path to match against and then calling http://localhost:4567/test/all/5 would be mapped to the right route, while calling http://localhost:4567/test/2/3 would fail the first one and would be mapped to the second.