[英]Importing and using groovy code in 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中。
首先,您的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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.