class PersonController {
// action1 may be invoked from a POST
// action2 has no restrictions
// action3 may be invoked from a POST or DELETE
static allowedMethods = [action1:'POST',
action3:['POST', 'DELETE']]
def action1() { ... }
def action2() { ... }
def action3() { ... }
}
allowedMethods
用途
根據 HTTP 要求方法限制對控制器動作的存取,當使用不正確的 HTTP 方法時,傳送 405(方法不允許)錯誤碼。
範例
說明
allowedMethods
屬性提供一個簡單的宣告語法,用於指定哪些 HTTP 方法允許用於控制器動作。預設情況下,所有要求方法都允許用於所有控制器動作。allowedMethods
屬性是選用的,只有在控制器有動作要限制為特定要求方法時才需要定義。
您可以在控制器動作中以程式方式執行這些檢查,並自行傳送 405 錯誤碼,但這往往會使控制器方法混亂,而控制器方法應更專注於應用程式邏輯和路由。這種方法在更複雜的場景中可能不足夠,在這些情況下,自行處理事情是沒問題的。
allowedMethods
屬性是一個 Map,其中鍵是受限制動作的名稱,而值是 String
或 String
的 List
。如果值是 String
,則表示唯一可使用來呼叫該動作的要求方法。如果它是 String
的 List
,則表示所有可使用來呼叫該動作的要求方法。如果違反指定的限制,則回應中會傳回 405 錯誤碼。
例如,此程式碼可防止使用 HTTP GET 呼叫 delete
動作
class PersonController {
def delete() {
if (request.method == 'GET') {
// redirect to the list action
redirect(action: list)
} else {
// the rest of the delete action goes here
}
}
}
它可以回傳 405 錯誤碼,而不是重新導向
class PersonController {
def delete() {
if (request.method == 'GET') {
response.sendError(405)
} else {
// the rest of the delete action goes here
}
}
}
但最乾淨的解決方案是使用 allowedMethods
class PersonController {
static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
def delete() {
// the delete logic goes here
}
}