java實現(xiàn)登錄驗證碼
更新時間:2018年06月22日 16:01:36 作者:紫薇帝星的故事
這篇文章主要為大家詳細介紹了java實現(xiàn)登錄驗證碼,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了java實現(xiàn)登錄驗證碼的具體代碼,供大家參考,具體內(nèi)容如下
1、ValidateCode.java
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import org.springframework.stereotype.Service;
/**
* 登錄驗證碼
*
*/
public class ValidateCode {
/**
* 得到驗證碼圖片
* @param out
* @param number 驗證數(shù)字
* @throws ServletException
* @throws IOException
*/
public void getImage(OutputStream out,String number)
throws ServletException, IOException {
//0.創(chuàng)建空白圖片
BufferedImage image=new BufferedImage(100,30,BufferedImage.TYPE_INT_RGB);
//1.獲取圖片畫筆
Graphics g = image.getGraphics();
Random r=new Random();
//2.設置畫筆顏色(Random類中的nextInt(n)返回一個大于等于0,小于n的隨機數(shù))
g.setColor(new Color(r.nextInt(255),r.nextInt(255), r.nextInt(255)));
//3.繪制矩形的背景
g.fillRect(0, 0, 100, 30);
//4.調(diào)用自定義的方法,獲取長度為4的字母數(shù)字組合的字符串
g.setColor(new Color(0,0,0));
g.setFont(new Font(null,Font.BOLD,24));
//5.設置顏色字體后,繪制字符串(x/y,最左邊字符所處的位置)
g.drawString(number, 20, 24);
//6.繪制8條干擾線(alpha表示透明度)
for(int i=0;i<8;i++){
g.setColor(new Color(r.nextInt(255),r.nextInt(255), r.nextInt(255),r.nextInt(255)));
g.drawLine(r.nextInt(100), r.nextInt(30), r.nextInt(100), r.nextInt(30));
}
ImageIO.write(image, "jpeg", out);
}
//自定義方法,獲取長度為size的字母數(shù)字組合的字符串
public String getNumber(int size){
String str="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
String number="";
Random r = new Random();
for(int i=0;i<size;i++){
number+=str.charAt(r.nextInt(str.length()));
}
return number;
}
}
2、Controller
@RequestMapping(value = "/check",method={RequestMethod.GET})
@ResponseBody
public void check(HttpServletRequest req) {
try {
HttpServletResponse response = this.getResponse();
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment;filename=" + "vcode.jpeg");
String number = validateCode.getNumber(4);
validateCode.getImage(response.getOutputStream(),number);
} catch (Exception e) {
}
}
3、html
<img style="width:4.4rem;height:1.9rem; margin-left:0.8rem;" src="http://127.0.0.1:8080/test/check">
效果圖

更多關于驗證碼的文章請點擊查看: 《java驗證碼》
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Java實現(xiàn)JSP在Servelt中連接Oracle數(shù)據(jù)庫的方法
這篇文章主要介紹了Java實現(xiàn)JSP在Servelt中連接Oracle數(shù)據(jù)庫的方法,需要的朋友可以參考下2014-07-07
win10系統(tǒng)64位jdk1.8的下載與安裝教程圖解
這篇文章主要介紹了win10系統(tǒng)64位jdk1.8的下載與安裝教程圖解,本文給大家介紹的非常詳細,對大家的工作或?qū)W習具有一定的參考借鑒價值,需要的朋友可以參考下2020-03-03
springboot 項目使用jasypt加密數(shù)據(jù)源的方法
Jasypt 是一個 Java 庫,它允許開發(fā)者以最小的努力為他/她的項目添加基本的加密功能,而且不需要對密碼學的工作原理有深刻的了解。接下來通過本文給大家介紹springboot 項目使用jasypt加密數(shù)據(jù)源的問題,一起看看吧2021-11-11

