cmpe 473-internet programming groovy scripting language

44
CMPE 473-Internet Programming CMPE 473-Internet Programming GROOVY SCRIPTING GROOVY SCRIPTING LANGUAGE LANGUAGE Presented by Presented by Seçkin ULUĞ Seçkin ULUĞ Canan Çelik Canan Çelik

Upload: clifford-bryant

Post on 02-Jan-2016

45 views

Category:

Documents


2 download

DESCRIPTION

CMPE 473-Internet Programming GROOVY SCRIPTING LANGUAGE. Presented by Seçkin ULUĞ Canan Çelik. Groovy Scripting Language. - PowerPoint PPT Presentation

TRANSCRIPT

CMPE 473-Internet ProgrammingCMPE 473-Internet Programming

GROOVY SCRIPTINGGROOVY SCRIPTINGLANGUAGELANGUAGE

Presented byPresented by

Seçkin ULUĞ Seçkin ULUĞ Canan ÇelikCanan Çelik

Groovy Scripting LanguageGroovy Scripting Language Groovy is an object-oriented programming language for the Java Groovy is an object-oriented programming language for the Java

Platform as an alternative to the Java programming language. It can Platform as an alternative to the Java programming language. It can be viewed as a be viewed as a scripting languagescripting language for the Java Platform, as it has for the Java Platform, as it has features similar to those Python, Ruby, Perl, and Smalltalk. features similar to those Python, Ruby, Perl, and Smalltalk.

Groovy uses a Java-like Groovy uses a Java-like curly bracket syntaxcurly bracket syntax which is dynamically which is dynamically compiled to compiled to JVM bytecodesJVM bytecodes and that works seamlessly with other and that works seamlessly with other Java code and Java code and librarieslibraries. .

Groovy is currently undergoing Groovy is currently undergoing standardizationstandardization via the via the Java Java Community ProcessCommunity Process under under JSR-241JSR-241.. In some contexts, the name In some contexts, the name JSR 241JSR 241 is used as an alternate identifier for the Groovy language. is used as an alternate identifier for the Groovy language.

Groovy 1.0 was released on Groovy 1.0 was released on January 2, 2007January 2, 2007. Groovy 1.1 is . Groovy 1.1 is currently in beta and supports Java 5 annotations and static imports.currently in beta and supports Java 5 annotations and static imports.

According to the brainchild of superstar According to the brainchild of superstar developers James Strachan and Bob McWhirter, developers James Strachan and Bob McWhirter, Groovy is an agile development language that is Groovy is an agile development language that is based entirely on the Java programming APIs. based entirely on the Java programming APIs.

Groovy is currently in the beginning phase of Groovy is currently in the beginning phase of its Java Specification Request, which was its Java Specification Request, which was approved in late March of 2004. Groovy is also approved in late March of 2004. Groovy is also the scripting language that some claim will the scripting language that some claim will forever change the way that Java platform is forever change the way that Java platform is viewed and utilized.viewed and utilized.

Basic Properties of GroovyBasic Properties of Groovy Groovy is an agile dynamic language for the Java PlatformGroovy is an agile dynamic language for the Java Platform

Builds upon the strengths of Java but has Builds upon the strengths of Java but has additional power additional power

Makes Makes modern programming featuresmodern programming features available to Java available to Java developers with developers with almost-zero learning curvealmost-zero learning curve

Increases developer productivity by Increases developer productivity by reducing structural codereducing structural code when developing web, GUI, database or console applications when developing web, GUI, database or console applications

continuously continuously integrates with all existing Java objects and integrates with all existing Java objects and librarieslibraries

compiles straight to Java bytecode so you can use it anywhere you compiles straight to Java bytecode so you can use it anywhere you can use Java can use Java

Why Another LanguageWhy Another Language

Groovy isn't the only scripting language that is compliant with the JRE. Python, Ruby, and Smalltalk are just three examples of scripting languages that have been successfully ported to the Java platform. This begs the question: Why another language? After all, many of us already combine our Java code with Jython or JRuby for faster application development; why should we learn another language?

