JFinal框架——簡單驗證碼
阿新 • • 發佈:2017-07-10
ica sof server cati class action 新的 nal size
JFinal很強大,驗證碼的實現也很簡單,在此記錄一下。
- HTML
1 <form action="/jfinal_verification/user/login1" method="post"> 2 用戶名:<input type="text" name="name"/></br> </br> 3 密碼: <input type="password" name="password"/> </br>4 <!-- 設置name為code 用於後臺接收驗證碼並進行校驗--> 5 驗證碼:<input type="text" name="code"/> 6 <!-- 獲取驗證碼並設置點擊事件,點擊之後獲取新的驗證碼 --> 7 <img src="/jfinal_verification/user/code" onclick="this.src=‘/jfinal_verification/user/code?x=‘+Math.random()"></br></br> 8 <buttontype="submit">登陸</button> 9 </form>
- JAVA
JFinal 2.0
生成驗證碼
1 public void code() { 2 CaptchaRender img = new CaptchaRender(RANDOM_CODE_KEY); 3 render(img); 4 }
驗證正確與否
1 private static final String RANDOM_CODE_KEY = "1"; 2 public void login1(){ 3 String inputRandomCode = getPara("inputRandomCode");4 boolean loginSuccess = CaptchaRender.validate(this, inputRandomCode.toUpperCase(), RANDOM_CODE_KEY); 5 if (loginSuccess) { 6 renderText("successful"); 7 }else{ 8 renderText("failed"); 9 } 10}
JFinal 2.2
生成驗證碼
1 public void code(){ 2 renderCaptcha(); 3 }
驗證正確與否
1 private static final String FORM_ITEM_CODE = "inputRandomCode"; 2 3 public void login1(){ 4 String result = ""; 5 //驗證驗證碼 6 if(validateCaptcha(FORM_ITEM_CODE)){ 7 result = "驗證成功"; 8 } 9 else{ 10 result = "驗證失敗"; 11 } 12 renderText(result); 13 }
- 點擊刷新
1 onclick="this.src=‘/user/code?x=‘+Math.random()">
- 註意
- 兩種方法的jar包不同,第二種方法的jar包必須用 jfinal-2.2 及以上,低版本不包含renderCaptcha();
- 若使用jetty,則需要導入jetty-server-8.1.8.jar;若使用Tomcat,則不能加入這個jar包,否則會沖突,並且在action或者src中需要加上你的項目名稱,不能直接寫方法名。
- 效果圖
JFinal框架——簡單驗證碼