验证码登陆java代码 java登录界面验证码( 二 )


Random random = new Random();
if(fc ) fc= ;
if(bc ) bc= ;
int r=fc+random nextInt(bc fc);
int g=fc+random nextInt(bc fc);
int b=fc+random nextInt(bc fc);
return new Color(r g b);
}
%
%
//设置页面不缓存
response setHeader( Pragma No cache );
response setHeader( Cache Control no cache );
response setDateHeader( Expires );
// 在内存中创建图象
int width= height= ;
BufferedImage image = new BufferedImage(width height BufferedImage TYPE_INT_RGB);
// 获取图形上下文
Graphics g = image getGraphics();
//生成随机类
Random random = new Random();
// 设定背景色
g setColor(getRandColor( ));
g fillRect( width height);
//设定字体
g setFont(new Font( Times New Roman Font PLAIN ));
// 随机产生 条干扰线 使图象中的认证码不易被其它程序探测到
g setColor(getRandColor( ));
for (int i= ;i ;i++)
{
int x = random nextInt(width);
int y = random nextInt(height);
int xl = random nextInt( );
int yl = random nextInt( );
g drawLine(x y x+xl y+yl);
}
// 取随机产生的认证码( 位数字)
String codeList = ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ;
String sRand= ;
for (int i= ;i ;i++){
int a=random nextInt(codeList length() );
String rand=codeList substring(a a+ );
sRand+=rand;
// 将认证码显示到图象中
g setColor(new Color( +random nextInt( ) +random nextInt( ) +random nextInt( )));//调用函数出来的颜色相同 可能是因为种子太接近 所以只能直接生成
g drawString(rand *i+ );
}
// 将认证码存入SESSION
session setAttribute( rand sRand);
// 图象生效
g dispose();
// 输出图象到页面
ImageIO write(image JPEG response getOutputStream());
out clear();
out = pageContext pushBody();
lishixinzhi/Article/program/Java/hx/201311/25536
Java如何实现验证码验证功能Java如何实现验证码验证功能呢?日常生活中 , 验证码随处可见,他可以在一定程度上保护账号安全,那么他是怎么实现的呢?
Java实现验证码验证功能其实非常简单:用到了一个Graphics类在画板上绘制字母 , 随机选取一定数量的字母随机生成,然后在画板上随机生成几条干扰线 。
首先,写一个验证码生成帮助类,用来绘制随机字母:
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;
public final class GraphicHelper {
/**
* 以字符串形式返回生成的验证码 , 同时输出一个图片
*
* @param width
*图片的宽度
* @param height
*图片的高度
* @param imgType
*图片的类型
* @param output
*图片的输出流(图片将输出到这个流中)
* @return 返回所生成的验证码(字符串)
*/
public static String create(final int width, final int height, final String imgType, OutputStream output) {
StringBuffer sb = new StringBuffer();
Random random = new Random();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics graphic = image.getGraphics();
graphic.setColor(Color.getColor("F8F8F8"));
graphic.fillRect(0, 0, width, height);
Color[] colors = new Color[] { Color.BLUE, Color.GRAY, Color.GREEN, Color.RED, Color.BLACK, Color.ORANGE,
Color.CYAN };
// 在 "画板"上生成干扰线条 ( 50 是线条个数)
for (int i = 0; i50; i++) {
graphic.setColor(colors[random.nextInt(colors.length)]);

推荐阅读