用于返回Json对象的restful Web服务的默认路由

时间:2016-03-14 18:28:02

标签: rest spark-java

我正在使用spark-java框架。我有一条路线:/ users。但是当我输入:/ users /:id时它返回404.但我想返回一个Json对象说:

{
  "default_url": "localhost:4567/users"
}

这是我的/用户路线。

Spark.get("/users", "application/json", (request, response) -> {
            response.status(200);
            response.type("application/json");
            return (new UserDaoImpl().getAllUsers());
        }, new JsonTransformer());

我收到如下错误,然后是前端的404

[qtp2868117-22] INFO spark.webserver.MatcherFilter - The requested route [/users/1] has not been mapped in Spark

2 个答案:

答案 0 :(得分:1)

您需要在路线中添加占位符。

Spark.get("/users/:id", "application/json", (request, response) -> {
    response.status(200);
    response.type("application/json");
    return (new UserDaoImpl(request.params(":id")).getAllUsers());
}, new JsonTransformer());

请参阅文档http://sparkjava.com/documentation.html#routes

答案 1 :(得分:1)

添加符合该情况的其他规则:

Spark.get("/users/:id", (request, response) -> {
    response.status(200);
    response.type("application/json");
    return "{\"default_url\": \"localhost:4567/users\"}";
});