亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

SpringBoot登錄驗證碼實現(xiàn)過程詳解

 更新時間:2020年04月10日 08:28:01   作者:曉宇碼匠  
這篇文章主要介紹了SpringBoot登錄驗證碼實現(xiàn)過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

今天記錄一下驗證碼的實現(xiàn),希望能夠幫助到大家!

首先我們看一下實現(xiàn)的效果:

此驗證碼的實現(xiàn)沒有用到太多的插件,話不多說直接上代碼,大家拿過去就可以用。

中間用到了org.apache.commons.lang3.RandomUtils工具類,需要pom配置:

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.10</version>
    </dependency>

1.驗證碼類

package com.youyou.login.util.validatecode;

import lombok.Data;

/**
* 驗證碼類
*/
public class VerifyCode {
  private String code;
  private byte[] imgBytes;
  private long expireTime;
  public String getCode() {
    return code;
  }
  public void setCode(String code) {
    this.code = code;
  }
  public byte[] getImgBytes() {
    return imgBytes;
  }
  public void setImgBytes(byte[] imgBytes) {
    this.imgBytes = imgBytes;
  }
  public long getExpireTime() {
    return expireTime;
  }
  public void setExpireTime(long expireTime) {
    this.expireTime = expireTime;
  }

}

2.驗證碼生成接口

package com.youyou.login.util.validatecode;

import java.io.IOException;
import java.io.OutputStream;

/**
* 驗證碼生成接口
*/
public interface IVerifyCodeGen {

/**
* 生成驗證碼并返回code,將圖片寫的os中
*
* @param width
* @param height
* @param os
* @return
* @throws IOException
*/
String generate(int width, int height, OutputStream os) throws IOException;

/**
* 生成驗證碼對象
*
* @param width
* @param height
* @return
* @throws IOException
*/
VerifyCode generate(int width, int height) throws IOException;
}

3.驗證碼生成實現(xiàn)類

package com.youyou.login.util.validatecode;
import com.youyou.util.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
/**
* 驗證碼實現(xiàn)類
*/
public class SimpleCharVerifyCodeGenImpl implements IVerifyCodeGen {
	private static final Logger logger = LoggerFactory.getLogger(SimpleCharVerifyCodeGenImpl.class);
	private static final String[] FONT_TYPES = { "u5b8bu4f53", "u65b0u5b8bu4f53", "u9ed1u4f53", "u6977u4f53", "u96b6u4e66" };
	private static final int VALICATE_CODE_LENGTH = 4;
	/**
* 設置背景顏色及大小,干擾線
*
* @param graphics
* @param width
* @param height
*/
	private static void fillBackground(Graphics graphics, int width, int height) {
		// 填充背景
		graphics.setColor(Color.WHITE);
		//設置矩形坐標x y 為0
		graphics.fillRect(0, 0, width, height);
		// 加入干擾線條
		for (int i = 0; i < 8; i++) {
			//設置隨機顏色算法參數
			graphics.setColor(RandomUtils.randomColor(40, 150));
			Random random = new Random();
			int x = random.nextint(width);
			int y = random.nextint(height);
			int x1 = random.nextint(width);
			int y1 = random.nextint(height);
			graphics.drawLine(x, y, x1, y1);
		}
	}
	/**
* 生成隨機字符
*
* @param width
* @param height
* @param os
* @return
* @throws IOException
*/
	@Override
	public String generate(int width, int height, OutputStream os) throws IOException {
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics graphics = image.getGraphics();
		fillBackground(graphics, width, height);
		String randomStr = RandomUtils.randomString(VALICATE_CODE_LENGTH);
		createCharacter(graphics, randomStr);
		graphics.dispose();
		//設置JPEG格式
		ImageIO.write(image, "JPEG", os);
		return randomStr;
	}
	/**
* 驗證碼生成
*
* @param width
* @param height
* @return
*/
	@Override
	public VerifyCode generate(int width, int height) {
		VerifyCode verifyCode = null;
		try (
		//將流的初始化放到這里就不需要手動關閉流
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		) {
			String code = generate(width, height, baos);
			verifyCode = new VerifyCode();
			verifyCode.setCode(code);
			verifyCode.setImgBytes(baos.toByteArray());
		}
		catch (IOException e) {
			logger.error(e.getMessage(), e);
			verifyCode = null;
		}
		return verifyCode;
	}
	/**
* 設置字符顏色大小
*
* @param g
* @param randomStr
*/
	private void createCharacter(Graphics g, String randomStr) {
		char[] charArray = randomStr.toCharArray();
		for (int i = 0; i < charArray.length; i++) {
			//設置RGB顏色算法參數
			g.setColor(new Color(50 + RandomUtils.nextint(100),
			+ RandomUtils.nextint(100), 50 + RandomUtils.nextint(100)));
			//設置字體大小,類型
			g.setFont(new Font(FONT_TYPES[RandomUtils.nextint(FONT_TYPES.length)], Font.BOLD, 26));
			//設置x y 坐標
			g.drawString(String.valueOf(charArray[i]), 15 * i + 5, 19 + RandomUtils.nextint(8));
		}
	}
}

4.工具類

package com.youyou.util;
import java.awt.*;
import java.util.Random;
public class RandomUtils extends org.apache.commons.lang3.RandomUtils {
	private static final char[] CODE_SEQ = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J',
	'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
	'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' };
	private static final char[] NUMBER_ARRAY = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
	private static Random random = new Random();
	public static String randomString(int length) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < length; i++) {
			sb.append(String.valueOf(CODE_SEQ[random.nextint(CODE_SEQ.length)]));
		}
		return sb.toString();
	}
	public static String randomNumberString(int length) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < length; i++) {
			sb.append(String.valueOf(NUMBER_ARRAY[random.nextint(NUMBER_ARRAY.length)]));
		}
		return sb.toString();
	}
	public static Color randomColor(int fc, int bc) {
		int f = fc;
		int b = bc;
		Random random = new Random();
		if (f > 255) {
			f = 255;
		}
		if (b > 255) {
			b = 255;
		}
		return new Color(f + random.nextint(b - f), f + random.nextint(b - f), f + random.nextint(b - f));
	}
	public static int nextint(int bound) {
		return random.nextint(bound);
	}
}

