package com.cn.fuleehaofangjia.biz;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 验证码类
* @author AliasYa
*
*/
public class VerlifyCodeUtil {
/**
* 生成验证码并将产生的数据保存到session中
*/
public static void verlifyCode(HttpServletRequest request,HttpServletResponse response){
//准备数据
String data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
//随机函数
Random random = new Random();
int width = 80; //宽
int height = 40;//高
//1 创建图片--服务器端内存
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//2编写内容
// * 获得画板(图层)
Graphics g = image.getGraphics();
// * 画笔颜色--黑
g.setColor(Color.BLACK);
// * 画一个矩形
g.fillRect(0, 0, width, height);
// * 画笔颜色--白
g.setColor(Color.gray);
// * 画一个矩形
g.fillRect(1, 1, width-2, height-2);
// 设置字体
g.setFont(new Font("粗体",Font.BOLD,20));
/** 将随机生成文字保存到session */
/** 1.准备缓存区 */
StringBuilder builderCode = new StringBuilder();
// 编写文字
for(int i = 0 ; i < 4 ; i++){
// 画笔颜色 -- 随机
g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
// 随机文字
int index = random.nextInt(data.length());
String str = data.substring(index, index + 1);
/** 2.缓存数据 */
builderCode.append(str);
// 将文字写入到画板
g.drawString(str, (i + 1)* (width / 6), 25);
}
/** 3.将缓存的数据保存到session 属性中*/
request.getSession().setAttribute("verifyCode", builderCode.toString());
// 干扰线
for(int i = 0 ; i < 10 ; i++){
// 画笔颜色 -- 随机
g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
// 划线--随机
g.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width),random.nextInt(height));
}
//3图片发送到浏览器
// 1,图片 2 图片格式 3输出位置
try {
ImageIO.write(image, "jpeg", response.getOutputStream());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
调用如下:
package com.cn.fuleehaofangjia.web.controller;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cn.fuleehaofangjia.biz.IUserBiz;
import com.cn.fuleehaofangjia.biz.VerlifyCodeUtil;
import com.cn.fuleehaofangjia.domain.User;
/**
* 验证码类
*
* @author AliasYa
*
*/
@Controller
@RequestMapping(value = "valiCode")
public class ValiCodeController {
@Resource(name = "userBiz")
private IUserBiz userBiz;
/**
* 生成验证码
*/
@RequestMapping(value = "/createCode")
public void createCode(HttpServletRequest request,
HttpServletResponse response) {
//已经生成验证码,并返回一张图片,且session里已经保存生成的正确的验证码
VerlifyCodeUtil.verlifyCode(request, response);
}
}