SpringBoot實現(xiàn)前端驗證碼圖片生成和校驗
SpringBoot下實現(xiàn)前端驗證碼圖片的生成和校驗,供大家參考,具體內(nèi)容如下
1.效果

點擊驗證碼可以獲取新的驗證碼
2.原理
后臺生成驗證碼圖片,將圖片傳到前臺。
后臺在session中保存驗證碼內(nèi)容。
前臺輸入驗證碼后傳到后臺在后臺取出session中保存的驗證碼進行校驗。
注意,驗證碼的明文是不能傳送到前端的。前端內(nèi)容都是透明的,不安全。驗證碼是用來防機器人并不是單單防人。如果把驗證碼明文傳到前端很容易就會被破解。
3.圖片生成
驗證碼生成工具類RandomValidateCodeUtil
public class RandomValidateCodeUtil {
public static final String RANDOMCODEKEY= "RANDOMVALIDATECODEKEY";//放到session中的key
private String randString = "0123456789";//隨機產(chǎn)生只有數(shù)字的字符串 private String
//private String randString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";//隨機產(chǎn)生只有字母的字符串
//private String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//隨機產(chǎn)生數(shù)字與字母組合的字符串
private int width = 95;// 圖片寬
private int height = 25;// 圖片高
private int lineSize = 40;// 干擾線數(shù)量
private int stringNum = 4;// 隨機產(chǎn)生字符數(shù)量
private static final Logger logger = LoggerFactory.getLogger(RandomValidateCodeUtil.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類是具有緩沖區(qū)的Image類,Image類是用于描述圖像信息的類
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
Graphics g = image.getGraphics();// 產(chǎn)生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 {
// 將內(nèi)存中的圖片通過流動形式輸出到客戶端
ImageIO.write(image, "JPEG", response.getOutputStream());
} catch (Exception e) {
logger.error("將內(nèi)存中的圖片通過流動形式輸出到客戶端失敗>>>> ", 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));
}
}
在Controller調(diào)用生成驗證碼圖片方法并將圖片傳到前端
/**
* 生成驗證碼
*/
@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);
RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
randomValidateCode.getRandcode(request, response);//輸出驗證碼圖片方法
} catch (Exception e) {
logger.error("獲取驗證碼失敗>>>> ", e);
}
}
前端獲取驗證碼圖片
html
<div class="row"> <div class="col-xs-6 pull_left"> <div class="form-group"> <input class="form-control" type="tel" id="verify_input" placeholder="請輸入驗證碼" maxlength="4"> </div> </div> <div class="col-xs-6 pull_left"> <a href="javascript:void(0);" rel="external nofollow" title="點擊更換驗證碼"> <img id="imgVerify" src="" alt="更換驗證碼" height="36" width="100%" onclick="getVerify(this);"> </a> </div> </div>
js
//獲取驗證碼
function getVerify(obj){
obj.src = httpurl + "/sys/getVerify?"+Math.random();
}
每次點擊圖片重新刷新驗證碼
界面初次加載時,調(diào)用getVerify()方法即可。
4.驗證碼驗證
前端獲取用戶輸入的驗證碼,傳到后臺進行驗證。
后臺驗證代碼
/**
* 忘記密碼頁面校驗驗證碼
*/
@RequestMapping(value = "/checkVerify", method = RequestMethod.POST, headers = "Accept=application/json")
public boolean checkVerify(@RequestBody Map<String, Object> requestMap, HttpSession session) {
try{
//從session中獲取隨機數(shù)
String inputStr = requestMap.get("inputStr").toString();
String random = (String) session.getAttribute("RANDOMVALIDATECODEKEY");
if (random == null) {
return false;
}
if (random.equals(inputStr)) {
return true;
} else {
return false;
}
}catch (Exception e){
logger.error("驗證碼校驗失敗", e);
return false;
}
}
后臺校驗后,返給前端驗證結(jié)果true或者false即可。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
利用java監(jiān)聽器實現(xiàn)在線人數(shù)統(tǒng)計
過去使用ASP和ASP.NET兩種編程的時候,都寫過在線人數(shù)統(tǒng)計能,實現(xiàn)功能挺簡單的!今天使用java來實現(xiàn)在線人數(shù)統(tǒng)計有點另類,是通過Java監(jiān)聽器實現(xiàn)的,需要的朋友可以參考下2015-09-09
springsecurity中http.permitall與web.ignoring的區(qū)別說明
這篇文章主要介紹了springsecurity中http.permitall與web.ignoring的區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08
mybatis-plus中l(wèi)ambdaQuery()與lambdaUpdate()比較常見的使用方法總結(jié)
mybatis-plus是在mybatis的基礎(chǔ)上做增強不做改變,簡化了CRUD操作,下面這篇文章主要給大家介紹了關(guān)于mybatis-plus中l(wèi)ambdaQuery()與lambdaUpdate()比較常見的使用方法,需要的朋友可以參考下2022-09-09
解析ConcurrentHashMap: 預(yù)熱(內(nèi)部一些小方法分析)
ConcurrentHashMap是由Segment數(shù)組結(jié)構(gòu)和HashEntry數(shù)組結(jié)構(gòu)組成。Segment的結(jié)構(gòu)和HashMap類似,是一種數(shù)組和鏈表結(jié)構(gòu),今天給大家普及java面試常見問題---ConcurrentHashMap知識,一起看看吧2021-06-06

