生成验证码操作

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();
    }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值