The answer is that “you don't have to learn a new language to code with Groovy”. Groovy differentiates itself from the other JRE-compliant scripting languages with its syntax and reuse of standard Java libraries. Whereas Jython and JRuby share the look and feel of their ancestors (Python and Ruby, respectively), Groovy feels like the Java language with far fewer restrictions. Groovy employs the features and libraries Java developers are most familiar with.

The fundamental tenets of agile development are that code should The fundamental tenets of agile development are that code should be well suited to a widebe well suited to a wide ra range of tasks and applicable in a variety ofnge of tasks and applicable in a variety of ways. Groovy lives up to these tenets byways. Groovy lives up to these tenets by

Making developers free from compilation Making developers free from compilation Permiting dynamic types Permiting dynamic types Making easy syntactical constructs Making easy syntactical constructs Allowing its scripts to be used inside normal Java applications Allowing its scripts to be used inside normal Java applications Providing a shell interpreter Providing a shell interpreter These features make Groovy a remarkably easy language to learn These features make Groovy a remarkably easy language to learn

and use, whether you're a seasoned Java developer or newcomer and use, whether you're a seasoned Java developer or newcomer to the Java platform. to the Java platform.

Agile DevelopmentAgile Development

Like many scripting languages, Groovy saves Like many scripting languages, Groovy saves compilation for runtime. This means that Groovy scripts compilation for runtime. This means that Groovy scripts are interpreted are interpreted when they are runwhen they are run, much like JavaScript , much like JavaScript is interpreted by the browser when a Web page is is interpreted by the browser when a Web page is viewed. viewed.

Runtime evaluation comes at a cost in terms of Runtime evaluation comes at a cost in terms of execution speed, which could rule out the use of execution speed, which could rule out the use of scripting languages in performance intensive projects, scripting languages in performance intensive projects, but compilation-free coding offers tremendous but compilation-free coding offers tremendous advantages when it comes to the build-and-run cycle. advantages when it comes to the build-and-run cycle.

Runtime compilation makes Groovy an ideal platform Runtime compilation makes Groovy an ideal platform for rapid prototyping, building various utilities, and for rapid prototyping, building various utilities, and testing frameworks. testing frameworks.

CompilationCompilation

Getting started..Getting started.. Groovy requires Java, (1.4 or greater is required). Groovy requires Java, (1.4 or greater is required). Groovy can be downloaded from Groovy can be downloaded from http://http://dist.codehaus.orgdist.codehaus.org

/groovy/distributions//groovy/distributions/ Add a new System variable with the name GROOVY_HOME and Add a new System variable with the name GROOVY_HOME and

the value of the directory groovy was installed in. the value of the directory groovy was installed in. Run groovyConsole.bat by double clicking on the icon in the bin Run groovyConsole.bat by double clicking on the icon in the bin

directory of the Groovy distribution. directory of the Groovy distribution. Type in the groovy console or your groovy file the magical sentence: Type in the groovy console or your groovy file the magical sentence:

println "Hello, World!“ println "Hello, World!“ Groovy files can beGroovy files can be run (actually compile and then run) run (actually compile and then run) by by typing typing

groovy file_name.groovy groovy file_name.groovy from the command linefrom the command line also Groovy also Groovy console can be copiled by simply pressing CTRL+R .console can be copiled by simply pressing CTRL+R .

As expected, result is: Hello, World!As expected, result is: Hello, World!

Running Groovy FilesRunning Groovy Files Running the script Emailer.groovyin Groovy is as easy Running the script Emailer.groovyin Groovy is as easy

as typing groovy Emailer.groovy on a command line. as typing groovy Emailer.groovy on a command line. If the same Java file (Emailer.java) wanted to be run an If the same Java file (Emailer.java) wanted to be run an

