您好,登錄后才能下訂單哦!
這篇文章給大家介紹springboot中怎么利用vue實(shí)現(xiàn)驗(yàn)證碼功能,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。
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";//隨機(jī)產(chǎn)生只有數(shù)字的字符串 private String //private String randString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";//隨機(jī)產(chǎn)生只有字母的字符串 //private String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//隨機(jī)產(chǎn)生數(shù)字與字母組合的字符串 private int width = 95;// 圖片寬 private int height = 25;// 圖片高 private int lineSize = 40;// 干擾線數(shù)量 private int stringNum = 4;// 隨機(jī)產(chǎn)生字符數(shù)量 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); } /** * 生成隨機(jī)圖片 */ public void getRandcode(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(); // BufferedImage類是具有緩沖區(qū)的Image類,Image類是用于描述圖像信息的類 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR); Graphics g = image.getGraphics();// 產(chǎn)生Image對(duì)象的Graphics對(duì)象,改對(duì)象可以在圖像上進(jìn)行各種繪制操作 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); } // 繪制隨機(jī)字符 String randomString = ""; for (int i = 1; i <= stringNum; i++) { randomString = drowString(g, randomString, i); } logger.info(randomString); //將生成的隨機(jī)字符串保存到session中 session.removeAttribute(RANDOMCODEKEY); session.setAttribute(RANDOMCODEKEY, randomString); g.dispose(); try { // 將內(nèi)存中的圖片通過流動(dòng)形式輸出到客戶端 ImageIO.write(image, "JPEG", response.getOutputStream()); } catch (Exception e) { e.printStackTrace(); // logger.error("將內(nèi)存中的圖片通過流動(dòng)形式輸出到客戶端失敗>>>> ", 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); } /** * 獲取隨機(jī)的字符 */ public String getRandomString(int num) { return String.valueOf(randString.charAt(num)); } }
要跨域!!
@RestController @RequestMapping("/Code") public class CodeController { private final static Logger logger = LoggerFactory.getLogger(CodeController.class); /** * 生成驗(yàn)證碼 */ @GetMapping("getVerify") @CrossOrigin(origins = "*") // @RequestMapping(value = "/getVerify") public void getVerify(HttpServletRequest request, HttpServletResponse response) { try { response.setContentType("image/jpeg");//設(shè)置相應(yīng)類型,告訴瀏覽器輸出的內(nèi)容為圖片 response.setHeader("Pragma", "No-cache");//設(shè)置響應(yīng)頭信息,告訴瀏覽器不要緩存此內(nèi)容 response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expire", 0); CodeUtil randomValidateCode = new CodeUtil(); randomValidateCode.getRandcode(request, response);//輸出驗(yàn)證碼圖片方法 } catch (Exception e) { e.printStackTrace(); // logger.error("獲取驗(yàn)證碼失敗>>>> ", e); } } /** * 校驗(yàn)驗(yàn)證碼 */ @RequestMapping(value = "/checkVerify",headers = "Accept=application/json") @CrossOrigin(origins = "*",allowCredentials="true") public boolean checkVerify(@RequestParam String verifyInput, HttpSession session) { try{ //從session中獲取隨機(jī)數(shù) 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("驗(yàn)證碼校驗(yàn)失敗", e); return false; } } }
頁面部分
<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="更換驗(yàn)證碼" @click="getVerify(this)" /> <el-col :span="6"> <el-form-item label="驗(yàn)證碼" prop="code"> <el-input v-model="formData.code" placeholder="請(qǐng)輸入驗(yàn)證碼" clearable : > </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: "請(qǐng)輸入驗(yàn)證碼", 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(); }, }); }
實(shí)際應(yīng)用中:
防止頁面跳回不重新加載:
imgUrl直接綁定隨機(jī)數(shù)
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: "驗(yàn)證碼錯(cuò)誤", }); 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; },
關(guān)于springboot中怎么利用vue實(shí)現(xiàn)驗(yàn)證碼功能就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。