繁体   English   中英

具有Scala和Play框架的Recaptcha

[英]Recaptcha with scala and play framework

通过使用tutorial ,我试图在我的play项目中应用验证码。

的HTML

<form action="/applyForWork" method="post" enctype="multipart/form-data">
        <input type="text" name="relevant" id="relevant" >
        <input type="file" name="file"/>
        <br/>
        @Html(views.ReCaptcha.render())
        <br/>
        <input type="submit" value="Upload"/>
</form>

控制者

def applyForWork = Action {
    implicit request =>
      println(request.body.asFormUrlEncoded) //None
      Ok("submitted")
  }

Q1。为什么这个println(request.body.asFormUrlEncoded)给出None


Q2.captcha框显示在我的html中,但是如何验证它是否正确?

我正在使用scala 2.10和play framework 2.2

A1。 这样做的原因是你的形式是enctype。 使用multipart / form-data时,您可以通过以下方式访问表单数据:

request.body.asMultipartFormData

A2。 无论如何,如果我是您,我将坚持您提到的教程中介绍的解决方案,并为Recaptcha值创建表单映射。

case class CaptchaForm(challenge: String, response: String)

val captchaForm = Form[CaptchaForm](
 mapping(
    "recaptcha_challenge_field" -> nonEmptyText,
    "recaptcha_response_field" -> nonEmptyText
  )(CaptchaForm.apply)(CaptchaForm.unapply)
 )

这样,您可以在需要处理Repatcha的任何地方重用它。

def applyForWork = Action { implicit request =>
  captchaForm.bindFromRequest.fold(
    formWithErrors => BadRequest("Captcha Param Error"),
    captchaForm => {
      println(captchaForm.challenge)
      println(captchaForm.response)
      if (check(request.remoteAddress, captchaForm.challenge, captchaForm.response)) {
        //Captcha ok
      }
    }
  ) 
}

def check(remoteAddress: String, challenge: String, response: String): Boolean = {
  val reCaptcha = new ReCaptchaImpl()
  reCaptcha.setPrivateKey(privateKey())
  val reCaptchaResponse = reCaptcha.checkAnswer(remoteAddress, challenge, response)
  reCaptchaResponse.isValid()
}

暗示

考虑在模板中使用路由映射,而不要使用硬编码的URL。 在这种情况下,请更换

action="/applyForWork"

action="@routes.YourFormController.handleAction()"

如果您将映射更改为路线中的操作,则无需更改所有使用该映射的模板。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM