Groovy&Grails-插件应用-Simple Captcha Plugin

信息

  • 评级:4星
  • 版本:0.9.4
  • 更新:2013-09-27
  • 适用:Grails2.0.0 > *

简介

创建简单的图像验证码,防止自动完成和提交HTML表单

安装


compile ":simple-captcha:0.9.4"

使用

页面访问


<img src="${createLink(controller: 'simpleCaptcha', action: 'captcha')}"/>
<label for="captcha">Type the letters above in the box below:</label>
<g:textField name="captcha"/>

后台调用


class MyController {
    def simpleCaptchaService

    // This is the action that handles the submission of the form with the CAPTCHA
    def save = { 
        boolean captchaValid = simpleCaptchaService.validateCaptcha(params.captcha) 
    } 
}

配置

在Config.groovy中增加


simpleCaptcha {
    // font size used in CAPTCHA images
    fontSize = 30
    height = 200
    width = 200

    // number of characters in CAPTCHA text 
    length = 6

    // amount of space between the bottom of the CAPTCHA text and the bottom of the CAPTCHA image 
    bottomPadding = 16

    // distance between the diagonal lines used to obfuscate the text 
    lineSpacing = 10

    // the charcters shown in the CAPTCHA text must be one of the following 
    chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    // this param will be passed as the first argument to this java.awt.Font constructor 
    // http://docs.oracle.com/javase/6/docs/api/java/awt/Font.html#Font(java.lang.String,%20int,%20int) 
    font = "Serif"
}

应用

创建测试工程


$grails create-app example-simplecaptcha
$grails create-domain-class com.example.user

给domain增加属性


package com.example

class User {

    String username
    String fullname
    String password

    static constraints = {
        username()
        fullname()
        password()
    }
}

引入插件,生成脚手架


$grails install-plugin simple-captcha
$grails compile

$grails generate-all com.example.user

修改views/user/_form.gsp,在代码最后增加


<div class="fieldcontain">
    <img src="${createLink(controller: 'simpleCaptcha', action: 'captcha')}"/>
    <label for="captcha">Type the letters above in the box below:</label>
    <g:textField name="captcha"/>
</div>

修改controllers/UserController.groovy,修改save方法


def save() {
    boolean captchaValid = simpleCaptchaService.validateCaptcha(params.captcha)
    if(!captchaValid) {
        flash.message = "验证码错误"
        render(view: "create")
        return
    }
    def userInstance = new User(params)
    if (!userInstance.save(flush: true)) {
        render(view: "create", model: [userInstance: userInstance])
        return
    }

    flash.message = message(code: 'default.created.message', args: [message(code: 'user.label', default: 'User'), userInstance.id])
    redirect(action: "show", id: userInstance.id)
}

参考

  • 插件地址
  • 参考书-apress-Beginning Groovy, Grails and Griffon

你可能感兴趣的:(Groovy&Grails-插件应用-Simple Captcha Plugin)