手擼簡單驗證碼

驗證機制是所有登錄或關(guān)鍵業(yè)務都會用到的功能,驗證機制也是多種多樣,比如簡單的驗證碼,語言驗證碼,短信驗證碼,還有一些根據(jù)行為進行驗證的驗證機制。這次我們來實現(xiàn)一個簡單的驗證碼。
輸出驗證碼的類
輸出驗證碼是一個繪圖的過程,繪圖的過程大部分語言都是類似的,比如準備一個畫布、準備一個畫筆、然后在畫布上繪制圖形、輸出內(nèi)容等步驟。只是不同的語言具體調(diào)用的 API 不同而已。
直接上代碼,代碼如下:
public class ImageCode{// 圖形中的內(nèi)容private String code;// 圖片private ByteArrayInputStream image;private int width = 400;private int height = 100;public static ImageCode getInstance() throws IOException {return new ImageCode();}private ImageCode() throws IOException{// 圖形緩沖區(qū) 畫布BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);// 畫筆Graphics graphics = image.getGraphics();// 涂色graphics.setColor(new Color(255, 255, 255));// 畫矩形graphics.fillRect(0, 0, width, height);// 字體graphics.setFont(new Font("宋體", Font.PLAIN, 30));Random random = new Random();this.code = "";StringBuilder sb = new StringBuilder(6);for (int i = 0; i < 6; i++) {String s = String.valueOf(random.nextInt(10));sb.append(s);graphics.setColor(new Color(0, 0, 0));graphics.drawString(s, (width / 6) * i, 40);}this.code = sb.toString();// 收筆graphics.dispose();ByteArrayInputStream inputStream = null;ByteOutputStream outputStream = new ByteOutputStream();try {// 賦值給byteArrayInputStreamImageOutputStream imageOutputStream = ImageIO.createImageOutputStream(outputStream);ImageIO.write(image,"jpeg",imageOutputStream);inputStream = new ByteArrayInputStream(outputStream.toByteArray());imageOutputStream.close();}catch (Exception e){System.out.println("生成驗證碼失敗");} finally {System.out.println("關(guān)閉資源");outputStream.close();}this.image = inputStream;}}
輸出驗證碼
上面的類就是一個用于輸出驗證碼的類,我們要測試該類,需要創(chuàng)建一個 SpringMVC 的項目來進行測試,測試也比較簡單,直接上代碼,代碼如下。
@GetMapping("/verifyCode")public void generatorCode(HttpServletResponse response){try {ImageCode imageCode = ImageCode.getInstance();// 驗證碼的值String code = imageCode.getCode();// 驗證碼圖片ByteArrayInputStream image = imageCode.getImage();response.setContentType("image/jpeg");byte[] bytes = new byte[1024];try(ServletOutputStream out = response.getOutputStream()) {while (image.read(bytes) !=-1 ){out.write(bytes);}}}catch (Exception e){System.out.println("異常");}}
上面的代碼也是非常簡單的,直接看效果吧。

上面就是驗證碼的輸出,刷新一下可以看到數(shù)字又進行了變化。
總結(jié)
上面是一個簡單的驗證碼,該驗證碼只是完成了簡單的功能,在實際的場景中很容易被識別從而失去保護的作用。所以可以增加一些干擾線,或者對數(shù)字進行扭曲等變換。
評論
圖片
表情
