您好,欢迎访问一九零五行业门户网

PlayFramework完整实现一个APP(七)

1.添加验证码
application controller添加captcha()
public static void captcha() {
images.captcha captcha = images.captcha();
renderbinary(captcha);
}
添加route
get     /captcha                                application.captcha
访问 http://localhost:9000/captcha
验证码图片已经实现了,现在需要做的是验证输入信息与验证码一致
修改captcha()方法
public static void captcha(string id) {
images.captcha captcha = images.captcha();
string code = captcha.gettext(#e4eafd);
cache.set(id, code, 10mn);
renderbinary(captcha);
}
修改show()方法
public static void show(long id) {
   post post = post.findbyid(id);
   string randomid = codec.uuid();
   render(post, randomid);
}
修改show.html页面
在comment下方添加验证码图片,和验证控件
  <p>
       <label for="content">your message: </label>
       <textarea name="content" id="content">${params.content}</textarea>
   </p>
   <p>
    <label for="code">please type the code below: </label>
    <img src="@{application.catcha(randomid)}">
    <br />
    <input type="text" name="code" id="code" size="18" value="" />
    <input type="hidden" name="randomid" value="${randomid}" />
   </p>
   <p>
       <input type="submit" value="submit your comment" />
   </p>
2.验证
修改postcomment 方法
public static void postcomment(
long postid,
@required(message=author is required) string author,
@required(message=a message is required) string content,
@required(message=please type the code) string code,
string randomid) {
   post post = post.findbyid(postid);
   validation.equals(code, cache.get(randomid)).message(invalid code. please type it again);
if(validation.haserrors()) {
    render(application/show.html, post);
   }
post.addcomment(author, content);    flash.success(thanks for posting %s, author);
   cache.delete(randomid);
   show(postid);
}
修改show.html页面
  #{iferrors}
       <p class="error">
           ${errors[0]}
       </p>
   #{/iferrors}
以上就是playframework完整实现一个app(七)的内容。
其它类似信息

推荐信息