您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關vue+spring boot如何實現校驗碼功能,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
用vue寫了一個校驗碼來玩玩,樣子如下:
1.img標簽
<img ="height:40px; width: 100px; cursor: pointer;" ref="imgIdentifyingCode" :src="selectedLogoPicture.imgUrl" class="logoImg" >
2.js代碼
/** * 獲取校驗碼 */ getIdentifyingCode() { let selft = this; //let pic = this.$refs.imgIdentifyingCode selft.loadingChack = true; let uuid = Utils.getUuid(32, 16); this.$store.state.uuid = uuid; this.$api.reader.getVerify( { responseType: "arraybuffer", uuid: uuid }, r => { selft.loadingChack = false; selft.selectedLogoPicture.imgUrl = "data:image/png;base64," + r; } ); },
3.controller
@RequestMapping("/getVerify") public void getVerify(@RequestParam String uuid, HttpServletRequest request, HttpServletResponse response) { response.setContentType("image/jpeg");// 設置相應類型,告訴瀏覽器輸出的內容為圖片 response.setHeader("Pragma", "No-cache");// 設置響應頭信息,告訴瀏覽器不要緩存此內容 response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expire", 0); userService.getRandcodedDawTransparent(uuid, request, response);// 輸出驗證碼圖片方法 }
4.service
@Override public void getRandcodedDawTransparent(String uuid, HttpServletRequest request, HttpServletResponse response) { try { Map<String, Object> map = CodeUtil.getRandcodedDawTransparent(); // 將生成的隨機字符串保存到session中 log.info("==保存的uuid:"+uuid); log.info("==保存的code:"+map.get("code")); sessionUtil.saveCode(uuid, map.get("code")); response.setContentType("image/png"); OutputStream out = response.getOutputStream(); out.write((byte[]) map.get("img")); out.flush(); out.close(); } catch (IOException e) { log.error(e.getMessage()); } }
5.util
public static Map<String, Object> getRandcodedDawTransparent() throws IOException { Map<String, Object> rsMap = new HashMap<>(); // 創建BufferedImage對象 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 獲取Graphics2D Graphics2D g2d = image.createGraphics(); // 增加下面代碼使得背景透明 image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT); g2d.dispose(); g2d = image.createGraphics(); g2d.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));// 字體大小 g2d.setColor(getRandColor(110, 133));// 字體顏色 // 繪制干擾線 for (int i = 0; i <= lineSize; i++) { drowLine(g2d, width, height); } // 繪制隨機字符 String randomString = ""; for (int i = 1; i <= stringNum; i++) { randomString = drowString(g2d, randomString, i); } log.info(randomString); rsMap.put("code", randomString); g2d.dispose(); ByteArrayOutputStream baos = new ByteArrayOutputStream();// io流 ImageIO.write(image, "png", baos);// 寫入流中 byte[] bytes = baos.toByteArray();// 轉換成字節 bytes = Base64.encodeBase64(bytes); rsMap.put("img", bytes); return rsMap; }
關于“vue+spring boot如何實現校驗碼功能”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。