springboot登陸頁面圖片驗證碼簡單的web項目實現(xiàn)
寫在前面
前段時間大家都說最近大環(huán)境不好,好多公司在裁員,換工作的話不推薦輕易的裸辭,但是我想說的是我所在的公司好流弊,有做不完的業(yè)務(wù)需求,還有就是招不完的人......
最近我也是比較繁忙,但是還是要抽一點時間來進(jìn)行自我復(fù)盤和記錄,最近也寫一個簡單的小功能,就是登陸界面的圖片驗證碼功能
環(huán)境:Tomcat9、Jdk1.8
1 生成驗證碼的工具類
public class RandomValidateCodeUtil {
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(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);
}
/**
* 生成隨機(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對象的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);
}
logger.info(randomString);
//將生成的隨機(jī)字符串保存到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);
}
/**
* 獲取隨機(jī)的字符
*/
public String getRandomString(int num) {
return String.valueOf(randString.charAt(num));
}
}
這個類不用動,可以直接拿來用
2 頁面代碼
<!--html/bady代碼-->
<div >
<div >
<div >
<input type="tel" id="verify_input" placeholder="請輸入驗證碼" maxlength="4">
</div>
</div>
<div >
<a href="javascript:void(0);" rel="external nofollow" title="點擊更換驗證碼">
<img id="imgVerify" src="login/getVerify" alt="更換驗證碼" height="36" width="170" onclick="getVerify(this);">
</a>
</div>
<input type="button" onclick="aVerify()" value="提交">
</div>
</body>
<!--js中的代碼-->
<script type="text/javascript" src="./js/jquery.min.js"></script>
<script>
//獲取驗證碼
/*function getVerify(obj){
obj.src = "login/getVerify?"+Math.random();//原生js方式
}*/
//獲取驗證碼
function getVerify() {
// $("#imgCode").on("click", function() {
$("#imgVerify").attr("src", 'login/getVerify?' + Math.random());//jquery方式
// });
}
function aVerify(){
var value =$("#verify_input").val();
// alert(value);
$.ajax({
async: false,
type: 'post',
url: 'login/checkVerify',
dataType: "json",
data: {
verifyInput: value
},
success: function (result) {
if (result) {
alert("success!");
} else {
alert("failed!");
}
// window.location.reload();
getVerify();
}
});
}
</script>
注意:這里有2種獲取驗證碼圖片的方法
3 獲取code和驗證code的類
@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");//設(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);
}
}
/**
* 校驗驗證碼
*/
@RequestMapping(value = "/checkVerify", method = RequestMethod.POST,headers = "Accept=application/json")
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){
logger.error("驗證碼校驗失敗", e);
return false;
}
}
}
4 效果圖鎮(zhèn)樓

5 源碼
當(dāng)然上面代碼只是核心部分,如果有問題可去github自行下載 charmsongo
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Spring?Boot?Shiro?auto-configure工作流程詳解
這篇文章主要為大家介紹了Spring?Boot?Shiro?auto-configure工作流程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02
SpringCloud Hystrix-Dashboard儀表盤的實現(xiàn)
這篇文章主要介紹了SpringCloud Hystrix-Dashboard儀表盤的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
Java SpringMVC 異常處理SimpleMappingExceptionResolver類詳解
這篇文章主要介紹了SpringMVC 異常處理SimpleMappingExceptionResolver類詳解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-09-09
詳解SpringBoot中@SessionAttributes的使用
這篇文章主要通過示例為大家詳細(xì)介紹了SpringBoot中@SessionAttributes的使用,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2022-07-07
模仿mybatis-plus實現(xiàn)rpc調(diào)用
這篇文章主要為大家介紹了模仿mybatis-plus實現(xiàn)rpc調(diào)用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02

