根据您希望如何返回结果(XML、 JSON 等) ,有几种方法可以使用。例如,使用 renderJSON 方法,可以非常容易地呈现结果。如果您想呈现 XML,那么您可以使用与在视图中构建 HTML 文档相同的方法。
这里有一个简洁的例子。
路由档案
GET /user/{id} Application.getUser(format:'xml')
GET /user/{id}/json Application.getUserJSON
POST /user/ Application.createUser
PUT /user/{id} Application.updateUser
DELETE /user/{id} Application.deleteUser
申请文件
public static void createUser(User newUser) {
newUser.save();
renderText("success");
}
public static void updateUser(Long id, User user) {
User dbUser = User.findById(id);
dbUser.updateDetails(user); // some model logic you would write to do a safe merge
dbUser.save();
renderText("success");
}
public static void deleteUser(Long id) {
// first check authority
User.findById(id).delete();
renderText("success");
}
public static void getUser(Long id) {
User user = User.findById(id)
renderJSON(user);
}
public static void getUserJSON(Long id) {
User user = User.findById(id)
renderJSON(user);
}
public static void createUser(User newUser) {
newUser.save();
user(newUser.id);
}
public static void updateUser(Long id, User user) {
User dbUser = User.findById(id);
dbUser.updateDetails(user); // some model logic you would write to do a safe merge
dbUser.save();
user(id);
}
public static void deleteUser(Long id) {
User.findById(id).delete();
renderText("success");
}
public static void user(Long id) {
User user = User.findById(id)
render(user);
}
这仍然是一个受欢迎的问题,但是投票最多的答案与当前的游戏版本不同。下面是一个使用 play 2.2.1的可用 REST 示例:
转乘/路线:
GET /users controllers.UserController.getUsers
GET /users/:id controllers.UserController.getUser(id: Long)
POST /users controllers.UserController.createUser
PUT /users/:id controllers.UserController.updateUser(id: Long)
DELETE /users/:id controllers.UserController.deleteUser(id: Long)
App/controller/UserController.java:
public static Result getUsers()
{
List<User> users = Database.getUsers();
return ok(Json.toJson(users));
}
public static Result getUser(Long id)
{
User user = Database.getUser(id);
return user == null ? notFound() : ok(Json.toJson(user));
}
public static Result createUser()
{
User newUser = Json.fromJson(request().body().asJson(), User.class);
User inserted = Database.addUser(newUser);
return created(Json.toJson(inserted));
}
public static Result updateUser(Long id)
{
User user = Json.fromJson(request().body().asJson(), User.class);
User updated = Database.updateUser(id, user);
return ok(Json.toJson(updated));
}
public static Result deleteUser(Long id)
{
Database.deleteUser(id);
return noContent(); // http://stackoverflow.com/a/2342589/1415732
}