欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java實現(xiàn)登錄驗證碼

 更新時間:2018年06月22日 16:01:36   作者:紫薇帝星的故事  
這篇文章主要為大家詳細(xì)介紹了java實現(xiàn)登錄驗證碼,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了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.設(shè)置畫筆顏色(Random類中的nextInt(n)返回一個大于等于0,小于n的隨機(jī)數(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.設(shè)置顏色字體后,繪制字符串(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">

效果圖

更多關(guān)于驗證碼的文章請點擊查看: 《java驗證碼》

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論