技术开发 频道

精通 Grails: RESTful Grails

  实现 GET

  由于您已经知道如何返回 XML 了,实现 GET 方法就应该是小菜一碟了。但有一点需要注意。对 http://localhost:9090/trip/airport 的 GET 请求应该返回一个机场列表。而对 http://localhost:9090/trip/airport/den 的 GET 请求应该返回 IATA 代码为 den 的一个机场实例。要达到这个目的,必须建立一个 URL 映射。

  在文本编辑器中打开 grails-app/conf/UrlMappings.groovy。默认的 /$controller/$action?/$id? 映射看起来应该很熟悉。URL http://localhost:9090/trip/airport/show/1 映射到了 AiportController 和 show 操作,而 params.id 值被设置成 1。操作和 ID 结尾的问号说明 URL 元素是可以选择的。

  如清单 10 所示,向将 RESTful 请求映射回 AirportController 的 static mappings 块添加一行。由于还没有在其他控制器中实现 REST 支持,所以我暂时对控制器进行了硬编码。稍候可能会用 $controller 来替代 URL 的 airport 部分。

  清单 10. 创建一个自定义 URL 映射

class UrlMappings {
    static mappings
= {
      
"/$controller/$action?/$id?"{
         constraints {
// apply constraints here
         }
        }          
        
"/rest/airport/$iata?"(controller:"airport",action:"index")
    
"500"(view:'/error')
   }
}

  该映射确保了所有以 /rest 开头的 URI 都被传送到了 index 操作(这样就不需要协商内容了)。它还意味着您可以检查 params.iata 存在与否,以此来决定是应该返回列表还是一个实例。

  按清单 11 所示的方法,修改 index 操作:

  清单 11. 从 HTTP GET 返回 XML

def index = {      
  switch(request.method){
    
case "POST":   //...
    
case "GET":
      
if(params.iata){render Airport.findByIata(params.iata) as XML}
      
else{render Airport.list() as XML}          
      break
    
case "PUT":    //...
    
case "DELETE": //...
  }      
}

  在 Web 浏览器中输入 http://localhost:9090/trip/rest/airport 和 http://localhost:9090/trip/rest/airport/den,确认自定义 URL 映射已经就位。

0
相关文章