主頁
& ltimg src="RandomCodeCtrl"/>。
web.xml
& ltservlet & gt
& ltservlet-name & gt;RandomCodeCtrl & lt/servlet-name & gt;
& ltservlet-class & gt;com . chain way . util . randomcodectrl & lt;/servlet-class & gt;
& lt啟動時加載& gt4 & lt/load-on-startup & gt;
& lt/servlet & gt;
& ltservlet映射& gt
& ltservlet-name & gt;RandomCodeCtrl & lt/servlet-name & gt;
& lturl模式& gt/RandomCodeCtrl & lt;/URL-pattern & gt;
& lt/servlet-mapping & gt;
RandomCodeCtrl:
包com . chain way . util;
導入Java . io . io exception;
導入javax . servlet . servlet exception;
導入javax.servlet..chainway.util
導入Java . awt . color;
導入Java . awt . font;
導入Java . awt . graphics;
導入Java . awt . image . buffered image;
導入Java . util . random;
導入javax . imageio . imageio;
導入javax . servlet . http . http servlet request;
導入javax . servlet . http . http servlet response;
導入javax . servlet . http . http session;
公共類RandomCode {
/**
*隨機獲取壹種字體
* @param Random隨機數
* @return Font返回新字體。
*/
私有同步字體getsFont(Random random){
返回新字體(" Fixedsys ",字體。CENTER_BASELINE,18);
}
/**
*返回隨機顏色。
* @param int fc隨機數
* @param int bc隨機數
* @param Random隨機數
* @return Color返回新顏色。
*/
同步顏色getRandColor(int fc,int bc,Random random){
if(fc & gt;255)fc = 255;
if(BC & gt;255)BC = 255;
int r = fc+random . nextint(BC-fc-6);
int g = fc+random . nextint(BC-fc-4);
int b = fc+random . nextint(BC-fc-8);
返回新顏色(r,g,b);
}
/**
*生成隨機數圖片
*/
公共同步void getRandcode(http servlet request請求,HttpServletResponse響應)引發異常{
system . set property(" Java . awt . headless "," true ");
http session session = request . getsession();
int width=80,height = 26//設置圖片大小
BufferedImage image = new BufferedImage(寬度,高度,BufferedImage。TYPE _ INT _ RGB);
graphics g = image . get graphics();
Random Random = new Random();
g.fillRect(0,0,width,height);//設置邊框
g.setFont(新字體(“Times New Roman”,字體。ROMAN_BASELINE,18);
g . set color(getRandColor(111,133,隨機));
//生成隨機線
for(int I = 0;我& lt11;i++){
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);
}
//生成隨機點
g . set color(getRandColor(130,150,random));
//生成5個隨機數
String sRand =
for(int I = 0;我& lt5;i++){
g . set font(gets font(random));
g . set Color(new Color(random . nextint(101),random . nextint(111),random . nextint(121)));
//String rand = String . value of(getRandomString(random . nextint(36));
string rand = string . value of(getRandomString(random . nextint(10));
sRand+= rand;
g.translate(random.nextInt(3),random.nextInt(3))。
g .抽繩(蘭德,13*i,16);
}
session . remove attribute(" Rand ");
session.setAttribute("Rand ",sRand);
g . dispose();
ImageIO.write(image," JPEG ",response . get output stream());
}
公共同步字符串getRandomString(int num){
string rand string = " 0123456789 ";
//String rand String = " 0123456789 abcdefghijklmnopqrstuvwxyz ";
返回string . value of(rand string . charat(num));
}
}
//落地判斷方法
從進程中獲取驗證碼並進行比較。