protected?void?doGet(HttpServletRequest?request,
HttpServletResponse?response)?throws?ServletException,?IOException?{
Random?random?=?new?Random();
int?colorRandoMin?=?200;
int?colorRandoMax?=?255;
//?int?randomNum?=?random.nextInt(randoMax)?%?(randoMax?-?randoMin?+?1)
//?+?randoMin;
//?生成驗(yàn)證碼
BufferedImage?bufferedImage?=?new?BufferedImage(68,?23,
BufferedImage.TYPE_INT_RGB);
//?繪圖上上下文對象
Graphics?graphics?=?bufferedImage.createGraphics();
//?畫個背景
//?三元色數(shù)值隨機(jī)產(chǎn)生
//?設(shè)置顏色
graphics.setColor(new?Color(random.nextInt(colorRandoMax
-?colorRandoMin?+?1)
+?colorRandoMin,?random.nextInt(colorRandoMax?-?colorRandoMin
+?1)
+?colorRandoMin,?random.nextInt(colorRandoMax?-?colorRandoMin
+?1)
+?colorRandoMin));
//?填充矩形
graphics.fillRect(0,?0,?68,?23);
//?繪制文字
char[]?valChar?=?"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
.toCharArray();
//?索引
int?index?=?0;
int?len?=?valChar.length;
//?用來拼接字符存儲進(jìn)session
StringBuilder?sb?=?new?StringBuilder();
//?重設(shè)文字顏色范圍
colorRandoMin?=?1;
colorRandoMax?=?130;
//?生成4個字符
for?(int?i?=?0;?i?<?4;?i++)?{
//?生成索引
index?=?random.nextInt(len);
graphics.setFont(new?Font("Arial",?Font.BOLD,?16));
//?設(shè)置文字顏色
graphics.setColor(new?Color(random.nextInt(colorRandoMax
-?colorRandoMin?+?1)
+?colorRandoMin,?random.nextInt(colorRandoMax
-?colorRandoMin?+?1)
+?colorRandoMin,?random.nextInt(colorRandoMax
-?colorRandoMin?+?1)
+?colorRandoMin));
//?繪制文字
graphics.drawString(valChar[index]?+?"",?i?*?15?+?5,?18);
sb.append(valChar[index]);
}
//?存儲在session中
request.getSession().setAttribute("validateCode",?sb.toString());
sb?=?null;
//?輸入驗(yàn)證碼圖
OutputStream?out?=?response.getOutputStream();
ImageIO.write(bufferedImage,?"jpg",?out);
//?刷新并關(guān)閉輸出流
out.flush();
out.close();
}