gpt4 book ai didi

grails - 在GSP中导入和使用Groovy代码

转载 作者:行者123 更新时间:2023-12-02 13:45:37 25 4
gpt4 key购买 nike

我正在尝试在GSP中使用常规功能。请帮忙,因为我要在这里整理头发。

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

我也尝试过将承租人更改为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中。

最佳答案

首先,您的GSP导入应为:

<%@ page import="company.ConstantsFile" %>

其次,您的daysBetween应该是静态的(更有意义),并且除了 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
}
}

第三,通过以下方式访问它:
<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>

关于grails - 在GSP中导入和使用Groovy代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14698451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com