簡體   English   中英

Grails 3.1.16攔截器未過濾方法

[英]Grails 3.1.16 Interceptors not filtering on method

我正在嘗試使用Grails攔截器來匹配具有特定HTTP方法的特定uri。 盡管我將Grails版本從3.1.1升級到了3.1.16,但該問題應該得到解決 ,但match方法的method參數卻被忽略了。

我的代碼的簡化版本是:

@GrailsCompileStatic
class MyInterceptor {

    int order = HIGHEST_PRECEDENCE

    MyInterceptor () {
        match(uri: '/api/domain/*', method: 'PUT')
        match(uri: '/api/domain/*', method: 'DELETE')
        match(uri: '/api/domain/*', method: 'POST')
    }
}

通過以下攔截器測試:

@TestFor(MyInterceptor)
class MyInterceptorSpec extends Specification {

    @Unroll
    def "it matches '#method #uri'"() {
        when: "A request matches the interceptor"
        withRequest(uri: uri, method: method)

        then:"The interceptor does match"
        interceptor.doesMatch()

        where:
        uri             | method
        '/api/domain/1' | 'PUT'
        '/api/domain/1' | 'POST'
        '/api/domain/1' | 'DELETE'
    }

    @Unroll
    def "it does not match '#method #uri'"() {
        when:
        withRequest(uri: uri, method: method)

        then:
        !interceptor.doesMatch()

        where:
        uri             | method
        '/api/domain'   | 'GET'
        '/api/domain/1' | 'GET' // failing test
    }

}

如何確保攔截器僅針對給定的HTTP方法匹配uri?

默認情況下,Grails中不可能。

查看UrlMappingMatcher的代碼,我們可以看到,當我們使用uri定義匹配規則時,方法部分將被忽略:

@Override
Matcher matches(Map arguments) {
    if(arguments.uri) {
        uriPatterns << arguments.uri.toString()
    }
    else {
        controllerRegex = regexMatch( arguments, "controller")
        actionRegex = regexMatch( arguments, "action")
        namespaceRegex = regexMatch( arguments, "namespace")
        methodRegex = regexMatch( arguments, "method")
    }
    return this
}

@Override
Matcher excludes(Map arguments) {
    if(arguments.uri) {
        uriExcludePatterns << arguments.uri.toString()
    }
    else {
        def exclude = new MapExclude()
        exclude.controllerExcludesRegex = regexMatch( arguments, "controller", null)
        exclude.actionExcludesRegex = regexMatch( arguments, "action", null)
        exclude.namespaceExcludesRegex = regexMatch( arguments, "namespace", null)
        exclude.methodExcludesRegex = regexMatch( arguments, "method", null)
        excludes << exclude
    }
    return this
}

但是,您可以創建UrlMappingMatcher的子類,即使定義了uri,也要考慮該方法,並使用它代替Interceptor中的常規方法:

// in MyInterceptor.groovy
Matcher match(Map arguments) {
    // use your own implementation of the UrlMappingMatcher
    def matcher = new MethodFilteringUrlMappingMatcher(this)
    matcher.matches(arguments)
    matchers << matcher
    return matcher
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM