2016-12-15 36 views
0

有沒有辦法重新配置Grails 3鏈接生成器來創建Restful鏈接,即localhost:8080/book/{id}而不是在URL中包含動作的舊樣式,localhost:8080/book/show/{id}Grails 3 Restful鏈接生成器(無操作)

我希望在響應的位置標題中留有寧靜的URL以保存操作。

回答

0

我一直在使用這個Grails Restful Link Generator作爲解決方法。我對此並不滿意,但這是迄今爲止我所能達到的最好成績。

1.創建一個src/main/groovy特質從URL

import grails.web.mapping.LinkGenerator 

trait RestfulLinkGeneratorTrait { 

    LinkGenerator grailsLinkGenerator 

    String generateLink(Map map) { 
     map.controller = map.controller ?: this.controllerName 
     map.absolute = map.absolute ?: true 
     map.action = map.action ?: "show" 
     grailsLinkGenerator.link(map).replace("/$map.action", "") 
    } 
} 

2.實現你的控制器(S)的RestfulLinkGenerator並調用generateLink(id: obj.id)生成鏈接刪除多餘的動作。

@Secured('ROLE_USER') 
class BookController extends RestfulController implements RestfulLinkGeneratorTrait { 

    //... other methods ...// 

    @Transactional 
    def save() { 
     // ... save you resource ... // 
     response.addHeader(HttpHeaders.LOCATION, generateLink(id: book.id)) 
     respond book, [status: CREATED, view: 'show'] 
    } 

    //... other methods ...// 

}