眾所周知,開源的圖形驗證碼kaptcha已經廣泛使用多年了,隨著springboot的發展壯大,kaptcha也有了基於springboot的starter模式,這讓kaptcha的使用更加的簡單,下面就介紹一下如何使用kaptcha starter包來快速實現圖形驗證碼。
引入starter包
kaptcha最早是以jar包的方式發行的,如果要使用就要引入一系列的包,而且要遵循規範引入xml的配置,並且要bean化,雖然步驟不多,但是也比較繁雜一些,自從springboot使用了starter模式,就讓這些工作來的更為簡單。首先在要使用kaptcha的工程中引入kaptcha的starter包。
<code> <dependency> <groupid>com.baomidou/<groupid> <artifactid>kaptcha-spring-boot-starter/<artifactid> <version>1.1.0/<version> /<dependency>/<code>
配置kaptcha
starter模式的配置是和工程主體配置一體化的,也就是放置到application.yml中,相關參數和原先的kaptcha一致,不在多述。
<code>#圖形驗證碼配置kaptcha: height: 50 width: 200 content: length: 4 source: 0123456789abcdefghijklmnopqrstuvwxyz space: 2 font: color: blue name: 宋體,楷體,微軟雅黑 size: 40 background-color: from: lightGray to: white border: enabled: true color: black thickness: 1/<code>
開始使用
通過@Autowired註解kaptcha就可以直接使用了。
<code>@Autowiredprivate Kaptcha kaptcha;/<code>
kaptcha只提供了三個方法:
1. 生成驗證碼render();
<code>@GetMapping("/render") @ApiOperation(value = "獲取圖形驗證碼", notes = "圖形驗證") public void render() { kaptcha.render(); }/<code>
2. 輸入碼驗證
<code>@PostMapping("/valid") @ApiOperation(value = "圖形驗證碼驗證", notes = "圖形驗證") @ApiImplicitParams({ @ApiImplicitParam(paramType = "query", name = "code", value = "輸入驗證碼", dataType = "String") }) public ResponseData validDefaultTime(@RequestParam String code) { ResponseData result=new ResponseData(); try { kaptcha.validate(code); result.setStatus(ResponseCode.SUCCESS); }catch (KaptchaIncorrectException e){ result.setStatus(ResponseCode.GRAPHIC_VERIFICATION_ERROR); }catch (KaptchaNotFoundException e){ result.setStatus(ResponseCode.GRAPHIC_VERIFICATION_NOTFOUND_ERROR); }catch (KaptchaRenderException e){ result.setStatus(ResponseCode.GRAPHIC_VERIFICATION_RENDER_ERROR); }catch (KaptchaTimeoutException e){ result.setStatus(ResponseCode.GRAPHIC_VERIFICATION_EXPIRED_ERROR); } return result; }/<code>
這裡強調一下異常處理,validate方法只有驗證成功返回true,其他錯誤都是通過異常暴露的,所以在程序處理的時候要捕獲這些異常並進行相關處理。
3. 輸入驗證碼超時設置驗證
<code>@PostMapping("/validTime") @ApiOperation(value = "圖形驗證碼驗證,有效期60秒", notes = "圖形驗證") @ApiImplicitParams({ @ApiImplicitParam(paramType = "query", name = "code", value = "輸入驗證碼", dataType = "String") }) public ResponseData validWithTime(@RequestParam String code) { ResponseData result=new ResponseData(); try { kaptcha.validate(code,60); result.setStatus(ResponseCode.SUCCESS); }catch (KaptchaIncorrectException e){ result.setStatus(ResponseCode.GRAPHIC_VERIFICATION_ERROR); }catch (KaptchaNotFoundException e){ result.setStatus(ResponseCode.GRAPHIC_VERIFICATION_NOTFOUND_ERROR); }catch (KaptchaRenderException e){ result.setStatus(ResponseCode.GRAPHIC_VERIFICATION_RENDER_ERROR); }catch (KaptchaTimeoutException e){ result.setStatus(ResponseCode.GRAPHIC_VERIFICATION_EXPIRED_ERROR); } return result; }/<code>
這個方法和2的方法類似,只是增加了超時設置。
前端使用
<code>/<code>
閱讀更多 瘋冰無極 的文章