GroovyClassHelloWorldTutorial
Version 3.1 by JeromeVelociter on 2009/03/21
.code { width: auto; }
Creating a Groovy Class
This tutorial illustrates the XWiki.parseGroovyFromPage API method. This method allow you to instantiate a groovy class from both velocity and groovy code.
Create a groovy class
- Create a new page, for example Groovy.HelloWorldClass containing :
/{pre}*{/pre} {pre}Groovy Class{/pre} {pre}#{/pre}* {pre}*{/pre}/
class groovyClass {
def xwiki;
def context;
void setObjects(xwiki, context) {
setXWiki(xwiki);
setContext(context);
}
void setXWiki(xwiki) {
this.xwiki = xwiki;
}
void setContext(context) {
this.context = context;
}
String helloWorld() {
return "Hello World";
}
}
{pre}/{/pre}* *{pre}#{/pre} {pre}*{/pre}/
class groovyClass {
def xwiki;
def context;
void setObjects(xwiki, context) {
setXWiki(xwiki);
setContext(context);
}
void setXWiki(xwiki) {
this.xwiki = xwiki;
}
void setContext(context) {
this.context = context;
}
String helloWorld() {
return "Hello World";
}
}
{pre}/{/pre}* *{pre}#{/pre} {pre}*{/pre}/
Notice the trick of putting a Velocity comment in the Groovy comment so that the code is not parsed by Velocity.
Instantiate and use your class from velocity
- Create a new page, for example "Main.HelloWorldFromVelocity" containing :
{pre}#{/pre}set($groovyObject = {pre}${/pre}xwiki.parseGroovyFromPage("Groovy.HelloWorldClass"))
$groovyObject.setObjects($xwiki, $context)
$groovyObject.helloWorld()
$groovyObject.setObjects($xwiki, $context)
$groovyObject.helloWorld()
- See the result, feeling groovy ?
Instantiate and use your class from groovy
- Create a new page, for example "Groovy.HelloWorldClass" containing :
{pre}<{/pre}%
groovyObject = xwiki.parseGroovyFromPage("Dev.HelloWorldGroovyClass")
groovyObject.setObjects(xwiki, context)
print(groovyObject.helloWorld())
%{pre}>{/pre}
groovyObject = xwiki.parseGroovyFromPage("Dev.HelloWorldGroovyClass")
groovyObject.setObjects(xwiki, context)
print(groovyObject.helloWorld())
%{pre}>{/pre}
- See the result, feeling groovy ?