extra command: javac Emailer.java, followed by java extra command: javac Emailer.java, followed by java Emailer should be written. This might seem trivial, you Emailer should be written. This might seem trivial, you can easily imagine the advantage of runtime compilation can easily imagine the advantage of runtime compilation in a larger context of application development. in a larger context of application development.

Groovy also permits scripts to drop a main method in Groovy also permits scripts to drop a main method in order to statically run an associated application.order to statically run an associated application.

Groovy does not require the explicit typing of formal languages such as C++ Groovy does not require the explicit typing of formal languages such as C++ and the Java language. and the Java language.

Java static typing: Java static typing: String myStr="Hello World"; String myStr="Hello World"; Groovy dynamic typing:Groovy dynamic typing: myStr="Hello World"myStr="Hello World" As it can be seen there is no need to declare the variable type. As it can be seen there is no need to declare the variable type. TThere is here is

also also no need to use a semicolon after the declaration in Groovy. no need to use a semicolon after the declaration in Groovy.

Another concept getting a new meaning in groovy is polymorphism. One can have all the power of polymorphism without inheritance with dynamic typing.

class Song{ length name } class Book{ name author } def doSomething(thing){ println "going to do something with a thing named = " + thing.name } Above are two Groovy classes, ‘Song’ and ‘Book’. Both classes contain a name property. The

method ‘doSomething’ takes a ‘thing’ and attempts to print the object's ‘name’ property. Since ‘doSomething’ method does not define a type for its input parameter, any object will work so long as the object contains a name property. Both instances of Song and Book can be used as input for ‘doSomething’ like:

mySong = new Song(length:90, name:"Burning Down the House") myBook = new Book(name:"One Duck Stuck", author:"Phyllis Root") doSomething(mySong) Burning Down the House anotherSomething = doSomethinganotherSomething(myBook) One Duck Stuck

Polymorphism in GroovyPolymorphism in Groovy

VariablesVariables x = 1 println xx = 1 println x 11 x = new java.util.Date()x = new java.util.Date() println xTue Dec 01 20:20:59 EET 2007println xTue Dec 01 20:20:59 EET 2007x = false println xx = false println x falsefalsex = "Hi" println xx = "Hi" println x HiHi Any String assignment can contain the pattern ${Any String assignment can contain the pattern ${variablenamevariablename}, },

and the value of the named variable will be interpolated into the and the value of the named variable will be interpolated into the String:String:

i=42i=42 println “Hello ${i}”println “Hello ${i}” Hello 42Hello 42

ListsLists

myList = [1776, -1, 33, 99, 0, 9763]myList = [1776, -1, 33, 99, 0, 9763]println myList[0]println myList[0] 17761776println myList.size()println myList.size() 66aList = ['python', 'ruby', 'groovy'] println aList = ['python', 'ruby', 'groovy'] println

aList[-3] aList[-3] pythonpython

