Groovy easy to get started--grails combat basics

Source: Internet
Author: User
Tags i18n mkdir create domain grails log4j
Before learning anything, the most important thing is to cultivate interest, groovy one of the world's most dazzling technology--grails believe that we have already heard, I will be through the Grails Combat series to show you the charming style of grails, so that you feel the charm of grails, To fall madly in love with Grails and fall in love with groovy. Learn groovy,grails and learn Java, you need to build a development environment before the actual combat, you can easily get started in groovy-build a groovy development environment to learn how to build a groovy environment, then I will talk about how to build a grails environment, And then the hand-written demo program ended, I will also take time to write a "groovy easy to get started--grails combat Advanced article" one, to build grails environment 0, download grails (http://dist.codehaus.org/grails/ Grails-bin-1.0.zip, be aware of the "latest version" hint from--groovy & grails in the flower and extract it to your location (my location is D:\D\MY_DEV\grails) 1, set the environment variable Grails_ HOME (note capitalization), the procedure is similar to "Set environment variable Groovy_home" 2, add%grails_home%\bin to the environment variable path, and "Append bin in Groovy_home directory to environment variable path" Similar (if you only want to do grails development, you can do without groovy_home) two, create Grails demo program 3, open "command line", select the current directory (my D:\Temp\grails_apps), on the Black-white window, enter "Grails Create-app Demo ", not including double quotes", you can see output similar to the following in your screen: D:\_dev\grails_apps>grails create-app demowelcome to Grails 1.0- Http://grails.org/Licensed under Apache standard License 2.0Grails home is set to:d:\d\my_dev\grails-1.0base directory:d : \_dev\grails_appsenvironment set to Developmentnote:no plugin scripts foundrunning script D:\D\MY_DEV\grails-1.0\scripts\createapp.groovy [mkdir] Created dir:d:\_dev\grails_apps\demo\src [mkdir] Created dir:d:\_dev\ Grails_apps\demo\src\java [mkdir] Created Dir:d:\_dev\grails_apps\demo\src\groovy [mkdir] Created dir:d:\_dev\grails _apps\demo\grails-app [mkdir] Created dir:d:\_dev\grails_apps\demo\grails-app\controllers [mkdir] Created dir:d:\_ dev\grails_apps\demo\grails-app\services [mkdir] Created dir:d:\_dev\grails_apps\demo\grails-app\domain [mkdir] Created dir:d:\_dev\grails_apps\demo\grails-app\taglib [mkdir] Created dir:d:\_dev\grails_apps\demo\grails-app\ Utils [mkdir] Created dir:d:\_dev\grails_apps\demo\grails-app\views [mkdir] Created dir:d:\_dev\grails_apps\demo\ grails-app\views\layouts [mkdir] Created dir:d:\_dev\grails_apps\demo\grails-app\i18n [mkdir] Created dir:d:\_dev\ grails_apps\demo\grails-app\conf [mkdir] Created dir:d:\_dev\grails_apps\demo\test [mkdir] Created dir:d:\_dev\ Grails_apps\demo\test\unit [mkdir] Created dir:d:\_dev\grails_apps\demo\test\integration [mkdir] Created dir:d:\_dev\grails_apps\demo\scripts [mkdir] Created Dir:d:\_dev\grails_apps\demo\web-app [ MKDIR] Created dir:d:\_dev\grails_apps\demo\web-app\js [mkdir] Created dir:d:\_dev\grails_apps\demo\web-app\css [ MKDIR] Created dir:d:\_dev\grails_apps\demo\web-app\images [mkdir] Created dir:d:\_dev\grails_apps\demo\web-app\ web-inf\classes [mkdir] Created dir:d:\_dev\grails_apps\demo\web-app\meta-inf [mkdir] Created Dir:d:\_dev\grails_ Apps\demo\lib [mkdir] Created dir:d:\_dev\grails_apps\demo\grails-app\conf\spring [mkdir] Created dir:d:\_dev\grails _apps\demo\grails-app\conf\hibernate[propertyfile] Creating new Property file:d:\_dev\grails_apps\demo\ application.properties [Copy] Copying 2 files to D:\_dev\grails_apps\demo [copy] Copying 2 files to D:\_dev\grails_apps\de Mo\web-app\web-inf [Copy] Copying 5 files to d:\_dev\grails_apps\demo\web-app\web-inf\tld [copy] Copying all files to D:\_d Ev\grails_apps\demo\web-app [Copy] Copying files to D:\_dev\grails_aPps\demo\grails-app [Copy] Copying 1 file to D:\_dev\grails_apps\demo [copy] Copying 1 file to D:\_dev\grails_apps\demo [C Opy] Copying 1 file to D:\_dev\grails_apps\demo[propertyfile] Updating property file:d:\_dev\grails_apps\demo\ application.propertiescreated grails application at d:\_dev\grails_apps/demod:\_dev\grails_apps> through the Grails Create-app "This command, Grails automatically helped us create the engineering environment needed for development. In fact, you already have a running Web application, then go to the Demo directory ("CD demo"), enter "Grails Run-app", return, start the ' perfectly formed ' program prototype, open the browser, enter http://localhost : 8080/demo, enter, you see:) Let's go ahead, please stop this program (Ctrl + C) 4, enter "CD demo" in "Command line" and enter to enter the demo directory and then "Grails create-domain-class User" to create domain Class is similar to Pojo's Pogo, which corresponds to the model in MVC, but Pogo created by grails is empty and needs to add properties, constraints (constraints) and so on. The output results are as follows: D:\_dev\grails_apps\demo>grails create-domain-class userwelcome to Grails 1.0-http://grails.org/ Licensed under Apache standard License 2.0Grails home is set to:d:\d\my_dev\grails-1.0base Directory:d:\_dev\grails_apps \demoenvironment set to Developmentnote:no plugin scripts FoundrunNing script D:\D\MY_DEV\grails-1.0\scripts\CreateDomainClass.groovy [copy] Copying 1 file to d:\_dev\grails_apps\demo\ grails-app\domaincreated for User [copy] Copying 1 file to d:\_dev\grails_apps\demo\test\integrationcreated Tests for use Rd:\_dev\grails_apps\demo>5, enter D:\Temp\grails_apps\demo\grails-app\domain (this directory contains all the domain classes), Open User.groovy, modified to read as follows: Class User {string name string password string toString () {"$name: $password"} static Constrai NTS = {Name (blank:false) password (blank:false, Size:6.)}} contraints This class variable is defined by some constraints, such as name cannot be blank, password cannot be blank and Length between 6 and 16 (including 6 and 16) 6, enter "Grails generate-all User" in the "command line", For the user to generate all the required code for CRUD operations (such as Controller Usercontroller.groovy) and pages (such as LIST.GSP), the output is as follows: D:\_dev\grails_apps\demo>grails Generate-all Userwelcome to Grails 1.0-http://grails.org/licensed under Apache standard License 2.0Grails home are set to : D:\D\MY_DEV\grails-1.0Base directory:d:\_dev\grails_apps\demoenvironment set to Developmentnote:no plugin scripts Foundrunning SCRipt D:\D\MY_DEV\grails-1.0\scripts\GenerateAll.groovy [mkdir] Created dir:d:\_dev\grails_apps\demo\web-app\ Web-inf\lib [mkdir] Created dir:c:\documents and settings\daniel\.grails\1.0\projects\demo\classes [GROOVYC] Compiling 7 source files to C:\Documents and settings\daniel\.grails\1.0\projects\demo\classes [mkdir] Created dir:c:\do Cuments and Settings\daniel\.grails\1.0\projects\demo\resources\grails-app\i18n[native2ascii] Converting files From d:\_dev\grails_apps\demo\grails-app\i18n to C:\Documents and settings\daniel\.grails\1.0\projects\demo\ resources\grails-app\i18n [Copy] Copying 1 file to C:\Documents and settings\daniel\.grails\1.0\projects\demo\classes [ Copy] Copying 1 file to C:\Documents and settings\daniel\.grails\1.0\projects\demo\resources [copy] Copying 1 file to c:\d Ocuments and Settings\daniel\.grails\1.0\projects\demo[0] spring. Grailswebapplicationcontext refreshing org.codehaus.groovy.grails.commons.spring.grailswebapplicationcontext@ 2b2057:display name [oRG.CODEHAUS.GROOVY.GRAILS.COMMONS.SPRING.GRAILSWEBAPPLICATIONCONTEXT@2B2057]; startup Date [Tue Feb 23:26:45 CST 2008]; Root of context hierarchy[16] spring. Grailswebapplicationcontext Bean Factory for application context [ ORG.CODEHAUS.GROOVY.GRAILS.COMMONS.SPRING.GRAILSWEBAPPLICATIONCONTEXT@2B2057]: org.springframework.beans.factory.support.defaultlistablebeanfactory@eebf17generating views for domain class User ... Generating controller for domain class User ... Finished generation for domain class userd:\_dev\grails_apps\demo>7, modifying demo\grails-app\controllers\ The contents of Usercontroller.groovy are: Class Usercontroller {def loginservice//new Code DEF index = {Redirect (Action:list,params:para MS)}//The Delete, save and update actions only accept POST requests def allowedmethods = [Delete: ' Post ', Save: ' Post ', u Pdate: ' POST ' def list = {if (!params.max) Params.max = ten [UserList:User.list (params)} def show = {def User = use R.get (params.id) if (!user) {flash.message = "User not found WITH ID ${params.id} "redirect (Action:list)} else {return [User:user]}} def delete = {def user = User.get (params. ID) if (user) {User.delete () Flash.message = "User ${params.id} deleted" Redirect (Action:list)} else {flash.message = " User not found with ID ${params.id} "redirect (Action:list)}} def edit = {def user = User.get (params.id) if (!user) {f Lash.message = "User not found with ID ${params.id}" redirect (Action:list)} else {return [User:user]}} def update = {def user = User.get (params.id) if (user) {user.properties = params if (!user.haserrors () && user.save ()) {FL Ash.message = "User ${params.id} updated" redirect (Action:show,id:user.id)} else {render (view: ' Edit ', Model:[user:user ]}}} else {flash.message = "User not found with ID ${params.id}" redirect (Action:edit,id:params.id)}} def create = { def user = new User () User.properties = params return [' User ': User]} def save = {def user = new User (params) if (!user.ha Serrors () && USER.SAve ()) {flash.message = "User ${user.id} created" redirect (Action:show,id:user.id)} else {render (view: ' Create ', model:[ User:user]}}//new code DEF LOGIN = {if (Request.method = = ' POST ') {User U = New User () U.properties = params if (!u.va Lidate ()) {render (view: ' Login ', Model:[user:u]} if (Params.name && params.password) {def user = Loginservice.c Heck (u) if (user) {flash.message = "Welcome ${user.name}" render (view: "OK", model: [User:user])} else {flash.error = "Invalid ${u.name} with ${u.password}" render (view: "Login", model: [User:u])}} else {render (view: "Login", model: [US Er:u]}}}} You may have seen the class loginservice, and I'll show you how to create it, the Loginservice class encapsulates all the business logic that's involved in the login, and grails automatically injects it into Usercontroller 8, in the " Command line, enter "Grails create-service Login", create Loginservice.groovy, output: D:\_dev\grails_apps\demo>grails create-service Loginwelcome to Grails 1.0-http://grails.org/licensed under Apache standard License 2.0Grails home is set To:d:\d\my_de V\grails-1.0base directory:d:\_dev\grails_aPps\demoenvironment set to Developmentnote:no plugin scripts foundrunning script D:\D\MY_DEV\grails-1.0\scripts\ Createservice.groovy [Copy] Copying 1 file to d:\_dev\grails_apps\demo\grails-app\servicescreated Service for Login [ Copy] Copying 1 file to d:\_dev\grails_apps\demo\test\integrationcreated servicetests for Logind:\_dev\grails_apps\ Demo>9, modify the contents of the Demo\grails-app\services\loginservice.groovy: Class Loginservice {Boolean transactional = True def Check (User u) {def user = User.findwhere (name:u.name, Password:u.password) return user}}10, in Demo\grails-app\views\user Directory to create LOGIN.GSP and OK.GSP, which correspond to the view in MVC, the contents are: LOGIN.GSP (copy demo\grails-app\views\user\create.gsp content to LOGIN.GSP, and modify) : Home User List Login${flash.error}
Name:
Password:
OK.GSP: ${flash.message} Name: ${user?. Name
Password: ${user? Password}11, modify the Demo\grails-app\conf\bootstrap.groovy, initialize the database: Save a user instance to the database (Grails comes with Hsqldb and jetty) with the following contents: Class BootStrap {def init = {ServletContext-new User (Name: "Demo", Password: "123456"). Save ()} def destroy = {}} 12, in the " Command line, enter "Grails Run-app" and run our web App with the output as follows: D:\_dev\grails_apps\demo>grails run-appwelcome to Grails 1.0-http:// Grails.org/licensed under Apache standard License 2.0Grails home is set to:d:\d\my_dev\grails-1.0base directory:d:\_dev\ Grails_apps\demoenvironment set to Developmentnote:no plugin scripts foundrunning script D:\D\MY_DEV\grails-1.0\ Scripts\runapp.groovy [GROOVYC] compiling 4 source files to C:\Documents and settings\daniel\.grails\1.0\projects\demo\ Classesrunning Grails Application. 2008-02-05 23:46:08.912::info:logging to STDERR via org.mortbay.log.stderrlog2008-02-05 23:46:08.066::info: jetty-6.1.42008-02-05 23:46:08.347::info:no Transaction Manager found-if Your webapp requires one, please configure one .2008-02-05 23:46:09.081:/demo:info:set Web App root system property: ' Demo ' = [d:\_dev\grails_apps\demo\web-app\]2008-02-05 23:46:09.081:/demo:info:initializing log4j from [File:c:\documents and settings\daniel/.grails/1.0/projects/demo/ resources/log4j.properties]2008-02-05 23:46:09.113:/demo:info:initializing Spring Root webapplicationcontext[0] Spring. Grailswebapplicationcontext refreshing org.codehaus.groovy.grails.commons.spring.grailswebapplicationcontext@ 5facbd:display name [ORG.CODEHAUS.GROOVY.GRAILS.COMMONS.SPRING.GRAILSWEBAPPLICATIONCONTEXT@5FACBD]; startup Date [Tue Feb 23:46:14 CST 2008]; Parent:org.springframework.web.context.support.xmlwebapplicationcontext@1fef80a[0] Spring. Grailswebapplicationcontext Bean Factory for application context [ ORG.CODEHAUS.GROOVY.GRAILS.COMMONS.SPRING.GRAILSWEBAPPLICATIONCONTEXT@5FACBD]: org.springframework.beans.factory.support.defaultlistablebeanfactory@aa4c7c2008-02-05 23:46:21.590:/demo:INFO: Initializing Spring frameworkservlet ' grails ' 2008-02-05 23:46:21.871::info:started Selectchannelconnector@0.0.0.0:8080server running. Browse to Http://localhost:8080/demo 13, open the browser, enter: Http://localhost:8080/demo/user/login, enter demo at name, Password Enter 123456, click ' Login ', jump to the Success page: Welcome demoname:demopassword:123456 If you're not familiar with Grails's engineering catalogue, I'm here to provide a table for you, Describes the purpose of each directory in detail: "Grails authoritative guide" table 3-1. Grails Project Catalog Name related description Grails-app This directory contains the core artifacts of the Grails application (core artifact) + conf This directory contains configuration files such as Developmentdatasource.groovy + Controllers This directory contains the controller that handles requests (request), grails controller will be explained in chapter 7th + domain This directory contains the domain model, and the domain model will be explained in chapter 4th + i18n This directory contains message bundles for internationalization (note: Refers to properties files, such as messages.properties) + Services This directory contains service files that encapsulate the business logic, The service will be explained in the 10th Chapter + taglib This directory contains the dynamic tag library generated by the secondary page, the dynamic label will be explained in chapter 8th + views This directory contains the Groovy Server page (GSP) and JSP page + Layouts This directory contains the layout of the GSP or JSP (layout), which is supported by Sitemesh. This will be explained in the 8th Chapter grails-test This directory contains the application's unit test hibernate this directory contains optional hibernate profiles, This will be explained in the 11th Chapter LIB this directory contains the jar file spring This directory contains the optional spring configuration file, which will be explained in chapter 11th SRC This directory contains other groovy and Java resources + Java This directory contains the Java source files to be compiled + Groovy This directory contains the pending compilationGroovy source Files Web-app This directory contains resources for Web applications (CSS,JAVASCRIPT, etc.) Note: Grails1.0 has moved hibernate and spring two directories to the grails-app\conf directory, The Grails-test directory is also renamed to the Test,test directory with the integration directory and the unit directory, respectively, to store the integration test Code and unit test code to imagine creating the same Web application using the framework combination (such as SSH) that you use to do your project. You immediately feel that Grails lets us focus on the business logic without wasting time on those scaffolding code (such as configuration files). Starting today, you don't have to envy the ROR that Ruby programmers use, and you can use Grails to efficiently develop Web applications. You can also visit the Grails official website (http://www.grails.org) for further study.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.