經過以上代碼,我們的驗證碼生成功能基本上已經實現(xiàn)了,現(xiàn)在還需要一個controller來調用它。

@ApiOperation(value = "驗證碼")
@GetMapping("/verifyCode")
public void verifyCode(HttpServletRequest request, HttpServletResponse response) {
	IVerifyCodeGen iVerifyCodeGen = new SimpleCharVerifyCodeGenImpl();
	try {
		//設置長寬
		VerifyCode verifyCode = iVerifyCodeGen.generate(80, 28);
		String code = verifyCode.getCode();
		LOGGER.info(code);
		//將VerifyCode綁定session
		request.getSession().setAttribute("VerifyCode", code);
		//設置響應頭
		response.setHeader("Pragma", "no-cache");
		//設置響應頭
		response.setHeader("Cache-Control", "no-cache");
		//在代理服務器端防止緩沖
		response.setDateHeader("Expires", 0);
		//設置響應內容類型
		response.setContentType("image/jpeg");
		response.getOutputStream().write(verifyCode.getImgBytes());
		response.getOutputStream().flush();
	}
	catch (IOException e) {
		LOGGER.info("", e);
	}
}

搞定!后臺編寫到此結束了。那么又會有博友說了:“說好的實現(xiàn)效果呢?”

好吧,那么我們繼續(xù)前端的代碼編寫。

前端代碼:

<html>
<body>

<div>
<input id="code" placeholder="驗證碼" type="text" class=""
style="width:170px">
<!-- 驗證碼 顯示 -->
<img οnclick="javascript:getvCode()" id="verifyimg" style="margin-left: 20px;"/>
</div>

<script type="text/javascript">
getvCode();

/**
* 獲取驗證碼
* 將驗證碼寫到login.html頁面的id = verifyimg 的地方
*/
function getvCode() {
document.getElementById("verifyimg").src = timestamp("http://127.0.0.1:81/verifyCode");
}
//為url添加時間戳
function timestamp(url) {
var getTimestamp = new Date().getTime();
if (url.indexOf("?") > -1) {
url = url + "&timestamp=" + getTimestamp
} else {
url = url + "?timestamp=" + getTimestamp
}
return url;
};
</script>
</body>

</html>

可以實現(xiàn)點擊圖片更換驗證碼。

實現(xiàn)效果:

當然文章開頭的截圖是我系統(tǒng)中的截圖,需要大家自己去根據自己的情況去開發(fā)前端了。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

  • Spring Boot JPA中使用@Entity和@Table的實現(xiàn)

    Spring Boot JPA中使用@Entity和@Table的實現(xiàn)

    這篇文章主要介紹了Spring Boot JPA中使用@Entity和@Table的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-03-03
  • 在logback.xml中自定義動態(tài)屬性的方法

    在logback.xml中自定義動態(tài)屬性的方法

    這篇文章主要介紹了在logback.xml中自定義動態(tài)屬性的方法,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-08-08
  • Java增加自定義注解進行校驗入參詳解

    Java增加自定義注解進行校驗入參詳解

    這篇文章主要為大家詳細介紹了Java如何通過增加自定義注解實現(xiàn)校驗入參功能,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起了解一下
    2023-04-04
  • Java編程中void方法的學習教程

    Java編程中void方法的學習教程

    這篇文章主要介紹了Java編程中void方法的學習教程,包括對void方法進行單元測試,需要的朋友可以參考下
    2015-10-10
  • Mybatis使用JSONObject接收數據庫查詢的方法

    Mybatis使用JSONObject接收數據庫查詢的方法

    這篇文章主要介紹了Mybatis使用JSONObject接收數據庫查詢,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-12-12
  • Java 中的io模型詳解

    Java 中的io模型詳解

    這篇文章主要介紹了Java 中io模型的相關資料,幫助大家更好的理解和學習使用Java,感興趣的朋友可以了解下
    2021-04-04
  • Springboot3.3 整合Cassandra 4.1.5的詳細過程

    Springboot3.3 整合Cassandra 4.1.5的詳細過程

    這篇文章主要介紹了Springboot3.3 整合Cassandra 4.1.5的詳細過程,本文通過實例代碼給大家介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧
    2024-06-06
  • Springboot整合mybatis的步驟

    Springboot整合mybatis的步驟

    這篇文章主要介紹了Springboot整合mybatis的步驟,幫助大家更好的理解和學習使用
    2021-04-04
  • Spring?IOC中對象的創(chuàng)建、策略及銷毀時機和生命周期詳解

    Spring?IOC中對象的創(chuàng)建、策略及銷毀時機和生命周期詳解

    這篇文章主要介紹了Spring?IOC中對象的創(chuàng)建、策略及銷毀時機和生命周期詳解,Spring默認使用類的空參構造方法創(chuàng)建bean,假如類沒有空參構造方法,將無法完成bean的創(chuàng)建,需要的朋友可以參考下
    2023-08-08
  • Java實現(xiàn)多數據源的幾種方式總結

    Java實現(xiàn)多數據源的幾種方式總結

    這篇文章主要給大家總結介紹了關于Java實現(xiàn)多數據源的幾種方式,最近項目中的工作流需要查詢多個數據源的數據,數據源可能是不同種類的,需要的朋友可以參考下
    2023-08-08

最新評論