Spring框架生成圖片驗證碼實例
這篇文章會從前臺頁面到后臺實現(xiàn)完整的講解,下面跟著小編一起來看看。
1、前臺的代碼,image.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>獲取圖片驗證碼</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/static/js/jquery-1.10.2.min.js"></script>
</head>
<body>
<form action="##" method='post'>
<input type="hidden" id="userId" name="userId" value="">
<div class="form-group">
<div class="email controls">
<input type="text" name='loginName' id="loginName" placeholder="用戶名" value="" class='form-control'/>
</div>
</div>
<div class="form-group">
<div class="pw controls">
<input type="password" autocomplete="off" id="pwd" name="pwd" placeholder="密碼" class='form-control'/>
</div>
</div>
<div class="form-group">
<div class="email controls">
<input id="validateCode" onblur="checkImg(this.value)" name="validateCode" type="text" class="form-control" placeholder="輸入驗證碼"/>
</div>
<span class="y_yzimg"><img id="codeValidateImg" onClick="javascript:flushValidateCode();"/></span>
<p class="y_change"><a href="javascript:flushValidateCode();" >換一張</a></p>
</div>
<div class="form-group">
<span class="text-danger"></span>
</div>
<div class="submit">
<div class="remember">
<input type="checkbox" name="remember" value="1" class='icheck-me' data-skin="square" data-color="blue" id="remember">
<label for="remember">記住我</label>
</div>
<input type="button" value="登錄" onclick="javascript:submitForm();" class='btn btn-primary'>
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
flushValidateCode();//進(jìn)入頁面就刷新生成驗證碼
});
/* 刷新生成驗證碼 */
function flushValidateCode(){
var validateImgObject = document.getElementById("codeValidateImg");
validateImgObject.src = "${pageContext.request.contextPath }/getSysManageLoginCode?time=" + new Date();
}
/*校驗驗證碼輸入是否正確*/
function checkImg(code){
var url = "${pageContext.request.contextPath}/checkimagecode";
$.get(url,{"validateCode":code},function(data){
if(data=="ok"){
alert("ok!")
}else{
alert("error!")
flushValidateCode();
}
})
}
</script>
</body>
</html>
2、后臺代碼ImageGenController.java
package com.dufyun.springmvc.web.controller;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.dufy.javaweb.test.RandomValidateCode;
@Controller
public class ImageGenController {
@RequestMapping(value="/toImg")
public String toImg(){
return "image/image";
}
//登錄獲取驗證碼
@RequestMapping("/getSysManageLoginCode")
@ResponseBody
public String getSysManageLoginCode(HttpServletResponse response,
HttpServletRequest request) {
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.setHeader("Set-Cookie", "name=value; HttpOnly");//設(shè)置HttpOnly屬性,防止Xss攻擊
response.setDateHeader("Expire", 0);
RandomValidateCode randomValidateCode = new RandomValidateCode();
try {
randomValidateCode.getRandcode(request, response,"imagecode");// 輸出圖片方法
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
//驗證碼驗證
@RequestMapping(value = "/checkimagecode")
@ResponseBody
public String checkTcode(HttpServletRequest request,HttpServletResponse response) {
String validateCode = request.getParameter("validateCode");
String code = null;
//1:獲取cookie里面的驗證碼信息
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
if ("imagecode".equals(cookie.getName())) {
code = cookie.getValue();
break;
}
}
//1:獲取session驗證碼的信息
//String code1 = (String) request.getSession().getAttribute("");
//2:判斷驗證碼是否正確
if(!StringUtils.isEmpty(validateCode) && validateCode.equals(code)){
return "ok";
}
return "error";
//這里我沒有進(jìn)行字母大小模糊的驗證處理,感興趣的你可以去試一下!
}
}
3、生成驗證碼的工具類RandomValidateCode.java
package com.dufy.javaweb.test;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RandomValidateCode {
private Random random = new Random();
private String randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";// 隨機(jī)產(chǎn)生的字符串
private int width = 80;// 圖片寬
private int height = 26;// 圖片高
private int lineSize = 40;// 干擾線數(shù)量
private int stringNum = 4;// 隨機(jī)產(chǎn)生字符數(shù)量
/*
* 獲得字體
*/
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);
}
/*
* 繪制字符串
*/
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));
}
/**
* 生成隨機(jī)圖片
*/
public void getRandcode(HttpServletRequest request,HttpServletResponse response,String key) {
// BufferedImage類是具有緩沖區(qū)的Image類,Image類是用于描述圖像信息的類
BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_BGR);
Graphics g = image.getGraphics();// 產(chǎn)生Image對象的Graphics對象,改對象可以在圖像上進(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);
}
//1:將隨機(jī)生成的驗證碼放入Cookie中
Cookie cookie = new Cookie(key,randomString);
response.addCookie(cookie);
//2:將隨機(jī)生成的驗證碼放入session中
String sessionid = request.getSession().getId();
request.getSession().setAttribute(sessionid+key, randomString);
System.out.println("*************" + randomString);
//總結(jié):這兩種方式都是很好,
//(1):使用cookie的方式,將驗證碼發(fā)送到前臺瀏覽器,不安全!不建議使用。
//(2):使用session的方式,雖然能解決驗證碼不發(fā)送到瀏覽器,安全性較高了,但是如果用戶量太大,這樣的存儲方式會對服務(wù)器造成壓力,影響服務(wù)器的性能。不建議使用。
//這里暫時實現(xiàn)用這種方式,好的辦法是,在項目中使用的緩存,將生成的驗證碼存放到緩存中,設(shè)置失效時間,這樣既可以實現(xiàn)安全性也能減輕服務(wù)器的壓力。
g.dispose();
try {
ByteArrayOutputStream tmp = new ByteArrayOutputStream();
ImageIO.write(image, "png", tmp);
tmp.close();
Integer contentLength = tmp.size();
response.setHeader("content-length", contentLength + "");
response.getOutputStream().write(tmp.toByteArray());// 將內(nèi)存中的圖片通過流動形式輸出到客戶端
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
response.getOutputStream().flush();
response.getOutputStream().close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
4、總結(jié)
本文的內(nèi)容到這就結(jié)束了,如果對里面的地方有不懂的地方,可以留言討論。希望本文的內(nèi)容對大家的學(xué)習(xí)工作能有所幫助。
- SpringBoot實現(xiàn)前端驗證碼圖片生成和校驗
- Spring Security OAuth2集成短信驗證碼登錄以及第三方登錄
- Spring Boot 驗證碼的生成和驗證詳解
- Springboot實現(xiàn)阿里云通信短信服務(wù)有關(guān)短信驗證碼的發(fā)送功能
- SpringBoot實現(xiàn)短信驗證碼校驗方法思路詳解
- 實例詳解Spring Boot實戰(zhàn)之Redis緩存登錄驗證碼
- SpringBoot 集成Kaptcha實現(xiàn)驗證碼功能實例詳解
- Spring MVC 中 短信驗證碼功能的實現(xiàn)方法
- Spring Security Oauth2.0 實現(xiàn)短信驗證碼登錄示例
- springboot實現(xiàn)郵箱驗證碼功能
相關(guān)文章
Spring Boot支持Crontab任務(wù)改造的方法
這篇文章主要介紹了Spring Boot支持Crontab任務(wù)改造的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01
Spring?session?redis?修改默認(rèn)的序列化方法(案例)
這篇文章主要介紹了Spring?session?redis?修改默認(rèn)的序列化方法,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-04-04
SpringBoot4.5.2 整合HikariCP 數(shù)據(jù)庫連接池操作
這篇文章主要介紹了SpringBoot4.5.2 整合HikariCP 數(shù)據(jù)庫連接池操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09

