public class VerifyController {
/**
* 获取验证码
*
* @throws IOException
*/
@RequestMapping(value = "/verify")
public void verifyCode(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// 生成验证码
int width = 73;
int height = 27;
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 获取画布对象
Graphics gh = bi.getGraphics();
// 获取画区,一个矩形区域
gh.fillRect(0, 0, width, height);
// 为矩形填充成白色
gh.setColor(new Color(0, 0, 0));
//设置字体
gh.setFont(new Font("Arial", Font.PLAIN, 24));
// 生成随机验证码
Random random = new Random();
// 随机的四个字符
String num = getRandomNum();
// 把验证码放入当前会话,注册的时候需要先校验
req.getSession().setAttribute(Constant.VERIFYCODE, num);
// 画出验证码
gh.drawString(String.valueOf(num), 6, 20);
// 加上干扰
gh.drawLine(0, random.nextInt(height), width, random.nextInt(height));
gh.drawLine(0, random.nextInt(height), width, random.nextInt(height));
gh.drawLine(0, random.nextInt(height), width, random.nextInt(height));
ImageIO.write(bi, "JPEG", resp.getOutputStream());
}
private String getRandomNum() {
List<Object> list = new ArrayList<Object>();
for (char i = 'a'; i <= 'z'; i++) {
list.add(i);
}
for (char i = 'A'; i <= 'Z'; i++) {
list.add(i);
}
for (int i = 0; i < 10; i++) {
list.add(i);
}
// 随机取出四个元素以返回
StringBuffer sb = new StringBuffer();
Random random = new Random();
for (int i = 0; i < 4; i++) {
sb.append(list.get(random.nextInt(list.size())));
}
return sb.toString();
}
}
生成验证码操作
最新推荐文章于 2024-09-10 17:20:04 发布