10

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:selectまたは他の種類のタグについて語っています...私が使用したような関数の結果を出力したいだけですJSP内に。

4

1 に答える 1

19

まず、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
    }
}

3 番目に、次の方法でアクセスします。

<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>
于 2013-02-05T01:05:24.760 に答える