MapsMapsscores=["Brett":100, "Pete":"Did not finish", scores=["Brett":100, "Pete":"Did not finish",

“ “Andrew":86.87934]Andrew":86.87934] It should be noted that each of the values stored inIt should be noted that each of the values stored in the map is of a the map is of a

different type.different type. println scores["Pete"]println scores["Pete"] Did not finishDid not finishprintln scores.Peteprintln scores.Pete

Did not finishDid not finish

Map.each method: Map.each method: printMapClosure = { key, value -> println key + "=" + value }printMapClosure = { key, value -> println key + "=" + value } ["first" : "1", "second" : "2", "third" :["first" : "1", "second" : "2", "third" : 3"].each(printMapClosure)3"].each(printMapClosure) second=2second=2 third=3third=3 first=1first=1

Conditional ExecutionConditional Execution

amPM =amPM = Calendar.getInstance().get(Calendar.AM_PM)Calendar.getInstance().get(Calendar.AM_PM)

if (amPM == Calendar.AM){if (amPM == Calendar.AM){ println("Good println("Good morning")morning")

}}

else{else{

println("Good evening")println("Good evening")

}}

Good eveningGood evening

IteratorsIterators

str = "uncle man“str = "uncle man“ for (ch in str){ println ch }for (ch in str){ println ch }uunnccllee mmaann

ClosuresClosures One of the most interesting syntax extension Groovy provides beyond standard

Java is what are called closures. This term has been overloaded in a lot of places in computer science, but for now just similar to inner classes. One difference is that variables can be passed in or out; Groovy closures do not constitute a "lexical scope" the way an inner class does. Below example indicates how to break a String into a List and print it one word per line, both the "long way" and using closures.

Without closures: x = "When in the course of human events ...".tokenize() for (val in x) println val With closures, default parameter name: "When in the course of human events ...".tokenize().each{ println it } square = { it * it } [ 1, 2, 3, 4 ].collect(square) [ 1, 4, 9, 16 ]

Closures (2)Closures (2) class Dog{ action train(){ action.call() } } sit = { println "Sit, Sit! Sit! Good dog"} down = { println "Down! DOWN!" } myDog = new Dog(action:sit) myDog.train() Sit, Sit! Sit! Good dog mollie = new Dog(action:down) mollie.train() Down! DOWN!

[1, 2, 3].each { val = it val += val println val}246

Dealing with FilesDealing with Files

Groovy's java.io.File class has a newReader method that returns a BufferedReader (and newPrintWriter(), which returns a PrintWriter). java.io.File also has eachLine, which opens the file and reads each line.

myFileName = "C:\\temp.txt" myFile = new File(myFileName) printFileLine = { println "File line: " + it }

myFile.eachLine( printFileLine )

File line: first lineFile line: second lineFile line: third line

filename="C:\\temp.txt"; chars=0; lines=0; words=0; new java.io.File(filename).eachLine { chars+=it.length() + 1 words+=it.tokenize().size(); lines++; } println "\t${lines}\t${words}\t${chars}\t${filename}"3 6 34 C:\temp.txt

Java.javaJava.java

import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;import java.util.StringTokenizer;public class javaVersion{

public static void main(String[] args) throws IOException {int chars=0, lines=0, words=0;String filename=args[0];BufferedReader r = new BufferedReader(new FileReader(filename));String it;while ((it = r.readLine()) != null) {

chars+=it.length() + 1;words+=new StringTokenizer(it).countTokens();lines++;

}System.out.println("\t" + lines + "\t" + words +

"\t" + chars + "\t" + filename);}

}

Groovy.groovyGroovy.groovy filename="C:\\temp.txt"; chars=0; lines=0; words=0; new java.io.File(filename).eachLine { chars+=it.length() + 1 words+=it.tokenize().size(); lines++; } println "\t${lines}\t${words}\t${chars}\t${filename}"

Groovy inside the JavaGroovy inside the Java

- Easy to embed groovy scripts in java Easy to embed groovy scripts in java applicationsapplications

- Object oriented approach of groovy Object oriented approach of groovy languagelanguage

- Three ways to use a groovy script inside a Three ways to use a groovy script inside a java applicationjava application- Adopting Adopting GroovyShell to evaluate groovy expressionsGroovyShell to evaluate groovy expressions- Dynamic loading and using Groovy classesDynamic loading and using Groovy classes- Using the Using the GroovyScriptEngineGroovyScriptEngine to run groovy scripts to run groovy scripts

GroovyShell ApproachGroovyShell Approach

Uses Uses GroovyShellGroovyShell to execute and evaluate to execute and evaluate groovy scriptsgroovy scripts

Follow the steps below:Follow the steps below: Include groovy libraries in your classpathInclude groovy libraries in your classpathSet binding object for passing the parameters Set binding object for passing the parameters

to methodsto methodsUse evaluate method of shell to run the scriptUse evaluate method of shell to run the script

GroovyShell Approach(Example)GroovyShell Approach(Example)import groovy.lang.Binding;import groovy.lang.GroovyShell;public class TestGS {

public static void main(String[] args) {Binding binding = new Binding();binding.setVariable( “foobar”, new Integer(2) );GroovyShell shell = new GroovyShell( binding );shell.evaluate(

“println ‘Hello Class!’;” +“calendar =

Calendar.getInstance().get(Calendar.AM_PM);” +“(calendar == Calendar.AM) ?

println(\”Good morning\”) : println(\”Good evening\”);” +“println ‘foobar is ‘ + foobar;”);

}}

TestGS.java

Dynamic Loading ApproachDynamic Loading Approach

Uses Uses GroovyClassLoaderGroovyClassLoader to dynamically to dynamically create and load your groovy classescreate and load your groovy classes

No binding objects requiredNo binding objects requiredFollow the steps below:Follow the steps below:

Include groovy libraries in your classpathInclude groovy libraries in your classpathCreate groovy class scriptCreate groovy class scriptUse GroovyClassLoader to parse the script Use GroovyClassLoader to parse the script

and create the classand create the class

GroovyShell Approach(Example)GroovyShell Approach(Example)

class Gsquare{

public int square( int a ){

return a * a}

}

First create your groovy class script( i.e First create your groovy class script( i.e GSquare.groovy ) and then the test GSquare.groovy ) and then the test code( i.e TestGCL.java )code( i.e TestGCL.java )

GSquare.groovy

GroovyShell Approach(Ex. Cont’d)GroovyShell Approach(Ex. Cont’d)package pkgGroovyClassLoader;import groovy.lang.GroovyClassLoader;import groovy.lang.GroovyObject;import java.io.File;import java.io.IOException;import org.codehaus.groovy.control.CompilationFailedException;public class TestGCL {

public static void main(String[] args) throws CompilationFailedException, IOException, InstantiationException, IllegalAccessException {

GroovyClassLoader loader = new GroovyClassLoader();Class groovyClass = loader.parseClass( new

File(“Gsquare.groovy”) );GroovyObject groovyObject = (GroovyObject)

groovyClass.newInstance(); // create an instance// set parameters and call a methodObject arg = new Integer( 3 );Object answer = groovyObject.invokeMethod(“square”, arg);System.out.println( answer.toString() );

}}

TestGCL.java

Dynamic Loading Approach(2)Dynamic Loading Approach(2)

Alernatively in dynamic class loading Alernatively in dynamic class loading approach interfaces can be utilizedapproach interfaces can be utilized

Again no binding objects requiredAgain no binding objects requiredFollow the steps below:Follow the steps below:

Include groovy libraries in your classpathInclude groovy libraries in your classpathCreate groovy class scriptCreate groovy class scriptUse GroovyClassLoader to parse the script Use GroovyClassLoader to parse the script

and create the classand create the class

GroovyShell Approach(Example)GroovyShell Approach(Example)

public interface MyInterface {public int square( int a );

}

In addtion to your class script you should In addtion to your class script you should implement an interface to it in java (i.e implement an interface to it in java (i.e MyInterface.java)MyInterface.java)

class IGsquare implements MyInterface{

public int square( int a ){

return a * a}

}

IGSquare.groovyMyInterface.java

GroovyShell Approach(Ex. Cont’d)GroovyShell Approach(Ex. Cont’d)

package pkgGroovyClassLoader;import groovy.lang.GroovyClassLoader;import java.io.File;import java.io.IOException;import org.codehaus.groovy.control.CompilationFailedException;public class ITestGCL {

public static void main(String[] args) throws CompilationFailedException, IOException, InstantiationException, IllegalAccessException {

GroovyClassLoader loader = new GroovyClassLoader();Class groovyClass = loader.parseClass( new

File(“IGSquare.groovy”) );MyInterface myObject = (MyInterface)

groovyClass.newInstance();int answer = myObject.square( 3 );System.out.println( answer );

}}

ITestGCL.java

GroovyScripEngine ApproachGroovyScripEngine Approach

Uses Uses GroovyScriptEngine GroovyScriptEngine to run groovy to run groovy scriptsscripts

Follow the steps below:Follow the steps below: Include groovy libraries in your classpathInclude groovy libraries in your classpathSet binding object for passing the parameters Set binding object for passing the parameters

to methodsto methodsDefine a root that stores your scripts Define a root that stores your scripts

embeddedembeddedUse run method of secript engine to run the Use run method of secript engine to run the

scriptscript

GroovyShell Approach(Example)GroovyShell Approach(Example)

output = “Hello, ${input}!”foobar = 2

Very similar to shell instead this time you Very similar to shell instead this time you run scripts in .groovy filesrun scripts in .groovy files

Key Points:Key Points: Binding keeps values assigned in these scriptsBinding keeps values assigned in these scripts Tracing of modification of scripts inside the root defined Tracing of modification of scripts inside the root defined

and updating the other dependent scripts accordinglyand updating the other dependent scripts accordingly

GHello.groovy

GroovyShell Approach(Ex. Cont’d)GroovyShell Approach(Ex. Cont’d)

package pkgGroovyScriptEngine;import java.io.IOException;import groovy.lang.Binding;import groovy.util.GroovyScriptEngine;import groovy.util.ResourceException;import groovy.util.ScriptException;public class TestGSE {

public static void main(String[] args) throws CompilationFailedException, IOException, InstantiationException, IllegalAccessException {

String[] roots = new String[] { “./” };GroovyScriptEngine gse = new GroovyScriptEngine(roots);Binding binding = new Binding();binding.setVariable(“input”, “Class”);gse.run(“Ghello.groovy”, binding);System.out.println(binding.getVariable(“output”));System.out.println( “foobar is “ +

binding.getVariable(“foobar”));}

}

TestGSE.java

Groovy MarkupGroovy Markup

Support for various markup languages Support for various markup languages such as:such as:XML XML HTMLHTMLSAXSAXW3C DOMW3C DOMAntsAntsSwing UI Swing UI

XML-Tree GenerationXML-Tree Generation Manages XML-Tree generationManages XML-Tree generation MarkupBuilder() method is usedMarkupBuilder() method is used

data = [ 'Seçkin': [ 'eBay':7, 'GittiGidiyor':5 ], 'Canan': [ 'eBay':9, 'GittiGidiyor':4 ] ]xml = new groovy.xml.MarkupBuilder()xml.people() { for ( entry in data ) { person( name: entry.key ) { for ( e_shop in entry.value ) { online_shop(){ name( e_shop.key ) rating( e_shop.value ) } } } }}

XML-Tree Generation ResultXML-Tree Generation Result<people> <person name='Seçkin'> <online_shop> <name>eBay</name> <rating>7</rating> </online_shop> <online_shop> <name>GittiGidiyor</name> <rating>5</rating> </online_shop> </person> <person name='Canan'> <online_shop> <name>eBay</name> <rating>9</rating> </online_shop> <online_shop> <name>GittiGidiyor</name> <rating>4</rating> </online_shop> </person></people>

AdvantagesAdvantagesGeneral General

syntactical syntactical simplicitysimplicity

Ease of use of Ease of use of closures and closures and iteratorsiterators

XML-Tree ParsingXML-Tree Parsingxml = """<people> <person name='Seçkin'> <online_shop> <name>eBay</name> <rating>7</rating> </online_shop> <online_shop> <name>GittiGidiyor</name> <rating>5</rating> </online_shop> </person> <person name='Canan'> <online_shop> <name>eBay</name> <rating>9</rating> </online_shop></person></people>"""people = new groovy.util.XmlParser().parseText( xml )people.person['@name']

Similar to JavaSimilar to JavaUses XMLParser() Uses XMLParser()

methodmethodAdvantage:Advantage:

- Much easier to - Much easier to implement compared implement compared to Javato Java

GroovySQLGroovySQL Ease of JDBC programming with power of closures and Ease of JDBC programming with power of closures and

iteratorsiterators

A simple code that prints the people’s names in the A simple code that prints the people’s names in the database:database:

import groovy.sql.Sqlimport java.sql.DriverManager;

sql = Sql.newInstance("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=tempdb", "sa", "sa", "com.microsoft.jdbc.sqlserver.SQLServerDriver" );

sql.eachRow("select * from GroovySQL", { println it.id + " -- ${it.firstName} ${it.lastName} --"} );

Web DevelopmentWeb Development

Groovylet is basically the Groovylet is basically the counterpart of counterpart of a a Servlet in JavaServlet in Java

Alternative to servletAlternative to servletSame with Servlet as programming Same with Servlet as programming

capabilities are consideredcapabilities are consideredSyntactically simple and easy( groovy )Syntactically simple and easy( groovy )

Groovylet

Using GroovyletUsing Groovylet

Setting system variables and environmentSetting system variables and environmentPlace the archives Place the archives groovy.jar and asm.jargroovy.jar and asm.jar into into

thethe WEB-INF/libWEB-INF/lib directory and configure the directory and configure the buildpathbuildpath

IInsert the following tags to nsert the following tags to WEB-INF/web.xmlWEB-INF/web.xml filefile <servlet>

<servlet-name>Groovy</servlet-name> <servlet-class>groovy.servlet.GroovyServlet</servlet-class></servlet><servlet-mapping> <servlet-name>Groovy</servlet-name> <url-pattern>*.groovy</url-pattern></servlet-mapping>

Groovylet (Example)Groovylet (Example)

Login.html

<html> <head><title>Login</title></head> <body>

<h3>Enter your credentials</h3> <form action="Login.groovy" method=POST>

Username: <input type=text name=username size=20> Password: <input type=text name=password size=20>

</form></body></html>

Create a Create a simple HTML file that takes simple HTML file that takes username and password from user and do username and password from user and do from action "Login.groovyfrom action "Login.groovy””

Groovylet (Ex. Cont.’d)Groovylet (Ex. Cont.’d)

def username= request.getParameter("username")def password= request.getParameter("password")if (username == "java" && password == "developer") { response.sendRedirect("home.jsp") session = request.getSession(true); session.setAttribute("name", username)}else { println """ <h1>Login Invalid</h1> <p>Your IP has been logged > ${request.remoteHost}</p> """ paramMap = request.getParameterMap() println "<p>You Submitted:</p>" for (entry in paramMap) { println "${entry.key} = ${entry.value}<br/>" }}

Login.groovy

ConclusionConclusion Groovy scripting language is in progress. If you are Groovy scripting language is in progress. If you are

accustomed to use other languages a lot, it is possible accustomed to use other languages a lot, it is possible for you to find one more language unnecessary but for you to find one more language unnecessary but Groovy seems to be a language in competition with our Groovy seems to be a language in competition with our favorite languages and have the potential to take place favorite languages and have the potential to take place of them. of them.

In the meantime, Groovy has a lot going for it. It nicely In the meantime, Groovy has a lot going for it. It nicely blends some of the most useful features of Ruby, blends some of the most useful features of Ruby, Python, and Smalltalk, while conserving core syntax Python, and Smalltalk, while conserving core syntax based on the Java language. For developers familiar based on the Java language. For developers familiar with the Java platform, Groovy provides a simpler with the Java platform, Groovy provides a simpler alternative with almost no ramp-up time. For developers alternative with almost no ramp-up time. For developers new to the Java platform, it may act as an easy entry new to the Java platform, it may act as an easy entry point to the more extensive syntax and requirements of point to the more extensive syntax and requirements of the Java language.the Java language.

ReferencesReferences

groovy.codehaus.org/ groovy.codehaus.org/ http://www.onjava.com/pub/a/onjava/http://www.onjava.com/pub/a/onjava/

2004/09/29/groovy.html2004/09/29/groovy.htmlhttp://www.indicthreads.com/articles/http://www.indicthreads.com/articles/

1131/1131/groovy_grails_getting_started_guide.htmlgroovy_grails_getting_started_guide.html