Groovy轻松入门——Grails实战基础篇(3)

4,在“命令行”中,输入“grails create-controller Login”,创建登陆(login)的控制器LoginController,它对应MVC中的Controller,让它负责登陆相关业务,输出如下:

D:/Temp/grails_apps/demo>grails create-controller Login

Welcome to Grails 0.4.2 - http://grails.org/
Licensed under Apache Standard License 2.0
Grails home is set to: D:/D/MY_DEV/grails

Base Directory: D:/Temp/grails_apps/demo
Environment set to production
Running script D:/D/MY_DEV/grails/scripts/CreateController.groovy
    [mkdir] Created dir: D:/Temp/grails_apps/demo/grails-app/views/login
     [copy] copying 1 file to D:/Temp/grails_apps/demo/grails-app/controllers
Created Controller at D:/Temp/grails_apps/demo/grails-app/controllers/LoginContr
oller.groovy
     [copy] copying 1 file to D:/Temp/grails_apps/demo/grails-tests
Created ControllerTests at D:/Temp/grails_apps/demo/grails-tests/LoginController
Tests.groovy
D:/Temp/grails_apps/demo>

5,修改demo/grails-app/controllers/LoginController.groovy的内容为:

class LoginController {
    def loginService

    def index = { }
    
    def login = {
        User u = new User()
        u.properties = params
        if (params.name && params.password) {

            def user = loginService.check(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: [user: u])
        }
    }
}

大家或许也看到了LoginService这个类,我将在后面演示创建它,这个LoginService类封装了所有登陆相关的业务逻辑,Grails自动将其注入到LoginController中。

6,在“命令行”中,输入“grails create-service Login”,创建LoginService.groovy,输出

D:/Temp/grails_apps/demo>grails create-service Login

Welcome to Grails 0.4.2 - http://grails.org/
Licensed under Apache Standard License 2.0
Grails home is set to: D:/D/MY_DEV/grails

Base Directory: D:/Temp/grails_apps/demo
Environment set to production
Running script D:/D/MY_DEV/grails/scripts/CreateService.groovy
     [copy] copying 1 file to D:/Temp/grails_apps/demo/grails-app/services
Created Service at D:/Temp/grails_apps/demo/grails-app/services/LoginService.gro
ovy
     [copy] copying 1 file to D:/Temp/grails_apps/demo/grails-tests
Created ServiceTests at D:/Temp/grails_apps/demo/grails-tests/LoginServiceTests.
groovy
D:/Temp/grails_apps/demo>

7,修改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
    }
    
    def serviceMethod() {
        // Todo
    }
}

相关文章

背景:    8月29日,凌晨4点左右,某服务告警,其中一个...
https://support.smartbear.comeadyapi/docs/soapui/steps/g...
有几个选项可用于执行自定义JMeter脚本并扩展基线JMeter功能...
Scala和Java为静态语言,Groovy为动态语言Scala:函数式编程,...
出处:https://www.jianshu.com/p/ce6f8a1f66f4一、一些内部...
在运行groovy的junit方法时,报了这个错误:java.lang.Excep...