【问题标题】:access a Groovy file in GSP在 GSP 中访问 Groovy 文件
【发布时间】:2023-03-13 06:07:02
【问题描述】:

所以我试图在我的 GSP 中访问一个 groovy 函数。我有

<%@ page import = company.ConstantsFile %>

然后在 gsp 中我有

I have been in the heating and cooling business for <%daysBetween()%>

还有我的 ConstantsFile.groovy

package company


import static java.util.Calendar.*

class ConstantsFile {

    def daysBetween() {
        def startDate = Calendar.instance
        def m = [:]
        m[YEAR] = 2004
        m[MONTH] = "JUNE"
        m[DATE] = 26
        startDate.set(m)
        def today = Calendar.instance

        return today - startDate
    }
}

编辑:错误信息:

Class
groovy.lang.MissingMethodException
Message
No signature of method: 

【问题讨论】:

    标签: groovy import gsp


    【解决方案1】:

    导入很好,但 Groovy 是面向对象的语言。您需要(如在 JSP/JAVA 中)通过对象调用方法,因此首先创建一个 ConstantsFile 类实例或将方法 daysBetween 定义为静态,如下所示:

    class ConstantsFile {
        static daysBetween() {
            // your code goes here
        }
    }
    

    现在您可以在 GSP 文件中进行操作了

    <%= ConstantsFile.daysBetween() %>
    

    注意等号。没有它,方法返回的值不会被“打印”到生成的 html 中。

    您在使用 Grails 吗?如果是,那么在控制器级别调用 daysBetween() 方法并将结果作为模型的一部分返回到视图中会更好。

    提示:检查Groovy TimeCategory(滚动到“使用 Groovy 的时间类别”)

    最后一件事。 daysBetween() 方法的逻辑似乎不是恒定的。因此将其作为 ConstantFile 类的一部分嵌入违反了合同。事实上,这个类中也没有太多关于“文件”的内容:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-15
      • 1970-01-01
      • 1970-01-01
      • 2012-12-30
      • 2017-08-29
      • 1970-01-01
      相关资源
      最近更新 更多