Java RESTful 在玩!框架

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4379485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 16:44:24  来源:igfitidea点击:

RESTful on Play! framework

javarestjerseyrestletplayframework

提问by Gary

We are planning a project primarily serving content to mobile apps, but need to have a website.

我们正在规划一个主要为移动应用程序提供内容的项目,但需要有一个网站。

My question is whether is makes sense to use Jersey or Restlet to develop REST APIs for our mobile apps, and then use Play! to serve the website.

我的问题是使用 Jersey 或 Restlet 为我们的移动应用程序开发 REST API,然后使用 Play!为网站提供服务。

Or does it make more sense to just use Play! to do it all? If so, how to do REST with Play! framework?

还是仅使用 Play 更有意义!做这一切?如果是这样,如何使用 Play 进行 REST!框架?

回答by Codemwnci

Use Play! to do it all. Writing REST services in Play is very very easy.

使用播放!做这一切。在 Play 中编写 REST 服务非常简单。

Firstly, the routes file makes it straightforward to write routes that conform to the REST approach.

首先,路由文件使得编写符合 REST 方法的路由变得简单。

Then, you write your actions, in the controller, for each API method you want to create.

然后,在控制器中为要创建的每个 API 方法编写操作。

Depending on how you want to return the result (XML, JSON etc), there are a few methods you can use. For example, using the renderJSON method, allows the results to be rendered very easily. If you want to render XML, then you can just do so in the same way as you would build an HTML document in your View.

根据您希望如何返回结果(XML、JSON 等),您可以使用几种方法。例如,使用 renderJSON 方法,可以非常轻松地呈现结果。如果您想呈现 XML,那么您可以按照在视图中构建 HTML 文档的相同方式进行。

Here is a neat example.

这是一个简洁的例子。

routes file

路由文件

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

Application file

申请文件

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);
}

getUser.xml file

getUser.xml 文件

<user>
   <name>${user.name}</name>
   <dob>${user.dob}</dob>
   .... etc etc
</user>

回答by Peter Hilton

Integrating with a JAX-RS implementation is a possible alternative approach to using Play's built-in HTTP routing. For a RESTEasy example, see the RESTEasy Play! module.

与 JAX-RS 实现集成是使用 Play 的内置 HTTP 路由的一种可能的替代方法。有关 RESTEasy 示例,请参阅RESTEasy Play!模块

This approach makes sense if you are already invested in JAX-RS, or if you need some of the advanced features REST that JAX-RS provides such as content negotiation. If not, it would be simpler to just use Play directly to serve JSON or XML in response to HTTP requests.

如果您已经对 JAX-RS 进行了投资,或者如果您需要 JAX-RS 提供的一些高级功能 REST,例如内容协商,那么这种方法是有意义的。如果没有,直接使用 Play 来响应 HTTP 请求来提供 JSON 或 XML 会更简单。

回答by seb

As per request, a simple REST-like approach. It works almost the same way Codemwncis' solution works but uses the Accept header for content negotiation. First the routes file:

根据请求,一种简单的类似 REST 的方法。它的工作方式几乎与 Codemwncis 的解决方案的工作方式相同,但使用 Accept 标头进行内容协商。首先是路由文件:

GET     /user/{id}            Application.user
POST    /user/                Application.createUser
PUT     /user/{id}            Application.updateUser
DELETE  /user/{id}            Application.deleteUser

You don't specify any content type here. Doing so is IMHO only necessary when you want to have "special" URIs for certain resources. Like declaring a route to /users/feed/to always return in Atom/RSS.

您没有在此处指定任何内容类型。恕我直言,只有当您想为某些资源使用“特殊”URI 时才需要这样做。就像/users/feed/在 Atom/RSS 中声明一个总是返回的路由一样。

The Application controller looks like this:

应用程序控制器如下所示:

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);
}

As you can see I only removed the getUserJSON method and renamed the getUser method. For different content types to work you now have to create several templates. One for each desired content type. For example:

如您所见,我只删除了 getUserJSON 方法并重命名了 getUser 方法。要使不同的内容类型起作用,您现在必须创建多个模板。每个所需的内容类型一个。例如:

user.xml:

用户.xml:

<users>
  <user>
    <name>${user.name}</name>
    . . .
  </user>
</users>

user.json:

用户.json:

{
  "name": "${user.name}",
  "id": "${user.id}",
  . . . 
}

user.html:

用户.html:

<html>...</html>

This approach gives browsers always the HTML view, since all browsers send a text/html content type in their Accept header. All other clients (possibly some JavaScript-based AJAX requests) can define their own desired content type. Using jQuerys ajax() method you could do the following:

这种方法始终为浏览器提供 HTML 视图,因为所有浏览器都在它们的 Accept 标头中发送 text/html 内容类型。所有其他客户端(可能是一些基于 JavaScript 的 AJAX 请求)可以定义他们自己想要的内容类型。使用 jQuery ajax() 方法,您可以执行以下操作:

$.ajax({
  url: @{Application.user(1)},
  dataType: json,
  success: function(data) {
    . . . 
  }
});

Which should get you the details about User with the ID 1 in JSON format. Play currently supports HTML, JSON and XML natively but you can easily use a different type by either following the official documentationor use the content negotiation module.

这应该会以 JSON 格式为您提供有关 ID 为 1 的用户的详细信息。Play 目前原生支持 HTML、JSON 和 XML,但您可以通过遵循官方文档或使用内容协商模块轻松使用不同的类型。

If you are using Eclipse for development I suggest use the REST client pluginwhich lets you test your routes and their corresponding content type.

如果您使用 Eclipse 进行开发,我建议您使用REST 客户端插件,它可以让您测试路由及其相应的内容类型。

回答by opensas

you should have a look at

你应该看看

http://www.lunatech-labs.com/open-source/resteasy-crud-play-module

http://www.lunatech-labs.com/open-source/resteasy-crud-play-module

it's a module for play that automatically build a rest interface, just like the crud module automatically builds an admin area...

它是一个自动构建休息界面的播放模块,就像 crud 模块自动构建管理区域一样......

回答by tchristensen

It does seem like this approach is broken in Play version 1.2.3. If you download the source done by @seb and mentioned earlier https://github.com/sebhoss/play-user-sample, the creation of a new user object using POST with a JSON object is no longer possible.

这种方法似乎在 Play 1.2.3 版中被破坏了。如果您下载由 @seb 完成并在前面提到的源代码https://github.com/sebhoss/play-user-sample,则不再可能使用带有 JSON 对象的 POST 创建新用户对象。

You need to have specific methods for creation done using with json and xml POSTs. Outlined here: https://groups.google.com/forum/#!topic/play-framework/huwtC3YZDlU

您需要使用 json 和 xml POST 完成特定的创建方法。此处概述:https://groups.google.com/forum/#! topic/play-framework/huwtC3YZDlU

回答by Alden

This is still a popular question, but the highest voted answers are not up to date with the current version of play. Here's a working REST example with play 2.2.1:

这仍然是一个受欢迎的问题,但投票最高的答案与当前版本的游戏版本不一致。这是一个带有 play 2.2.1 的工作 REST 示例:

conf/routes:

配置/路线:

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/controllers/UserController.java:

应用程序/控制器/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
}