allowedMethods
用途
限制controller中可以从HTTP请求中访问的action列表。
举例
class PersonController {
// action1 may be invoked via a POST
// action2 has no restrictions
// action3 may be invoked via a POST or DELETE
static allowedMethods = action1:'POST',
action3:['POST', 'DELETE']
def action1 = { … }
def action2 = { … }
def action3 = { … }
}
描述
得到请求后Grails会从controller找到相应的action执行并给出适当的响应。下面的代码演示了如何从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
}
}
}
也可以不使用重定向到其他action的方法,而是返回一个405错误(Method Not Allowed),如下:
class PersonController {
def delete = {
if(request.method == 'GET') {
response.sendError(405)
} else {
// the rest of the delete action goes here
}
}
}
在controller里找到匹配的action以响应的相应的请求时,有一个问题,就是在一个controller或一个应用或很多应用中,有着很多很多的action,若是由应用对无效的请求设置特定的处理是可以的,但Grails框架提供了一个简单的声明语法解决了这个问题。
Grails提供了简单的声明语法,限制了从HTTP请求到controller中的action的访问。可以在controller中加入可选的allowedMethods
属性让Grails框架知道哪些HTTP请求被允许提交到controller的action中。默认所有的action请求都被允许,仅仅在某些action有访问限制的时候才需要加上allowedMethods
属性。
赋给allowedMethods
属性的值应该是一个Map,其中的key值是晕加限制的action的名字,value值是个字符串或一个字符串list,字符串中的值是允许提交到action的请求,若是字符串list则所有的字符串中的请求都被允许。如果有被限制的请求则返回一个405错误。