springboot+vue實現驗證碼功能
本文實例為大傢分享瞭springboot+vue實現驗證碼功能的具體代碼,供大傢參考,具體內容如下
1.工具類 直接用不用改
package com.example.demo.Util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.awt.*; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.Map; import java.util.Random; //import java.util.logging.Logger; public class CodeUtil { public static final String RANDOMCODEKEY= "RANDOMVALIDATECODEKEY";//放到session中的key private String randString = "0123456789";//隨機產生隻有數字的字符串 private String //private String randString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";//隨機產生隻有字母的字符串 //private String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//隨機產生數字與字母組合的字符串 private int width = 95;// 圖片寬 private int height = 25;// 圖片高 private int lineSize = 40;// 幹擾線數量 private int stringNum = 4;// 隨機產生字符數量 private static final Logger logger = LoggerFactory.getLogger(CodeUtil.class); private Random random = new Random(); /** * 獲得字體 */ private Font getFont() { return new Font("Fixedsys", Font.CENTER_BASELINE, 18); } /** * 獲得顏色 */ private Color getRandColor(int fc, int bc) { if (fc > 255) fc = 255; if (bc > 255) bc = 255; int r = fc + random.nextInt(bc - fc - 16); int g = fc + random.nextInt(bc - fc - 14); int b = fc + random.nextInt(bc - fc - 18); return new Color(r, g, b); } /** * 生成隨機圖片 */ public void getRandcode(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(); // BufferedImage類是具有緩沖區的Image類,Image類是用於描述圖像信息的類 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); Graphics g = image.getGraphics();// 產生Image對象的Graphics對象,改對象可以在圖像上進行各種繪制操作 g.fillRect(0, 0, width, height);//圖片大小 g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));//字體大小 g.setColor(getRandColor(110, 133));//字體顏色 // 繪制幹擾線 for (int i = 0; i <= lineSize; i++) { drowLine(g); } // 繪制隨機字符 String randomString = ""; for (int i = 1; i <= stringNum; i++) { randomString = drowString(g, randomString, i); } logger.info(randomString); //將生成的隨機字符串保存到session中 session.removeAttribute(RANDOMCODEKEY); session.setAttribute(RANDOMCODEKEY, randomString); g.dispose(); try { // 將內存中的圖片通過流動形式輸出到客戶端 ImageIO.write(image, "JPEG", response.getOutputStream()); } catch (Exception e) { e.printStackTrace(); // logger.error("將內存中的圖片通過流動形式輸出到客戶端失敗>>>> ", e); } } /** * 繪制字符串 */ private String drowString(Graphics g, String randomString, int i) { g.setFont(getFont()); g.setColor(new Color(random.nextInt(101), random.nextInt(111), random .nextInt(121))); String rand = String.valueOf(getRandomString(random.nextInt(randString .length()))); randomString += rand; g.translate(random.nextInt(3), random.nextInt(3)); g.drawString(rand, 13 * i, 16); return randomString; } /** * 繪制幹擾線 */ private void drowLine(Graphics g) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(13); int yl = random.nextInt(15); g.drawLine(x, y, x + xl, y + yl); } /** * 獲取隨機的字符 */ public String getRandomString(int num) { return String.valueOf(randString.charAt(num)); } }
2.Controller層
要跨域!!
@RestController @RequestMapping("/Code") public class CodeController { private final static Logger logger = LoggerFactory.getLogger(CodeController.class); /** * 生成驗證碼 */ @GetMapping("getVerify") @CrossOrigin(origins = "*") // @RequestMapping(value = "/getVerify") public void getVerify(HttpServletRequest request, HttpServletResponse response) { try { response.setContentType("image/jpeg");//設置相應類型,告訴瀏覽器輸出的內容為圖片 response.setHeader("Pragma", "No-cache");//設置響應頭信息,告訴瀏覽器不要緩存此內容 response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expire", 0); CodeUtil randomValidateCode = new CodeUtil(); randomValidateCode.getRandcode(request, response);//輸出驗證碼圖片方法 } catch (Exception e) { e.printStackTrace(); // logger.error("獲取驗證碼失敗>>>> ", e); } } /** * 校驗驗證碼 */ @RequestMapping(value = "/checkVerify",headers = "Accept=application/json") @CrossOrigin(origins = "*",allowCredentials="true") public boolean checkVerify(@RequestParam String verifyInput, HttpSession session) { try{ //從session中獲取隨機數 String inputStr = verifyInput; String random = (String) session.getAttribute("RANDOMVALIDATECODEKEY"); if (random == null) { return false; } if (random.equals(inputStr)) { return true; } else { return false; } }catch (Exception e){ e.printStackTrace(); // logger.error("驗證碼校驗失敗", e); return false; } } }
3.前臺vue方式:
頁面部分
<template> <div> <el-row :gutter="0"> <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="83px" label-position="left" > <img :src="imgUrl" alt="更換驗證碼" @click="getVerify(this)" /> <el-col :span="6"> <el-form-item label="驗證碼" prop="code"> <el-input v-model="formData.code" placeholder="請輸入驗證碼" clearable :style="{ width: '100%' }" > </el-input> </el-form-item> </el-col> <el-col :span="24"> <el-form-item size="large"> <el-button type="primary" @click="aVerify()">提交</el-button> <el-button @click="resetForm">重置</el-button> </el-form-item> </el-col> </el-form> </el-row> </div> </template>
js部分:
vue方法:
data() { return { imgUrl: "/api/Code/getVerify", formData: { code: undefined, }, rules: { code: [ { required: true, message: "請輸入驗證碼", trigger: "blur", }, ], }, }; },
methods: { aVerify() { var that = this; var data = Qs.stringify({ verifyInput: this.formData.code, }); that .axios({ method: "post", url: "/api/Code/checkVerify", data: data, }) .then((response) => { console.log(response); if ( response.data) { alert("success!"); } else { alert("failed!"); } getVerify(); }); }, getVerify(obj) { console.log(obj); // obj.src = "/api/Code/getVerify?" + Math.random(); this.imgUrl = "/api/Code/getVerify?" + Math.random(); }, resetForm() { this.$refs["elForm"].resetFields(); }, },
原生js方法:
function getVerify(obj) { // obj.src = "/api/Code/getVerify" obj.src = "/api/Code/getVerify?" + Math.random(); //原生js方式 console.log(obj.src); // this.imgCode= "/api/Code/getVerify?"+Math.random(); } // function getVerify() { // // $("#imgCode").on("click", function() { // $("#imgVerify").attr("src", 'Code/getVerify?' + Math.random());//jquery方式 // // }); // } function aVerify() { var value = $("#verify_input").val(); // alert(value); $.ajax({ async: false, type: "post", url: "/api/Code/checkVerify", dataType: "json", data: { verifyInput: value, }, success: function (result) { if (result) { alert("success!"); } else { alert("failed!"); } // window.location.reload(); getVerify(); }, }); }
實際應用中:
防止頁面跳回不重新加載:
imgUrl直接綁定隨機數
imgUrl: "/api/Code/getVerify?" + Math.random(),
aVerify() { var that = this; var data = Qs.stringify({ verifyInput: this.formData.code, }); that .axios({ method: "post", url: "/api/Code/checkVerify", data: data, }) .then((response) => { console.log(response); this.result=response.data; console.log(this.result); if ( response.data) { this.submitForm(); // alert("success!"); } else { this.$message({ type: "warning", message: "驗證碼錯誤", }); this.getVerify(); } // this.reload(); }); }, getVerify() { console.log("hhhhh"); // var timestmp = (new Date()).valueOf(); // obj.src = "/api/Code/getVerify?" + Math.random(); this.imgUrl = "/api/Code/getVerify?" + Math.random(); // this.imgUrl = "/api/Code/getVerify?" + "&t=" +timestmp; },
以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。
推薦閱讀:
- javaWeb如何實現隨機圖片驗證碼詳解
- vue+spring boot實現校驗碼功能
- SpringBoot 圖形驗證碼的生成和校驗
- java生成驗證碼圖片的方法
- java random.nextInt的坑及解決