您的位置:首页 > 编程语言 > Java开发

spring mvc框架中创建验证码

2015-08-05 22:11 507 查看
 

在spring mvc框架中的公共控制器中创建验证码,并把验证码放入session,并返回图片流

/**
* 创建验证码

* @throws Exception
*/
@RequestMapping(value = "/common/createCode", method = RequestMethod.GET)
public void createCode(HttpServletRequest request,
HttpServletResponse response) throws Exception {
/** 定义验证码宽度 */
int width = 120;
/** 定义验证码高度 */
int height = 36;
int codeX = 20;
int codeY = 25;
int fontHeight = 20;
char[] codeSequence = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9' };
BufferedImage bufferedImage = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics graphics = bufferedImage.getGraphics();
Random random = new Random();
/** 设置填充背景为白色 */
graphics.setColor(new Color(250, 250, 250));
graphics.fillRect(0, 0, width, height);
Font font = new Font("Fixedsys", Font.BOLD, fontHeight);
/** 设置字体样式 */
graphics.setFont(font);
graphics.setColor(Color.BLACK);
// 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
graphics.setColor(getRandColor(160, 200));
for (int i = 0; i < 100; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
graphics.drawLine(x, y, x + xl, y + yl);
}
/** 描边 */
graphics.drawRect(0, 0, width - 1, height - 1);
graphics.setColor(Color.BLACK);
/** 设置随机验证码 */
StringBuffer randomCode = new StringBuffer();
int red = 0, green = 0, blue = 0;
for (int i = 0; i < 4; i++) {
String code = String.valueOf(codeSequence[random.nextInt(10)]);
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
graphics.setColor(new Color(red, green, blue));
/** 用随机产生的颜色将验证码绘制到图像中 */
graphics.drawString(code, (i + 1) * codeX, codeY);
randomCode.append(code);
}
/** 将四位数字的验证码保存到Session中 */
HttpSession session = request.getSession();
session.setAttribute("loginCode", randomCode.toString());
response.setHeader("Pragma", "no-cache");
/** 禁止图像缓存 */
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
OutputStream sos = response.getOutputStream();
/** 将图像输出到Servlet输出流中 */
ImageIO.write(bufferedImage, "jpeg", sos);
sos.close();
}

//给定范围获得随机颜色
Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: