I wanted to develop a RESTful
Application with use of CRUD
in Play framework. Unfortunately I can't find a way to define DELETE
and PUT
in the routes of Play. Maybe there is just POST
and GET
available in Play?
Are you sure you cannot use DELETE/PUT? The docs say otherwise.
The HTTP method
The HTTP method can be any of the valid methods supported by HTTP (GET, POST, PUT, DELETE, HEAD).
http://www.playframework.org/documentation/2.0.4/JavaRouting
Play 2.x has not a CRUD module known from 1.x branch (IMHO fortunately), for defining routes using not standard methods like DELETE
or PUT
you need to just use required method in the route:
conf/routes:
PUT /put-item controllers.Application.putItem()
Anyway to use them from the browser methods other than GET
or POST
you'll need to create an AJAX call, There is a large step-by-step sample on this topic, anyway you can also build it with common jQuery.ajax() by defining the request type
$.ajax({
type: "PUT",
url: "@routes.Application.putItem()",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
A good way to define these is using a wildcard (*) This will allow you to use any method valid http method, including those that you have asked about.
For example,
* /items/{id} Items.display
in routes will allow a GET /items/15 or a PUT /items/15. Use wildcards like this to make your route definitions simpler and more flexible.
Don't forget OPTIONS method, if you going to use PUT or DELETE from web browser.
Here is what I did for Delete and Update
POST /path/:id controllers.Controller.update(id: Integer)
POST /path/:id/delete controllers.Controller.delete(id: Integer)
And in Controller just
public static Result delete(Integer id) {
Result result = null;
if(id>0){
//your code
}
else{
result = ok("invalid id");
}
return result;
}
It worked for us for delete and puts
If your intention is only to use RESTFul of play framework and you are using Java it is better use CXF or Spring webservices or Jersey. Play is a fantastic framework but best fit with play is scala
This is an example router in a play scala application that uses the most prominent http verbs:
GET / controllers.Application.listProjects
PUT /projects/:name controllers.Application.createProject(name: String)
GET /projects/list controllers.Application.listProjects
GET /projects/:id controllers.Application.projects(id: Long)
PUT /projects/:id/:name controllers.Application.addTaskToProject(name: String, id: Long)
PATCH /tasks/:id controllers.Application.modifyTask(id: Long, color:Option[String] ?= None)
You can have a look at the whole play scala example project here: https://github.com/nemoo/play-slick3-example
© 2022 - 2024 — McMap. All rights reserved.