2013-02-05 4 views
8

GSP内でGroovy関数を使用しようとしています。ここで私の髪を抱きしめているように助けてください。私のGSPの上部にGSPでGroovyコードをインポートして使用する

私は私のGSP内部<%@ page import = company.ConstantsFile %>

を持って、私は

<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 

を取得し、すべてのことがag:selectや他の種類のタグについて語っています...私はJSPで使ったような関数の結果を出力したいだけです。

答えて

17

まず、あなたの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を使用する必要があります。私はその後、あなたのGSPにあなたの助けを

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

感謝を使う例

class MyTagLib { static namespace = "my" def daysBetween = { attr -> out << ConstantsFile.daysBetween() } } 

を追加するために、今私のポストを編集するよ、私はあなたが私に提案し最初の方法を試してみましたが、私は次のエラーを取得します: エラー500:内部サーバーエラー URI /会社/ クラス groovy.lang.MissingMethodException メッセージ 方法のない署名:()値:静的company.ConstantsFile.daysBetween()は引数の型に適用可能である[]順位解決策:daysBetween() –

+0

OK。私はこれをやって大変申し訳ありませんが、それはカレンダーのインスタンスと数学でした。 +1して私の助けを受け入れる –

関連する問題