플레이시 휴식! 뼈대
우리는 주로 모바일 앱에 콘텐츠를 제공하는 프로젝트를 계획하고 있지만 웹 사이트가 필요합니다.
내 질문은 Jersey 또는 Restlet을 사용하여 모바일 앱용 REST API를 개발 한 다음 Play! 웹 사이트를 제공합니다.
아니면 Play를 사용하는 것이 더 합리적입니까? 그것을 모두하기 위해? 그렇다면 Play로 REST를 수행하는 방법! 뼈대?
요청에 따라 간단한 REST 유사 접근 방식입니다. Codemwncis의 솔루션이 작동하는 방식과 거의 동일하지만 컨텐츠 협상에 Accept 헤더를 사용합니다. 먼저 경로 파일 :
GET /user/{id} Application.user
POST /user/ Application.createUser
PUT /user/{id} Application.updateUser
DELETE /user/{id} Application.deleteUser
여기에 컨텐츠 유형을 지정하지 마십시오. IMHO는 특정 리소스에 대해 "특별한"URI를 원할 때만 필요합니다. /users/feed/
항상 Atom / RSS로 돌아갈 경로를 선언하는 것과 같습니다 .
애플리케이션 컨트롤러는 다음과 같습니다.
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);
}
보시다시피 getUserJSON 메소드 만 제거하고 getUser 메소드의 이름을 변경했습니다. 다른 컨텐츠 유형이 작동하려면 이제 여러 개의 템플리트를 작성해야합니다. 원하는 각 컨텐츠 유형마다 하나씩. 예를 들면 다음과 같습니다.
user.xml :
<users>
<user>
<name>${user.name}</name>
. . .
</user>
</users>
user.json :
{
"name": "${user.name}",
"id": "${user.id}",
. . .
}
user.html :
<html>...</html>
이 접근법은 모든 브라우저가 Accept 헤더에 text / html 컨텐츠 유형을 보내기 때문에 브라우저는 항상 HTML보기를 제공합니다. 다른 모든 클라이언트 (일부 JavaScript 기반 AJAX 요청)는 원하는 컨텐츠 유형을 정의 할 수 있습니다. jQuerys ajax () 메소드를 사용하면 다음을 수행 할 수 있습니다.
$.ajax({
url: @{Application.user(1)},
dataType: json,
success: function(data) {
. . .
}
});
JSON 형식의 ID 1을 가진 사용자에 대한 세부 정보를 얻을 수 있습니다. Play는 현재 기본적으로 HTML, JSON 및 XML을 지원하지만 공식 문서 를 따르 거나 콘텐츠 협상 모듈을 사용하여 다른 유형을 쉽게 사용할 수 있습니다 .
If you are using Eclipse for development I suggest use the REST client plugin which lets you test your routes and their corresponding content type.
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:
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:
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
}
Use Play! to do it all. Writing REST services in Play is very very easy.
Firstly, the routes file makes it straightforward to write routes that conform to the REST approach.
Then, you write your actions, in the controller, for each API method you want to create.
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.
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
<user>
<name>${user.name}</name>
<dob>${user.dob}</dob>
.... etc etc
</user>
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.
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.
you should have a look at
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...
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.
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
참고URL : https://stackoverflow.com/questions/4379485/restful-on-play-framework
'Programming' 카테고리의 다른 글
SQL Server 2008 및 SQL Server 2005 및 날짜 시간 사용 (0) | 2020.07.18 |
---|---|
람다 식에는 코드 줄 저장 이외의 용도가 있습니까? (0) | 2020.07.18 |
vb.net에서 중첩 / 종료 (0) | 2020.07.18 |
ApiController로 원시 문자열을 반환하는 방법은 무엇입니까? (0) | 2020.07.18 |
로컬 지점을 GitHub로 푸시 (0) | 2020.07.18 |