SpringBoot 實現“圖片驗證碼”登錄驗證 功能 【簡單實例】


效果圖 :

在這里插入圖片描述

目錄結構

 

 

 

一、工具類package com.zbw.utils;

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.Random;

public class RandomValidateCodeUtil {


public static final String RANDOMCODEKEY = "RANDOMVALIDATECODEKEY";//放到session中的key
private static final Logger logger = LoggerFactory.getLogger(RandomValidateCodeUtil.class);

// 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 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 getRandomCode(HttpServletRequest request, HttpServletResponse response) {

HttpSession session = request.getSession();

// BufferedImage類是具有緩沖區的Image類,Image類是用於描述圖像信息的類
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);

// 產生Image對象的Graphics對象,改對象可以在圖像上進行各種繪制操作
Graphics g = image.getGraphics();

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++) {
drawLine(g);
}

// 繪制隨機字符
String randomString = "";

for (int i = 1; i <= stringNum; i++) {
randomString = drawString(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) {
logger.error("將內存中的圖片通過流動形式輸出到客戶端失敗>>>> ", e);
}

}

/**
* 繪制字符串
*/
private String drawString(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 drawLine(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));
}
}

二、controller


package com.zbw.action;

import com.songo.utils.RandomValidateCodeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/login")
public class PicVerifyAction {
private final static Logger logger = LoggerFactory.getLogger(PicVerifyAction.class);

/**
* 生成驗證碼
*/
@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);

RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();

randomValidateCode.getRandomCode(request, response);//輸出驗證碼圖片方法

} catch (Exception e) {

logger.error("獲取驗證碼失敗>>>> ", e);

}

}

/**
* 校驗驗證碼
*/
@RequestMapping(value = "/checkVerify", method = RequestMethod.POST, headers = "Accept=application/json")
public boolean checkVerify(@RequestParam String verifyInput, HttpSession session) {
try {

//從session中獲取隨機數
String inputStr = verifyInput;

String random = (String) session.getAttribute("RANDOMVALIDATECODEKEY");

if (random == null || "".equals(random) || !random.equalsIgnoreCase(inputStr)) {
return false;
} else {
return true;
}

} catch (Exception e) {
logger.error("驗證碼校驗失敗", e);
return false;
}
}

}

 


三、前端 index.html
說明 : 使用了 jquery.js

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登陸</title>
</head>

<style>
#main_form {
width: 300px;
height: 200px;
margin: 100px auto;

background-color: #F0F0F0;
border: 1px solid #c2c2c2;
}

#input_content {
margin-top: 20px;
text-align: center;
border: 5px;
}

#verify_image, #submit_btn {
text-align: center;
margin: 20px auto;
}
</style>

<body>


<div id="main_form">
<div id="input_content">
<input autocomplete="off" autofocus id="verify_input" placeholder="請輸入驗證碼" maxlength="4">
</div>
<div id="verify_image">
<img id="imgVerify" src="login/getVerify" alt="更換驗證碼" height="36" width="170" onclick="getVerify(this);">
</div>

<div id="submit_btn">
<input type="button" onclick="aVerify()" value="判斷是否正確">
</div>
</div>


</body>
<script type="text/javascript" src="./js/jquery.min.js"></script>

<script>


function getVerify() {
$("#verify_input").val("");
$("#imgVerify").attr("src", 'login/getVerify?' + Math.random());//jquery方式
}

function aVerify() {
let value = $("#verify_input").val();

if (value.length < 4) {
alert("驗證碼不足4位 , 請重新輸入!!");
return 0;
}


$.ajax({
async: false,
type: 'post',
url: 'login/checkVerify',
dataType: "json",
data: {
verifyInput: value
},
success: function (result) {

if (result) {

if (confirm("驗證成功, 再試一次 !")) {
getVerify();
} else {
window.location.href = "https:www.baidu.com";
}

} else {
alert("驗證失敗 , 點擊確定重新驗證");
getVerify();
}
// window.location.reload();
}
});
}

</script></html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM