grails – 在GSP中导入和使用groovy代码

我试图在GSP中使用groovy函数.请帮忙,因为我要在这里去掉我的头发.

在我的GSP顶部,我有<%@ page import = company.ConstantsFile%>

我的GSP里面有

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

和我的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

        render today - startDate
    }
}

我也尝试将renter更改为puts,system.out等,但这不是我的主要问题.

Error 500: Internal Server Error
URI
/company/
Class
java.lang.NullPointerException
Message
Cannot invoke method daysBetween() on null object

所以我试试

<p>
    I have been in the heating and cooling business for <%(new ConstantsFile.daysBetween())%>
    </p>

但后来我明白了

Class: org.codehaus.groovy.control.MultipleCompilationErrorsException

unable to resolve class ConstantsFile.daysBetween @ line 37, column 1. (new ConstantsFile.daysBetween()) ^ 1 error

请有人帮助我或指向一个显示该做什么的网站..我已经尝试了谷歌搜索和一切谈论ag:选择或其他类型的标签…我只想输出像我用过的函数的结果在JSP中.

最佳答案
首先,您的GSP导入应该是:

<%@ page import="company.ConstantsFile" %>

其次,你的daysBetween应该是静态的(它更有意义)并且你不会从控制器以外的任何东西渲染:

class ConstantsFile {

    static 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
    }
}

第三,以下列方式访问它:

<p>I have been in the heating and cooling business for ${ConstantsFile.daysBetween}</p>

最后,你应该使用taglib.我正在编辑我的帖子以添加一个例子

class MyTagLib {

  static namespace = "my"

  def daysBetween = { attr ->
     out << ConstantsFile.daysBetween()
  }
}

然后在您的GSP中使用

<p>I have been in the heating and cooling business for <my:daysBetween /></p>

转载注明原文:grails – 在GSP中导入和使用groovy代码 - 代码日志