Java swing随机验证码
HttpServletResponse?回应)?摔投?ServletException,?IOException?{
?
?response . setcontenttype(" image/JPEG ");
?response.setHeader("Pragma ",“无缓存”);
?response . set header(" Cache-Control ",“无缓存”);
?response . setdate header(" Expires ",0);
?HttpSession?会话?=?request . getsession();
?
?int?宽度?=?60,?身高?=?20;
?
?BufferedImage?形象?=?新的?BufferedImage(宽度,身高,
BufferedImage。TYPE _ INT _ RGB);
?
?//?获取图形上下文
?图形?g?=?image . get graphics();
?
?//?生成随机类
?随机?随机?=?新的?random();
?
?//?设置背景颜色。
?g.setColor(getRandColor(200,?250));
?g.fillRect(0,?0,?宽度,?身高);
?
?//?设置字体
?g.setFont(新?Font("Times?新的?罗曼“,?字体。平平淡淡?18));
?
?//?155干扰线随机生成,使得图像中的认证码很难被其他程序检测到。
?g . set color(getRandColor(160,?200));
?为了什么?(int?我?=?0;?我?& lt?155;?i++)?{
int?x?=?random.nextInt(宽度);
int?y?=?random.nextInt(高度);
int?xl?=?random . nextint(12);
int?yl?=?random . nextint(12);
g.drawLine(x,y,?x?+?xl,?y?+?yl);
?}
?
?//?取随机生成的认证码(4位数)
?字符串?sRand?=?"";
?为了什么?(int?我?=?0;?我?& lt?4;?i++)?{
字符串?兰德?=?string . value of(random . nextint(10));
sRand?+=?兰德;
//?向图像显示验证码。
g.setColor(新?颜色(20?+?random.nextInt(110),?20?+?随意
?。nextInt(110),?20?+?random . nextint(110)));//?调用函数颜色都一样,可能是因为种子太近,所以只能直接生成。
g .抽绳(兰德,13?*?我?+?6,?16);
?}
?
?//?将身份验证代码存储在会话中。
?session.setAttribute("rand ",sRand);
?//?图像验证
?g . dispose();
?ServletOutputStream?responseOutputStream?=?response . get output stream();
?//?将图像输出到页面
?ImageIO.write(image,?“JPEG”,?responseOutputStream);
?
?//?关闭下面的输入流!
?responseoutputstream . flush();
?responseoutputstream . close();
?}
?
静电?颜色?getRandColor(int?fc,?int?bc)?{
?//?获取给定范围内的随机颜色。
?随机?随机?=?新的?random();
?如果?(fc?& gt?255)
fc?=?255;
?如果?(公元前?& gt?255)
公元前?=?255;
?int?r?=?fc?+?random.nextInt(bc?-?fc);
?int?g?=?fc?+?random.nextInt(bc?-?fc);
?int?b?=?fc?+?random.nextInt(bc?-?fc);
?回归?新的?颜色(r,g,?b);
?}
?
?/**?
?*?手柄?那个?HTTP?得到?方法。?
?*
?*?@param?请求?
?*servlet?请求?
?*?@param?回应?
?*servlet?回应?
?*/?
?受保护?作废?doGet(HttpServletRequest?请求,
HttpServletResponse?回应)?摔投?ServletException,?IOException?{
?processRequest(请求,回应);
?}这是我的web中使用的验证码。你可以改变它。