导入和GSP中使用Groovy代码(Importing and using groovy code

2019-08-16 18:37发布

我试图用一个GSP内的常规功能。 请帮助,因为我要去皮我的头发在这里。

在我的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
    }
}

我也试图改变租车人要放,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

请人帮助我,或指向我一个网站,显示做什么..我试着用搜索引擎,一切有关公司的会谈:选择或一些其他类型的标签......我只是想输出的函数的结果就像我用在JSP中。

Answer 1:

首先,你的普惠制的进口应该是:

<%@ 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>

最后,你应该使用标签库这一点。 我编辑我的职务,以添加例如

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>


文章来源: Importing and using groovy code in GSP