未调用 Grails 过滤器进行自定义操作

Grails filters not being called for custom actions

我正在尝试实现一个过滤器,该过滤器在某些情况下应该在转到 GSP 页面之前调用。由于 URL 在我希望它发生的实例和我不想发生的实例之间没有太大差异,我认为最好的方法是创建一个什么都不做的方法(使用打印语句里面) - 但是当我想要过滤器操作发生时可以简单地调用。

这两个我都试过了:

def hello(){
    print "hello"       
}

def hello = {
    print "hello"
}

只需添加

即可调用这些
hello()

在相关点

我的过滤器开始是这样的:

import uui.FormattingService

class TimeFormatterFilters {

    def FormattingService formattingService

    def filters = {
        someFilter(controller: 'userProfile', action: 'hello') {
            before = {
                print "filter action taking place"

对于 UserProfileController 中的任何一个新创建的方法,我都没有在过滤器中看到打印语句,但是如果我将过滤器的操作交换为 'index',我会在过滤器中看到打印被调用。

你是这样说的:

calling these simply by adding

hello()

这是否意味着您正在从另一个方法调用 hello() 方法?确保为了测试过滤器,您需要直接点击 URL /userProfile/home

您面临的问题是您直接从控制器中的另一个操作调用 hello() 操作。这只是一个普通的方法调用,不会通过过滤器。

Grails 过滤器在 HTTP 客户端请求特定 URI 时被调用,例如http://localhost:8080/my-app/myController/myAction 将匹配 myControllermyAction.

如果您在响应不同的 URI 时只是从控制器内部调用 myAction(),则不会使用过滤器。这就是你在做什么。