在GSP中导入和使用groovy代码

时间:2013-02-05 00:57:03

标签: grails groovy import gsp

我正在尝试在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中一样。

1 个答案:

答案 0 :(得分:18)

首先,您的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>