Importing and using groovy code in GSP

2019-04-21 09:38发布

问题:

I am trying to use a groovy function inside a GSP. Please help as I am about to tare my hair out here.

At the top of my GSP i have <%@ page import = company.ConstantsFile %>

Inside my GSP I have

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

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
    }
}

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

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.

回答1:

First, your GSP's import should be:

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

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>

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()
  }
}

Then use in your GSP

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