在GSP中导入和使用Groovy代码 [英] Importing and using groovy code in GSP
问题描述
我试图在GSP中使用groovy函数。
I am trying to use a groovy function inside a GSP. Please help as I am about to tare my hair out here.
在我的GSP的顶部,我有<%@ page import = company .ConstantsFile%>
At the top of my GSP i have <%@ page import = company.ConstantsFile %>
在我的GSP中,我有
Inside my GSP I have
<p>
I have been in the heating and cooling business for <%(ConstantsFile.daysBetween())%>
</p>
和我的ConstantsFile.groovy
and my 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等,但这不是我的主要问题。
I have also tried changing renter to puts, system.out, etc but that isn't my main problem.
Error 500: Internal Server Error
URI
/company/
Class
java.lang.NullPointerException
Message
Cannot invoke method daysBetween() on null object
So I try
<p>
I have been in the heating and cooling business for <%(new ConstantsFile.daysBetween())%>
</p>
但是我得到
but then i get
Class: org.codehaus.groovy.control.MultipleCompilationErrorsException
unable to resolve class ConstantsFile.daysBetween @ line 37, column 1. (new ConstantsFile.daysBetween()) ^ 1 error
请别人帮我或指向一个显示该怎么做的网站..我已经尝试过使用Google搜索和所有关于ag的讨论:选择或其他类型的标记...我只想输出像我以前在JSP中使用的函数的结果。
Please someone help me or point me to a website that shows what to do.. I have tried googling and everything talks about a g:select or some other kind of tag... I just want to output the result of the function like I used to in the JSPs.
推荐答案
首先,您的GSP的导入应该是:
First, your GSP's import should be:
<%@ page import="company.ConstantsFile" %>
第二,你的daysBetween应该是静态的(它更有意义),并且你不会渲染任何东西但控制器:
Second, your daysBetween should be static (it makes more sense) and you don't render from anything but a controller:
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
}
}
第三,按以下方式访问它:
Third, access it in the following way:
<p>I have been in the heating and cooling business for ${ConstantsFile.daysBetween}</p>
最后,您应该为此使用taglib。我正在编辑我的帖子以添加一个示例
And lastly, you should use a taglib for this. I'm editing my post now to add an example
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>
这篇关于在GSP中导入和使用Groovy代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!