简体   繁体   English

在GSP中导入和使用groovy代码

[英]Importing and using groovy code in GSP

I am trying to use a groovy function inside a GSP. 我试图在GSP中使用groovy函数。 Please help as I am about to tare my hair out here. 请帮忙,因为我要把头发弄到这里。

At the top of my GSP i have <%@ page import = company.ConstantsFile %> 在我的GSP顶部,我有<%@ page import = company.ConstantsFile %>

Inside my GSP I have 在我的GSP里面我有

<p>
I have been in the heating and cooling business for <%(ConstantsFile.daysBetween())%>
</p>

and my ConstantsFile.groovy 和我的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
    }
}

I have also tried changing renter to puts, system.out, etc but that isn't my main problem. 我也尝试将renter更改为puts,system.out等,但这不是我的主要问题。

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

Please someone help me or point me to a website that shows what to do.. I have tried googling and everything talks about ag:select or some other kind of tag... I just want to output the result of the function like I used to in the JSPs. 请有人帮助我或指向一个显示该做什么的网站..我已经尝试了谷歌搜索和一切谈论ag:选择或其他类型的标签...我只想输出像我用过的功能的结果在JSP中。

First, your GSP's import should be: 首先,您的GSP导入应该是:

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

Second, your daysBetween should be static (it makes more sense) and you don't render from anything but a controller: 其次,你的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
    }
}

Third, access it in the following way: 第三,通过以下方式访问它:

<p>I have been in the heating and cooling business for ${ConstantsFile.daysBetween}</p>

And lastly, you should use a taglib for this. 最后,你应该使用taglib。 I'm editing my post now to add an example 我正在编辑我的帖子以添加一个例子

class MyTagLib {

  static namespace = "my"

  def daysBetween = { attr ->
     out << ConstantsFile.daysBetween()
  }
}

Then use in your GSP 然后在您的GSP中使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM