溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Java如何實(shí)現(xiàn)滑動(dòng)驗(yàn)證碼

發(fā)布時(shí)間:2022-03-01 09:09:14 來(lái)源:億速云 閱讀:575 作者:小新 欄目:開(kāi)發(fā)技術(shù)

小編給大家分享一下Java如何實(shí)現(xiàn)滑動(dòng)驗(yàn)證碼,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

    功能:java實(shí)現(xiàn)滑動(dòng)驗(yàn)證碼

    項(xiàng)目是采用springboot,maven

    開(kāi)發(fā)工具:采用idea

    1.效果演示

    Java如何實(shí)現(xiàn)滑動(dòng)驗(yàn)證碼

    Java如何實(shí)現(xiàn)滑動(dòng)驗(yàn)證碼

    Java如何實(shí)現(xiàn)滑動(dòng)驗(yàn)證碼

    2.后端代碼

    控制層

    @Controller
    public class SliderCodeController {
     
        @Autowired
        ResourceLoader resourceLoader;
     
        @Autowired
        private FileUtil fileUtil;
     
        // 設(shè)置橫軸位置緩存
        public static Cache< String, Integer > cacheg = CacheBuilder.newBuilder().expireAfterWrite(60, TimeUnit.SECONDS)
                .maximumSize(666666).build();
     
        @GetMapping
        @RequestMapping("index")
        public String test(HttpServletRequest request, Model model) throws IOException {
            return "index";
        }
     
     
        @GetMapping
        @RequestMapping("getImg")
        public @ResponseBody
        Map< String, Object > getPic(HttpServletRequest request) throws IOException {
            try {
                File targetFile = fileUtil.getFile("target");
                File tempImgFile = fileUtil.getFile("temp");
                Map < String, Object > resultMap = VerifyImageUtil.pictureTemplatesCut(tempImgFile, targetFile);
                // 生成流水號(hào),這里就使用時(shí)間戳代替
                String lno = Calendar.getInstance().getTimeInMillis() + "";
                cacheg.put(lno, Integer.valueOf(resultMap.get("xWidth") + ""));
                resultMap.put("capcode", lno);
                // 移除橫坐標(biāo)送前端
                resultMap.remove("xWidth");
                return resultMap;
            }
            catch (Exception e) {
                e.printStackTrace();
                return null;
            }
     
        }
     
     
        @GetMapping
        @RequestMapping("checkImgCode")
        public @ResponseBody Map < String, Object > checkcapcode(@RequestParam("xpos") int xpos,
                                                                 @RequestParam("capcode") String capcode, HttpServletRequest request) throws IOException {
            Map < String, Object > result = new HashMap< String, Object >();
            Integer x = cacheg.getIfPresent(capcode);
            if (x == null) {
                // 超時(shí)
                result.put("code", 3);
            }
            else if (xpos - x > 5 || xpos - x < -5) {
                // 驗(yàn)證失敗
                result.put("code", 2);
            }
            else {
                // 驗(yàn)證成功
                result.put("code", 1);
            }
            return result;
        }
    }

    工具類

    @Component
    public class FileUtil {
     
        @Value("${file.path}")
        private String filePath;
     
        @Value("${file.target.path}")
        private String targetFilePath;
     
        @Value("${file.target.num}")
        private Integer targetfileNum;
     
        @Value("${file.temp.path}")
        private String tempFilePath;
     
        @Value("${file.temp.num}")
        private Integer tempfileNum;
     
        public File getFile(String type){
            int num = 0;
            String imgType = ".jpg";
            String oldFilePath = "";
            if(type.equals("target")){
                num = new Random().nextInt(targetfileNum)  + 1;
                oldFilePath = targetFilePath;
            } else  if(type.equals("temp")){
                num = new Random().nextInt(tempfileNum)  + 1;
                imgType = "-w.png";
                oldFilePath = tempFilePath;
            }
            String path = filePath;
            String fileImg =   num + imgType;
            String filePath = path + fileImg;
            File pathFile = new File(path);
            if(!pathFile.exists()){
                pathFile.mkdirs();
            }
            File file = new File(filePath);
            if(!file.exists()){
                try {
                    file.createNewFile();
                    ClassPathResource classPathResource = new ClassPathResource(oldFilePath + fileImg);
                    InputStream inputStream = classPathResource.getInputStream();
                    if(inputStream.available() != 0){
                        FileUtils.copyInputStreamToFile(inputStream, file);
                    }
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return file;
        }
     
    }

    3.前端頁(yè)面

    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
    <meta charset="UTF-8">
    <title>滑動(dòng)驗(yàn)證碼</title>
    <link rel="stylesheet" href="/css/slide.css" rel="external nofollow" >
    <script src="/js/jquery-1.11.1.min.js"></script>
    <script src="/js/jquery.lgyslide.js"></script>
    </head>
    <body>
    	<div id="imgscode"></div>
    	<script>
    		$(function() {
    			setTimeout(function() {
    				createcode();
    			}, 1000)
    		}());
    		//顯示驗(yàn)證碼
    		function createcode() {
    			$
    					.ajax({
    						type : 'POST',
    						url : '/getImg',
    						dataType : 'json',
    						success : function(data) {
    							if (data != null) {
    								$("#imgscode")
    										.imgcode(
    												{
    													frontimg : 'data:image/png;base64,'
    															+ data.slidingImage,
    													backimg : 'data:image/png;base64,'
    															+ data.backImage,
    													yHeight : data.yHeight,
    													refreshcallback : function() {
    														//刷新驗(yàn)證碼
    														createcode();
    													},
    													callback : function(msg) {
    														console.log(msg);
    														var $this = this;
    														$
    																.ajax({
    																	type : 'POST',
    																	url : '/checkImgCode',
    																	data : {
    																		xpos : msg.xpos,
    																		capcode : data.capcode
    																	},
    																	dataType : 'json',
    																	success : function(
    																			data) {
    																		console
    																				.log(data)
    																		if (data.code == 1) {
    																			$this
    																					.getsuccess();
    																		} else {
    																			if (data.code == 4) {
    																				createcode();
    																			} else if (data.code == 3) {
    																				$this
    																						.getfail("驗(yàn)證碼過(guò)期,請(qǐng)刷新");
    																			} else {
    																				$this
    																						.getfail("驗(yàn)證不通過(guò)");
    																			}
    																		}
     
    																	}
    																})
    													}
    												});
    							}
    						}
    					})
    		}
    	</script>
    </body>
    </html>

    看完了這篇文章,相信你對(duì)“Java如何實(shí)現(xiàn)滑動(dòng)驗(yàn)證碼”有了一定的了解,如果想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

    向AI問(wèn)一下細(xì)節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI