📜 ⬆️ ⬇️

Grails - the holy grail of a web developer

grails

Entry or torment of choice


Hello! I want to tell a little about Grails and show how to create a simple web application. To begin with, I was looking for a convenient and functional web framework for rapid development. My view alternately fell on Django, Ruby on Rails, and various Java development. Of course, I like Java, Spring Framework and Hibernate, all together is the most powerful thing. However, some moments did not suit me:

I began to look for an alternative. PHP was brushed aside right away due to the imperfection of this language and the traditions of “bicycle construction”. As an amateur Python was tested by Django, who liked its simplicity and convenience. I think that doing small projects on Django is just right, but I did not like the limited functionality of the template engine, for example, the lack of conditions and the assignment of variables in the templates. Of course, some may say that there should be a minimal logic in the pattern — no variables or branching. I dare say that in my opinion in real projects this creates numerous inconveniences. True, in the new version of Django, these problems will be solved soon. With all the advantages of this framework, I don’t like its procedural orientation - although this is a purely subjective opinion, as well as procedural orientation of Python itself, as if the OOP appeared in it only yesterday, and the lack of means to protect the application code at the level of the programming language itself - in Pyhton there are no constants, in the class all methods and properties are open, and in order to make a member of a class private, it is necessary to use underscores, which makes the code extremely unpleasant in reading. I looked at Ruby as an improved version of Python with a big emphasis on OOP, but I, like many who have tried Ruby, pushed the interpreter's syntax and inactivity, although in Ruby 1.9 things are much better. I wanted something else. And I found it - the holy grail.

Groovy - Java Next


As a Java fan, I began to look at Groovy, the language of the new generation based on Java. It is a compiled programming language with a nice Java syntax, easy to use and concise, with great power. A Groovy program is compiled into the bytecode of the Java virtual machine. The main advantages include compatibility with Java at the level of code and libraries, support for functional programming, a lot of convenient syntax sugar, and a lot of new features that will make our world better :) From Groovy, you can use Java classes and libraries, so that all your experience does not will be left behind. Of the drawbacks of Groovy, the dynamic typing of this language should be noted - although the types of variables can be specified explicitly, all checks occur at the stage of code execution, rather than compilation, as a result we have a lag compared to Java, and as shown by tests, the Groovy code is on average 40 times slower than similar Java code. But this problem, I think, will soon have a full-fledged solution - Groovy ++, a static code compiler that has recently appeared, allows using both dynamic and static typing in one project. Static typing is enabled using annotations, and according to the test results, the code becomes commensurate with the speed of execution with “classic” Java code.
')

Holy grail


For those who do not know, I'm talking about Grails - a web framework for developing web applications in the language of the new generation - Groovy. Why grails? Grails has absorbed the best of the existing technology. By ideology, it is similar to Ruby on rails and until some time it was called quite similar - Groovy on Rails, and then it was reduced to the usual now “Grails”. Grails is a add-on for Spring, Hibernate with the Sitemesh template engine and gsp user tags. Unlike Spring, where additional libraries are needed to create a simple application, everything in Grails is included out of the box, no XML configurations need to be set up, and all manipulations are done in a simple and natural way. Grails is now owned by a Java development leader, Spring Source. For Grails, there are plugins that extend its capabilities, for example, acegi for working with authorization and authentication. Grails follows the MVC principle, offers convenient tools for binding URLs to controllers, localizing applications, validating these models, and more. A typical project structure is the following:

 % PROJECT_HOME%
	 + grails-app
		 + conf -> settings
			 + hibernate
			 + spring
			 BootStrap.groovy -> application download
			 BuildConfig.groovy -> build setup
			 Config.groovy -> general settings
			 DataSource.groovy -> DB Settings
			 UrlMappings.groovy -> URL Bindings to Controllers
		 + controllers -> controllers
		 + domain -> models
		 + i18n -> localization
		 + services -> services
		 + taglib -> custom tags
		 + utils -> helper classes
		 + views -> views
			 + layouts -> layouts (template containers)
	 + lib -> libraries
	 + plugins -> plugins for grails
	 + scripts -> scripts
	 + src
		 + groovy
		 + java
		 + main
	 + target
	 + test -> unit tests
	 + web-app
		 + WEB-INF

So, it's time to try the Grails.

Fast start


We will need the following tools:

