Summary
Java Web Application Framework is the enterprise Java is one important reason for success. People wonder if there is no Apache Struts framework for Java EE could be so successful. Although the underlying programming language is important, however, the framework is usually to make the programming language into the center of attention. If you frequently visit the discussion forum, you'll notice that Ruby language and Ruby On Rails framework is also the case between. Ruby has been there 10 years, but only popular in the Ruby On Rails framework, the developers began to notice Ruby language.
Such as Ruby, PHP and Python scripting languages like more and more popular in recent years, therefore, need to develop a Java scripting language, and similar alternative Rails framework against Java environment. Groovy is the scripting language, and Grails is the framework.
In this article I will discuss Groovy's Web development features, and then continue to discuss the Grails framework. I will develop a sample Grails Web application, and discuss the various features of this framework.
What is Groovy?
Groovy is a language, its syntax is similar to Java, but simpler than Java. It is often regarded as the script / flexible / dynamic language, but I do not like this type of adjective, because I think they will only cause confusion. If Java is a wise middle-aged man, then Groovy is his teenage son. Groovy has many characteristics of his father, but more wild and more fun. They could also very well together.
Groovy far fewer rules than Java. For example, to get the standard Java "Hello World" output, you need to write a class, a main method with appropriate parameters, and so on. But in Groovy, if you do not want to write all the boilerplate code, you can put aside the class definition and the main method, you can only write one line of code prints out "Hello World".
The following is a document to print Hello World Hello.groovy content:
println "Hello World"
Java byte code platform is concerned only to be implemented. Similarly, the platform does not force you to use the Java language. Provide a byte code as long as the work will be conducted. Groovy code will be compiled to byte code, but for the Java platform, the byte code from Java code or Groovy code generated no difference.
The following is a Groovy example, it shows 浜?Groovy on the list, map and extent of De built-in support, and prove the simplicity of its use Groovy, Java, Jiang Tai Neng Li features:
/ / Print Date
def mydate = new java.util.Date ()
println mydate
/ / Iterate through a map
def numbersMAP = [''1'':'' ONE'',''2'':'' TWO'']
for (entry in numbersMAP) (
println "$ = $"
)
/ / Introducing the range
def range =''a''..'' d''
/ / Lists
def numberlist = [1, 2, 3, 4, 5, 6, 7, 8]
println numberlist;
println "Maximum value: $"
Please note that the above code to be used directly java.util.Date, built-in support of the collection to reduce the use of lists, map and extent of the required code. Groovy There are many other interesting features, such as closure and simplified XML processing. You can find a detailed list of groovy.codehaus.org.
Let us now discuss how to Groovy for Web development.
For Web development using Groovy
Most Java EE servlet tutorial is a basic example from the beginning. The Groovy Web development is, you will groovlet (the groovy concept in the corresponding servlet) started. If you are in out of the servlet class and doXX () method declaration, then the rest of the content on and groovlet like a. The following is an example of named Login.groovy of groovlet, you need to place it the most advanced Web application directory:
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 "" "
Login Invalid
Your IP has been logged> $
"" "
paramMap = request.getParameterMap ()
println "
You Submitted:
"
for (entry in paramMap) (
println "$ = $
"
)
)
You can just create a simple HTML form, then this form of behavior attributes sent to the action = "Login.groovy". Then add the following tag to web.xml:
Groovy
groovy.servlet.GroovyServlet
Groovy
*. Groovy
Now simply add the required Groovy jar files to the WEB-INF/lib directory of your Groovy Web applications on any Java EE application ready to run the server.
You should have noticed the code is not a semicolon, and the use of implicit variables, such as request and response. Other implicit variables context, application, session, out, sout, and html.
GSP is the corresponding JSP in the groovy concept. You do not need to use println generate HTML; Simply Groovy code embedded in HTML pages. Examples of this article will be referred to the use of Grails GSP.
Please note that because all the code will eventually be converted to byte code, so groovlet and GSP can easily collaborate with the servlet and JSP. So you do not distinguish groovlet and the GSP or the servlet and JSP.
Let us now discuss the promising Grails framework. If successful, Grails can significantly change the development of Java Web applications that way. Ruby Ruby on Rails on the impact, Grails Groovy can also achieve.
Grails features and architecture
Ruby On Rails Grails attempts to use the "statute of programming" (coding by convention) to reduce sample configuration files and other boilerplate code requirements. Use the "Statute of the programming", if the file name itself can explain the purpose of this document, then you do not need another statement in the configuration file such content. This framework will see the file name and file their own clear purpose. By using the "Statute of the programming", Grails will automatically generate Web applications that need many of the content. By using Grails, you will be able in a short period of time, to minimize the complexity of the Web application ready. See the following example.
Grails based on open source technologies such as Spring, Hibernate and SiteMesh. If you already good at these technologies, this is a good thing; but for some reason if you do not like these technologies, or if you think that not only need to learn Grails, also need to learn the other three frames, this is not a good thing. Although the implementation of these technologies can help Grails better, but for most people to learn the four framework is a very high threshold. Grails documentation is currently focused on it with Spring, Hibernate, and other processes of integration, but I think it needs to adopt the opposite approach, implemented as a simple Grails rapid Web application development framework. Developers need to consider the underlying fear or what happened.
Fortunately, once you start using Grails, you will find these frameworks Grails hides most of the underlying complexity. If you forget to run in the bottom of the Spring, Hibernate and other procedures, then things will become simpler.
By the view and controller layer composed of Web
By a domain consisting of business logic classes and services
From the domain classes and data resources in the persistence layer
Most frameworks have dozens of properties, which only a small few have been widely used. For Grails, this key feature is the "rule programming" (coding by convention) the automatic generation of examples and components.
Other features include Grails Ajax, validation, unit testing and functional testing of the built-in support. It uses a free open-source Canoo WebTest project to implement Web application functional testing. Grails also provides integration with the Quartz Scheduler.
It is time to install the Grails framework and write your first application.
Grails Installation
Installation process is very simple. The following is Grails download page: http://grails.org/Download. You can http://dist.codehaus.org/grails/grails-bin-0.2.1.zip download version 0.2.1. Note that the Grails source code and documentation provided as a separate download. Download zip file, simply extract the contents to a directory can be, in my case, this directory is C: groovygrails-0.2.1.
Create a new environment variable called GRAILS_HOME and set its value to C: groovygrails-0.2.1. Next will be added to the PATH environment variable GRAILS_HOMEbin. This installation is complete. Interface through the command prompt to run grails command you can check the installation was successful. You should get usage information for this command.
Now that you have a running Grails installation, then you have to create a Grails Web application ready.
Grails Application Development: Application Structure
Over the years I have been planning to develop clothing that can help me manage the application - the application should be able to tell me my favorite T-shirt on where it washed, ironed it, and so on. Someday I'll earn on the sale of the application of millions, but now I will use it as an example Grails.
The first step is to create a Grails project directory structure. In this step I will be C: groovygrailsapps create a new directory, and on this level to open a command prompt window. In this window, execute the command grails create-app. Asked to enter your application name. Enter ClothesMgt. Grails will show it to you to create all the directories and files. Figure 1 shows the structure of the last received command.
Figure 1: Grails project directory structure
This command will create about 800 KB size of the files and directories. The idea here is to follow this framework has been established Web application development practices, so it creates files and directories in most Web applications is useful. Although some people may not like the idea of mandatory use of a structure, but the practice of automatically generated based on the RAD features of Grails is based.
If you look more carefully these directories, you will find that there is for such as controllers, views, testing, configuration files and things like tag library directory. You'll also find some basic JavaScript and CSS files. So now the basic structure of the application has been made. You only need to do to fill in the blank, the application can be ready.
Please note that auto-generated directories and file with the command is optional. You can manually create all the files and directories. If you are familiar with Apache Ant, so you can even open GRAILS_HOME directory srcgrailsbuild.xml file to carefully review the use of each Grails command.
Database
In this case I will use a running on localhost called Clothes_Grails the MySQL database. Built a Grails HSQL database, which is a simple test application that is useful or just try Grails. If you are using HSQL DB, so no need to perform the following steps. I will use MySQL to prove that you can very easily use a database other than HSQL.
Download MySQL from http://www.mysql.com/products/connector/j/ drive, and mysql-connector-java - stable-bin.jar file placed in the ClothesMgtlib directory. Next you need to edit ClothesMgtgrails-appconfApplicationDataSource.groovy file.
Now the contents of this file should be similar to the following:
class ApplicationDataSource (
boolean pooling = true
String dbCreate = "create-drop"
String url = "jdbc: mysql: / / localhost / Clothes_Grails"
String driverClassName = "com.mysql.jdbc.Driver"
String username = "grails"
String password = "groovy"
)
Now let's look at how to use this database and object-relational mapping.
Field class
Grails Object-Relational Mapping (GORM) function for internal use Hibernate 3, but you do not understand or change any Hibernate settings. Grails is called "domain class" thing, these domain classes are mapped to the database object. You can use the relationships to link domain classes, they also provide for CRUD (create / read / update / delete) operations very powerful dynamic method.
In this case, we will create three domain classes, their names are Shirt, Trouser, and Cabinet. To create a domain class, just run the command grails create-domain-class. Please remember in your project directory (not its parent directory) within the run this command. This is a common mistake, although I have to remind you that you still guilty of at least one such error.
You must provide to the create-domain-class command only input is the class name. Run this command three times, the Shirt, Trouser, and Cabinet as the name of the three domain classes. Grails will now be in the directory grails-app/domain / create the domain class. They will only have two properties id and version. I will add the properties of these classes in order to make them more representative of the shirt, pants and wardrobe.
Listing 1: Cabinet.groovy
class Cabinet (
Long id
Long version
String name
String location
def relatesToMany = [shirts: Shirt, trousers: Trouser]
Set shirts = new HashSet ()
Set trousers = new HashSet ()
String toString () ("$: $ id")
boolean equals (other) (
if (other?. is (this)) return true
if (! (other instanceof Cabinet)) return false
if (! id | |! other?. id | | id! = other?. id) return false
return true
)
int hashCode () (
int hashCode = 0
hashCode = 29 1 10 11 12 13 14 15 16 17 18 19 2 20 21 22 23 24 25 26 27 28 29 3 30 31 32 4 5 6 7 8 9 (hashCode + (! id 1 2 3 4 5 6 7 8 9 0: id ^ (id>>> 32)))
)
)
Listing 2: Trouser.groovy
class Trouser (
Long id
Long version
String name
String color
Cabinet cabinet
def belongsTo = Cabinet
String toString () ("$: $ id")
boolean equals (other) (
if (other?. is (this)) return true
if (! (other instanceof Trouser)) return false
if (! id | |! other?. id | | id! = other?. id) return false
return true
)
int hashCode () (
int hashCode = 0
hashCode = 29 1 10 11 12 13 14 15 16 17 18 19 2 20 21 22 23 24 25 26 27 28 29 3 30 31 32 4 5 6 7 8 9 (hashCode + (! id 1 2 3 4 5 6 7 8 9 0: id ^ (id>>> 32)))
)
)
Listing 3: Shirt.groovy
class Shirt (
Long id
Long version
String name
String color
Cabinet cabinet
def belongsTo = Cabinet
String toString () ("$: $ id")
boolean equals (other) (
if (other?. is (this)) return true
if (! (other instanceof Shirt)) return false
if (! id | |! other?. id | | id! = other?. id) return false
return true
)
int hashCode () (
int hashCode = 0
hashCode = 29 1 10 11 12 13 14 15 16 17 18 19 2 20 21 22 23 24 25 26 27 28 29 3 30 31 32 4 5 6 7 8 9 (hashCode + (! id 1 2 3 4 5 6 7 8 9 0: id ^ (id>>> 32)))
)
)
I add only a few lines of a statement of the field names and colors, and then declare the Cabinet, Shirt and Trouser relationship. Each Shirt and Trouser belong to Cabinet, the Cabinet has the shirt and trouser set. belongsTo attribute is optional in this case, because one to many relationship, Grails will be "one" side as the owner. So you do not need to explicitly declared. Here, I explicitly declared only to make this relationship more evident.
Next we will discuss the Grails application, controller and view part.
Controller and view
Since the domain classes are ready, let's use the generate-all command automatically generates basic CRUD Web application. Grails generate-all command run three times, when classes are asked to provide domain name. The purpose of generate-all command is generated for each domain controller and view classes, but because of bug-245, Grails 0.2.1 can not generate the controller. You must manually generate the controller, the method is used for each domain class generate-controller command.
You should now be in the grails-appcontrollers directory see three controllers. The controller is responsible for Web application requests for a particular domain class. Therefore ShirtController.groovy Web applications will handle the domain class associated with the Shirt CRUD request, and so on. Now the controller has multiple closure, each closure is mapped to a URI. Language Groovy closure is a good feature, but get used to it or take some time. Listing 4 shows an excerpt Shirtcontroller.groovy.
Listing 4: ShirtController.groovy extract
class ShirtController (
def index = (redirect (action: list, params: params))
def list = (
[ShirtList: Shirt.list (params)]
)
def show = (
[Shirt: Shirt.get (params.id)]
)
def delete = (
def shirt = Shirt.get (params.id)
if (shirt) (
shirt.delete ()
flash.message = "Shirt $ deleted."
redirect (action: list)
)
else (
flash.message = "Shirt not found with id $"
redirect (action: list)
)
)
/ / ...
)
In this case, ShirtController closure of the list will be dealing with URI is / shirt / list of requests, and so on. You can use your controller used in the Java Web applications using things such as request, session and servletContext.
Please note: the value of the closure will be as explicit return statement, or as a closure body in the last statement of the value returned. Do not Grails does not return the generated code rather confused.
Once the controller to complete the processing of the request, it must be entrusted to the appropriate view. Grails uses custom mechanisms to achieve this. The list, therefore ShirtController closure will be entrusted to view / grails-app/views/shirt/list.gsp or / grails-app/views/shirt/list.jsp. While you are using Grails, all views can be JSP files instead of GSP. I almost did not write any code, but I'm ready for a Web application.
Let us try to deploy and run our application.
In the Java EE Server to deploy and run Grails
Grails has a built-in Resin server, you can use the grails run-app command to run the application. This command will deploy to the Resin application server and start the server. Http://localhost:8080/ClothesMgt so you can now access this application. You can also easily deployed to any JavaEE application server. I try to deploy it to Tomcat. To achieve this, I need to do is to run the grails war command to generate the war file to Tomcat's webapps directory in!
In this case, the resulting war file name is ClothesMgt.war. Once deployed to Tomcat, you should be able to access it in http://localhost:8080/ClothesMgt/ and see the screen shown in Figure 2.
Figure 2: Grails application
Through this application, access Shirt, Trouser, and Cabinet of all the CRUD functionality. Can display all the data closet to the wardrobe to add a new shirt and pants, edit and delete records of their value - to achieve all these operations without writing any business logic, view, or data access code. Only a few minutes you'll be better deployed in the JavaEE server, a proper Web application. Cool? !
Let us further customize Grails.
Create a custom controller
I will add new features and pages to the Web application, while reusing existing domain classes. shirt / list and trouser / list will display shirts and pants were a list, let us add a new display to simultaneously display a list of shirts and pants. To create a new display, you need a new controller and view.
Use generate-controller and generate-views command, you can easily use the fields automatically generated view and controller classes. However, in this case I want to create a class not directly associated with the domain controller. I will use the grails create-controller command. When prompted for the controller name, declare Display. Grails will grails-app/controllers / directory to create a controller called DisplayController.groovy in grails-tests directory to create a test suite. Edit controller as shown in Listing 5.
Listing 5: DisplayController.groovy
class DisplayController (
def index =
def list = (
params [''max''] = 10
return [shirtList: Shirt.list (params),
trouserList: Trouser.list (params)]
)
)
index redirect the request to the closure list. Closure in the list I will be the largest parameter set to 10, and then use the dynamic method Shirt.list and Trouser.list. Then return Groovy Map, it has two lists - the list of shirts and trousers list.
As a Java developer, when you see the Shirt.list () will naturally think that is the domain class in the list Shirt methods. However, if you open Shirt.groovy, will find that this method does not. For Java developers, do not know the characteristics of Groovy on Grails is not only confusing to use, and is a dead end. Grails dynamic method is a special feature, which is built on the Groovy language features a very special meta object protocol (MOP) above. So that you can use the dynamic method to query the domain class. Therefore, the controller, you will notice that the domain class called the method seems the domain class does not exist. Here you can read on the use of dynamic methods of inquiry for more information. Can be found here on the Grails controller and the domain class dynamic methods available in reference.
Since the controller can process the request, obtain and forward the list to the view, I need to create the appropriate view.
Create a custom view
When you create a controller, Grails also grails-appviews directory created a new show directory, and add the following to the web.xml file maps.
grails
/ Display / *
Grails currently has a generate-views command, this command can generate domain classes based on the view, however, does not automatically generate the view create-view command. See the example in Figure 3.
Figure 3: The default view of a display Trousers
I want to create an independent view of the domain class, so let us create a view file manually. Grails-appviewsdisplay in the directory, create a file named list.gsp, as shown in Listing 6.
Listing 6: list.gsp
Shirt List
Id Cabinet Color Name
$ $ $ $
Trouser List
Id Cabinet Color Name
$ $ $ $
And similar to the way I used before, you can now use the run-app command to run applications, or create a war file and deploy it to Tomcat. You should see the new view under http://localhost:8080/ClothesMgt/display/ shown in Figure 4.
Figure 4: The new shirts and pants to create the list view list
Now let's quickly discuss the Grails services.
Service
If you want to know how to separate the business logic and business logic of the position to place the answer in Grails service. Services to SomeNameService.groovy format name, and is placed in / grails-app/services / directory. Service dependency injection features available, you can easily call these services from the controller.
Let's look at an example of using the service. First, use create-service command to create new services. Run this command and naming services Order. Grails will create two files --grails-app/services/OrderService.groovy and grails-tests/OrderTests.groovy.
Now edit OrderService.groovy, as shown in Listing 7. When introducing new orderGoods () method will automatically generate serviceMethod ().
Listing 7: OrderService.groovy
class OrderService (
boolean transactional = true
def serviceMethod () (
/ / TODO
)
def orderGoods () (
return "Order Placed - New shirts and trousers
will be sent shortly. "
)
)
Now edit DisplayController, as shown in Listing 8. Rearrangement of the introduction of the use OrderService closure. Please note that service will be injected into Groovy.
Listing 8: DisplayController.groovy
class DisplayController (
OrderService orderService
def index =
def list = (
params [''max''] = 10
return [shirtList: Shirt.list (params)
, TrouserList: Trouser.list (params)]
)
def reorder = (
render (orderService.orderGoods ())
)
)
Now when you visit the URL http://localhost:8080/ClothesMgt/display/reorder, the rearrangement of the closure will be called OrderService, response will be sent back to the browser. You can be in a similar manner to all the business logic moved to service, and then use the injection of Grails feature is easy to use them.
Dynamic methods and properties
As previously mentioned, the domain class is not able to obtain data from the database, or update / delete the existing data in any way, such as find (), findAll () or save (). In the controller you do not write like redirect () or render () method like. But the domain classes and controllers have their aim of the project, and allow all the requested operation. The reason is Grails dynamic methods and properties exist. Dynamic method is dynamically added to the class, just like function is the same as compiled in the program.
These are the available methods and properties, without writing. These methods cover the most dynamic Web application development will face a common situation. For domain classes, the existence of such as find (), findAll (), list (), executeQuery (), save () and delete () method like dynamic.鎺у埗鍣ㄥ叿鏈夎濡俿ession銆乺equest鍜宺esponse涔嬬被鐨勫姩鎬佸睘鎬э紝浠ュ強璇稿chain()銆乺ender()鍜?redirect()涔嬬被鐨勬柟娉曘?瑕佺湡姝e埄鐢℅rails鐨勫己澶у姛鑳斤紝鎮ㄩ渶瑕佷簡瑙f墍鏈夎繖浜涘姩鎬佹柟娉曞拰灞炴?鐨勫姛鑳姐?
銆??椤轰究浠嬬粛涓?笅锛氳嚜鍔ㄩ噸杞藉拰@Property
銆??Grails鐨勪竴涓噸瑕佺壒鎬ф槸鑳藉鍦ㄥ紑鍙戣繃绋嬩腑杩涜浜嗘洿鏀规椂鑷姩閲嶈浇鏂囦欢銆傚洜姝ゅ彧闇?紪杈戝拰淇濆瓨gsp鏂囦欢锛屽氨浼氳嚜鍔ㄩ噸杞芥柊鏂囦欢銆傜劧鑰岃繖閲屽垱寤虹殑绫讳技OrderService 鐨勪簨鍔℃湇鍔′笉浼氳閲嶈浇銆傛偍浼氬湪鏈嶅姟鍣ㄦ帶鍒跺彴鐪嬪埌浠ヤ笅娑堟伅"[groovy] Cannot reload class [class OrderService] reloading of transactional service classes is not currently possible. Set class to non-transactional first. "銆?br />
銆??Grails鐨勮嚜鍔ㄩ噸杞藉姛鑳戒細涓烘偍鑺傜渷璁稿鏃堕棿锛屾偍灏辨棤闇?氮璐规椂闂存潵閲嶅惎鏈嶅姟鍣ㄤ簡銆傛垜纰板埌杩囦竴浜汫rails涓嶈兘鑷姩閲嶈浇鐨勬渚嬶紝渚嬪灏嗕竴涓猨sp鏂囦欢閲嶅懡鍚嶅埌gsp銆傜劧鑰岋紝Grails鐨勮繖椤瑰姛鑳芥湁鏈涘湪鏈潵鐗堟湰涓緱鍒拌繘涓?鏀硅繘銆?br />
銆??鍦℅roovy JSR 06 鐨勪箣鍓嶇増鏈腑锛屾偍蹇呴』浣跨敤@Property 鏉ュ畾涔塆roovy涓殑鏂板睘鎬с?鍥犳鎮ㄤ細鍦ㄧ嚎鐪嬪埌璁稿浣跨敤@Property鐨勬棫鐨凣roovy渚嬪瓙銆傜劧鑰岃娉ㄦ剰锛孈Property宸茬粡浠嶨roovy JSR 06涓Щ闄わ紝鍦℅rails 0.2鍜屼箣鍚庣殑鐗堟湰涓篃涓嶄細鍐嶉渶瑕佸畠銆傝鍙傞槄@Property 寤鸿鏉ヨ幏寰楁洿澶氱粏鑺傘?
Conclusion
銆??鍦ㄦ湰鏂囦腑锛屾垜浠嬬粛浜咷rails妗嗘灦鐨勫熀鏈壒鎬э紝骞朵娇鐢℅rails鍒涘缓浜嗕竴涓簲鐢ㄧ▼搴忋?Groovy鍜孏rails鏈?ぇ鐨勫ソ澶勬槸涓?垏閮借繍琛屽湪浼樼鐨勬棫Java鍜孞ava EE涓娾?鈥斿洜姝ゆ偍鑳藉浣跨敤Groovy鍜孏rails鐨凴AD鐗规?蹇?寮?彂搴旂敤绋嬪簭锛岀劧鍚庡皢搴旂敤绋嬪簭閮ㄧ讲鍒板彲闈犵殑Java EE鏈嶅姟鍣ㄤ笂銆傝?铏戝埌鍏充簬Ruby鍜孯ails鐨勫浼犲櫔闊筹紝鏄剧劧闇?涓?釜Java澶囬?鏂规銆侴roovy鍜孏rails鐪嬭捣鏉ラ潪甯搁?鍚堣繖涓鑹层?
相关链接:
Top Shell ToolsChina Unicom to introduce iPhone would be wastedCatalogs Clipboard Toolsavc-freeSenior Advanced: 12 strokes overall Speed of your Firefox 3.5CURRENT choice: RMVB movie subtitles DafaRelationship Is Kind Of A Very Mysterious ThingUsing the seven combat the Heart Jakarta Strutsreviews Games And EntertainmentPowerBuilder menu creationConvert Mp3 To Aac3D TV Is a pie or a bubble?Comments Terminal And Telnet Clients.mkv"Warriors serpent Z" list of people attribute XiangjieFree Mp4 To 3gp Converter