2013-02-05 26 views
8

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

我也試圖改變租車人要放, 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

首先,你的普惠制的進口應該是:

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

感謝您的幫助,我想你向我建議第一種方式,我得到了以下錯誤: 錯誤500:內部服務器錯誤 URI /公司/ 類 groovy.lang.MissingMethodException 消息 方法的無簽名:靜態company.ConstantsFile.daysBetween()是適用於參數類型:()值:[]名次sible解決方案:daysBetween() –

+0

好的。我很抱歉做到這一點,但這是我試圖做的日曆實例和數學。 +1並接受幫助我 –