[英]Play Framework Scala REST DELETE
I'm trying to figure out how to use the REST DELETE function using the Play Framework. 我试图弄清楚如何使用Play框架使用REST DELETE功能。 Here's what I have:
这就是我所拥有的:
My Model: 我的型号:
case class Task(id: Int, name: String, description: String, group: String)
object Task {
var list: List[Task] = Nil
def save(task: Task) = {
list = list ::: List(task)
}
def all(): List[Task] = Nil
def delete(id: Int){
val b = list.toBuffer
b.remove(id)
b.toArray
}
Here's what I have in my Controller for delete: 这是我在Controller中删除的内容:
def deleteTask(id: Int) = Action {
Task.delete(id)
Ok
}
and my route: 和我的路线:
DELETE /tasks/id controllers.TaskController.deleteTask(id: Int)
Forgot to mention my problem! 忘了提我的问题! How can I run this to test and make sure that it is working?
如何运行此测试并确保它正常工作? I use the command:
我使用命令:
curl --include --request POST --header "content-type: application/json" --data '{"id":4, "name": "test5", "description": "testdesc1","group": "groupc"}' http://localhost:9000/tasks
and it posts correctly. 并且它正确发布。 How can I do a similar action with
DELETE
? 如何使用
DELETE
执行类似的操作?
Your DELETE request is not defined properly right now.
您的DELETE请求目前尚未正确定义。 It should go
DELETE /tasks/:id
if you want to have theid
as a parameter如果你想将
id
作为参数,它应该是DELETE /tasks/:id
. 。
The problem in your Scala code is on line
b.remove(id)
- in this caseb
is actually from typeBufferLike
and the remove method does not do what you use it for.您的Scala代码中的问题是在行
b.remove(id)
- 在这种情况下,b
实际上来自BufferLike
类型,并且remove方法不会执行您使用它的方法。 It actually removes the element at the specifiedindex
and not the element which you provide.它实际上删除了指定
index
的元素,而不是您提供的元素。 So if you provide id=4 then it is going to try to remove the 5th element, and fail with anIndexOutOfBoundsException
which is a Runtime exception which leads to the error page you are receiving.因此,如果您提供id = 4,那么它将尝试删除第5个元素,并且因为运行时异常而导致您收到错误页面的
IndexOutOfBoundsException
失败。 You can just use thediff
method on List instead, like this:val newList = list diff List(id)
您可以在List上使用
diff
方法 ,如下所示:val newList = list diff List(id)
You have specified it already in your routes
file: you have defined a DELETE
request - this means that your curl request should also be a DELETE
one: 您已在
routes
文件中指定了它:您已定义DELETE
请求 - 这意味着您的curl请求也应该是DELETE
请求:
curl -X DELETE "http://localhost:9000/tasks/4"
There is no body to post when using DELETE
- you just specify the ID of the resource you would like to delete. 使用
DELETE
时没有要发布的正文 - 您只需指定要删除的资源的ID。
Bonus: consider returning some other status like HTTP 204 - it is more intuitive when dealing with deletion 奖励:考虑返回一些其他状态,如HTTP 204 - 处理删除时更直观
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.