Import and use groovy code in GSP

I am trying to use the groovy function inside GSP. Please help as I am going to pull my hair 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 also tried changing the tenant to puts, system.out, etc., but this is not my main problem.

 Error 500: Internal Server Error URI /company/ Class java.lang.NullPointerException Message Cannot invoke method daysBetween() on null object 

So I'm trying

 <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 help me or call me on a website that shows what to do. I tried a search on Google and everyone says about it: select or some other tag ... I just want to output the result of the function as I used in JSPs.

+8
import grails groovy gsp
source share
1 answer

First, your GSP import should be:

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

Secondly, your days should be static (this matters more), and you are not rendering anything except the 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 } } 

Thirdly, access it as follows:

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

And finally, you must use taglib for this. Now I am editing my post 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> 
+17
source share

All Articles