Download and unpack Grails (http://www.grails.org/Releases), set the GRAILS_HOME environment variable, which indicates the full path to the unpacked archive, for example ~ / grails, and add GRAILS_HOME / bin to the launch path. Download the IDE at www.grails.org/STS+Integration , install and configure as described on the site.

Now let's create the skeleton of our testapp application using Maven:

$ mvn org.apache.maven.plugins: maven-archetype-plugin: 2.0-alpha-4: generate -DarchetypeGroupId = org.grails -DarchetypeArtifactId = grails-maven-archetype -DarchetypeVersion = 1.2.0 -DgroupId = testapp -DartifactId testapp

$ cd testapp
$ mvn initialize

Now we run Eclipse and import our application. File -> Import -> Existing Projects into Workspace

After importing, you will see the following structure:

Project structure

Now let's configure our application. Open the file grails-app / conf / DataSource.groovy and see the following content:

  dataSource {
	 pooled = true
	 driverClassName = "org.hsqldb.jdbcDriver"
	 username = "sa"
	 password = ""
 }
 hibernate {
     cache.use_second_level_cache = true
     cache.use_query_cache = true
     cache.provider_class = 'net.sf.ehcache.hibernate.EhCacheProvider'
 }
 // environment specific settings
 environments {
	 development {
		 dataSource {
			 dbCreate = "create-drop" // one of 'create', 'create-drop', 'update'
			 url = "jdbc: hsqldb: mem: devDB"
		 }
	 }
	 test {
		 dataSource {
			 dbCreate = "update"
			 url = "jdbc: hsqldb: mem: testDb"
		 }
	 }
	 production {
		 dataSource {
			 dbCreate = "update"
			 url = "jdbc: hsqldb: file: prodDb; shutdown = true"
		 }
	 }
 } 

dataSource contains settings for connecting to the database. Let's adapt them to work with mysql:

  dataSource {
	 pooled = true
	 driverClassName = "com.mysql.jdbc.Driver"
	 username = "root"
	 password = ""
 }

We look further, we see the following section:

  environments {
	 development {
		 dataSource {
			 ...
		 }
	 } 

The environments section describes the modes of operation of the application. There are only three of them: development mode, testing mode and production mode. Each mode uses its own settings for connecting to the database. At the moment we are interested in the development mode, we will correct the settings as follows:

  development {
	 dataSource {
		 dbCreate = "update"
		 url = "jdbc: mysql: // localhost: 3306 / testapp"
	 }
 } 

Do not forget to check that the mysql service is running, and the testapp database is created.

Next, open the file grails-app / conf / BuildConfig.groovy. As I wrote above, this is the application build file. We are interested in the following piece of code:

  repositories {        
         grailsPlugins ()
         grailsHome ()

         // uncomment resolution
         // from public Maven repositories
         // mavenLocal ()
         // mavenCentral ()
         // mavenRepo "http://snapshots.repository.codehaus.org"
         // mavenRepo "http://repository.codehaus.org"
         // mavenRepo "http://download.java.net/maven/2/"
         // mavenRepo "http://repository.jboss.com/maven2/"
     }
     dependencies {
         // specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes eg.

         // runtime 'mysql: mysql-connector-java: 5.1.5'
     } 

This is a section for removing dependencies during assembly. Fix it like this:

  repositories {        
         grailsPlugins ()
         grailsHome ()

         // uncomment resolution
         // from public Maven repositories
         mavenLocal ()
         mavenCentral ()
         // mavenRepo "http://snapshots.repository.codehaus.org"
         mavenRepo "http://repository.codehaus.org"
         mavenRepo "http://download.java.net/maven/2/"
         // mavenRepo "http://repository.jboss.com/maven2/"
     }
     dependencies {
         // specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes eg.

         runtime 'mysql: mysql-connector-java: 5.1.5'
     } 

We have added the mysql driver. And now it's time to create a simple application. To begin with, we will create a Product model, for this we need to execute the create-domain-class command in the Grails console. When creating models, we do not need to manually create a table in the database, Grails will do it by itself. In Eclipse, open: Navigate -> Open Grails Command Prompt and execute:

grails> create-domain-class com.testapp.Product

The process of creating a model can be seen in the Eclipse console. If at creation you saw the following message:
Application expects grails version [1.2.0], but GRAILS_HOME is version [1.2.1] - you can use it if you want.

This means that with maven you created the skeleton application for grails 1.2.0, and you have a newer version on the system. Follow the instructions and run the upgrade command:

grails> upgrade

If the model creation process was successful, you will see the following code in grails-app / domain / Product.groovy:

  package com.testapp

 class Product {

     static constraints = {
     }
 } 

Fill the model with the fields we need - product name, description and price:

  class Product {

	 String name
	 String description
	 Float price
	 static constraints = {
		 name (nullable: false, blank: false, size: 1..50)
		 description (nullable: false, blank: false, size: 1..255)
	 }
	
	 String toString () {
		 return name; 
	 }
 } 

Wonderful! Now let's create a CRUD for it. For this, we don’t need to write controllers and views, and we can do with one command that generates everything by itself:

grails> generate-all com.testapp.Product

As a result, we see:

Generating views for domain class com.testapp.Product ...
Generating controller for domain class com.testapp.Product ...
Finished generation for domain class com.testapp.Product

This command has generated:
com.testapp.ProductController controller
display create.gsp, edit.gsp, list.gsp, show.gsp in the directory grails-app / views / product

On this our simple application is ready. Now you can run it using the run-app command. The running application will be available at localhost : 8080 / testapp

image

image

image

image

Source: https://habr.com/ru/post/86790/


All Articles